<?php
// إعدادات الـ Headers للسماح بالاتصال
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

$method = $_SERVER['REQUEST_METHOD'];
$store = isset($_GET['store']) ? $_GET['store'] : '';
$id = isset($_GET['id']) ? (int)$_GET['id'] : null;

if (!$store) {
    http_response_code(400);
    echo json_encode(["error" => "Invalid store"]);
    exit;
}

$valid_stores = [
    'users', 'warehouses', 'items', 'projects', 'transactions',
    'notifications', 'contacts', 'units', 'accounts',
    'journal_entries', 'activity_logs', 'subcontracts',
    'subcontract_abstracts', 'client_abstracts', 'settings',
    'client_contracts', 'client_abstracts_new', 'sub_contracts', 'sub_abstracts',
    'employees', 'advances', 'payrolls', 'custody_requests', 'settlements',
    'mixers', 'pumps', 'equipments', 'concrete_invoices', 'invoice_mixer_trips', 'pos_archive'
];

function update_store_version($storeName) {
    $versionFile = 'db_version.json';
    $versions = [];
    if (file_exists($versionFile)) {
        $versions = json_decode(file_get_contents($versionFile), true) ?: [];
    }
    // Update the store and the global _all timestamp
    $versions[$storeName] = time();
    $versions['_all'] = time();
    file_put_contents($versionFile, json_encode($versions));
}

if (!in_array($store, $valid_stores) && $store !== 'multi' && $store !== 'all_data' && $store !== 'process_concrete_batch' && $store !== 'concrete_invoice_details' && $store !== 'get_bulk_attendance' && $store !== 'save_bulk_attendance' && $store !== 'get_monthly_absences' && $store !== 'get_employee_absences' && $store !== 'patch_mixers_db' && $store !== 'versions' && $store !== 'update_notes') {
    http_response_code(400);
    echo json_encode(["error" => "Invalid store"]);
    exit;
}

// ==========================================
// UPDATE NOTES ONLY - Safe endpoint that modifies ONLY the notes field
// No journals, no inventory, no notifications, no side effects
// ==========================================
if ($store === 'update_notes' && $method === 'POST') {
    try {
        $input = json_decode(file_get_contents('php://input'), true);
        $target_store = isset($input['target_store']) ? $input['target_store'] : 'transactions';
        $record_id = isset($input['id']) ? (int)$input['id'] : null;
        $new_notes = isset($input['notes']) ? $input['notes'] : '';
        
        if (!$record_id || !in_array($target_store, $valid_stores)) {
            http_response_code(400);
            echo json_encode(["error" => "Missing id or invalid store"]);
            exit;
        }
        
        // Read existing record
        $stmt = $db->prepare("SELECT data FROM $target_store WHERE id = ?");
        $stmt->execute([$record_id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$row) {
            http_response_code(404);
            echo json_encode(["error" => "Record not found"]);
            exit;
        }
        
        // Parse existing JSON, update ONLY notes field
        $data = json_decode($row['data'], true);
        if (!is_array($data)) {
            http_response_code(500);
            echo json_encode(["error" => "Invalid data format"]);
            exit;
        }
        
        $data['notes'] = $new_notes;
        $updatedJson = json_encode($data, JSON_UNESCAPED_UNICODE);
        
        // Write back
        $upd = $db->prepare("UPDATE $target_store SET data = ? WHERE id = ?");
        $upd->execute([$updatedJson, $record_id]);
        
        update_store_version($target_store);
        
        echo json_encode(["success" => true, "message" => "Notes updated successfully", "id" => $record_id]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(["error" => $e->getMessage()]);
    }
    exit;
}

if ($store === 'multi') {
    $requested = isset($_GET['stores']) ? explode(',', $_GET['stores']) : [];
    $multi_data = [];
    try {
        $db_temp = new PDO("sqlite:database.sqlite");
        $db_temp->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        foreach ($requested as $s) {
            if (in_array($s, $valid_stores)) {
                $db_temp->exec("CREATE TABLE IF NOT EXISTS $s (id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT)");
                
                // --- Default data initialization for users and warehouses ---
                if ($s == 'users' || $s == 'warehouses') {
                    $stmtCount = $db_temp->query("SELECT COUNT(*) as count FROM $s");
                    $rowCount = $stmtCount->fetch(PDO::FETCH_ASSOC);
                    if ($rowCount['count'] == 0) {
                        if ($s == 'users') {
                            $admin = json_encode(["username"=>"admin", "password"=>"123", "role"=>"مدير نظام", "warehouse_id"=>null], JSON_UNESCAPED_UNICODE);
                            $db_temp->exec("INSERT INTO users (data) VALUES ('$admin')");
                        } else if ($s == 'warehouses') {
                            $wh = json_encode(["name"=>"مخزن رئيسي", "location"=>"المقر الرئيسي"], JSON_UNESCAPED_UNICODE);
                            $db_temp->exec("INSERT INTO warehouses (data) VALUES ('$wh')");
                        }
                    }
                }
                // ------------------------------------------------------------
                
                $stmt = $db_temp->query("SELECT id, data FROM $s");
                $store_data = [];
                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    $jd = json_decode($row['data'], true);
                    if(is_array($jd)) {
                        $jd['id'] = $row['id'];
                        $store_data[] = $jd;
                    }
                }
                $multi_data[$s] = $store_data;
            }
        }
        echo json_encode($multi_data);
    } catch(Exception $e) {
        echo json_encode(["error" => $e->getMessage()]);
    }
    exit;
}

if ($store === 'patch_mixers_db') {
    try {
        $db->exec("ALTER TABLE mixers ADD COLUMN driver_token TEXT UNIQUE;");
    } catch(Exception $e) {}
    try {
        $db->exec("ALTER TABLE mixers ADD COLUMN status TEXT DEFAULT 'active';");
    } catch(Exception $e) {}
    try {
        $db->exec("ALTER TABLE mixers ADD COLUMN breakdown_notes TEXT;");
    } catch(Exception $e) {}
    
    $stmt = $db->query("SELECT id, data FROM mixers WHERE driver_token IS NULL OR driver_token = ''");
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $token = bin2hex(random_bytes(16));
        $update = $db->prepare("UPDATE mixers SET driver_token = ? WHERE id = ?");
        $update->execute([$token, $row['id']]);
        if (!empty($row['data'])) {
            $jsonData = json_decode($row['data'], true);
            if (is_array($jsonData)) {
                $jsonData['driver_token'] = $token;
                $updateData = $db->prepare("UPDATE mixers SET data = ? WHERE id = ?");
                $updateData->execute([json_encode($jsonData), $row['id']]);
            }
        }
    }
    echo json_encode(["status" => "patched"]);
    exit;
}

// الاتصال بقاعدة بيانات SQLite (سيتم إنشاء الملف database.sqlite تلقائياً)
try {
    $db = new PDO("sqlite:database.sqlite");
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Auto-patch mixers table for new features (Magic Link)
    try { $db->exec("ALTER TABLE mixers ADD COLUMN driver_token TEXT"); } catch(Exception $e) {}
    try { $db->exec("ALTER TABLE mixers ADD COLUMN status TEXT DEFAULT 'active'"); } catch(Exception $e) {}
    try { $db->exec("ALTER TABLE mixers ADD COLUMN breakdown_notes TEXT"); } catch(Exception $e) {}
    
    // Auto-generate tokens for any existing mixer that doesn't have one
    try {
        $stmt = $db->query("SELECT id, data, driver_token FROM mixers WHERE driver_token IS NULL OR driver_token = ''");
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $newToken = bin2hex(random_bytes(16));
            $jd = json_decode($row['data'], true);
            if (is_array($jd)) {
                $jd['driver_token'] = $newToken;
                $upd = $db->prepare("UPDATE mixers SET driver_token = ?, data = ? WHERE id = ?");
                $upd->execute([$newToken, json_encode($jd, JSON_UNESCAPED_UNICODE), $row['id']]);
            }
        }
    } catch(Exception $e) {}
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(["error" => "Database connection failed: " . $e->getMessage()]);
    exit;
}

// ==========================================
// BULK ATTENDANCE LOGIC
// ==========================================
if ($store === 'get_bulk_attendance' && $method === 'GET') {
    $date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
    
    // Ensure table exists
    $db->exec("CREATE TABLE IF NOT EXISTS daily_attendance (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        employee_id INTEGER NOT NULL,
        date DATE NOT NULL,
        status TEXT NOT NULL,
        notes TEXT,
        UNIQUE(employee_id, date)
    )");

    // Since employees are stored as JSON in 'data' column, we fetch them first
    $stmt = $db->query("SELECT id, data FROM employees");
    $emps = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $empData = json_decode($row['data'], true);
        if (isset($empData['status']) && $empData['status'] === 'active') {
            $emps[] = [
                'employee_id' => $row['id'],
                'name' => $empData['name'] ?? 'Unknown',
                'project_id' => $empData['project_id'] ?? null
            ];
        }
    }

    // Now fetch attendance for that date
    $attStmt = $db->prepare("SELECT employee_id, status, notes FROM daily_attendance WHERE date = ?");
    $attStmt->execute([$date]);
    $attendanceData = [];
    while ($row = $attStmt->fetch(PDO::FETCH_ASSOC)) {
        $attendanceData[$row['employee_id']] = [
            'status' => $row['status'],
            'notes' => $row['notes']
        ];
    }

    // Merge
    $result = [];
    foreach ($emps as $emp) {
        $eid = $emp['employee_id'];
        if (isset($attendanceData[$eid])) {
            $emp['status'] = $attendanceData[$eid]['status'];
            $emp['notes'] = $attendanceData[$eid]['notes'];
            $emp['is_new'] = false;
        } else {
            $emp['status'] = 'حضور'; // Default
            $emp['notes'] = '';
            $emp['is_new'] = true;
        }
        $result[] = $emp;
    }

    echo json_encode($result);
    exit;
}

if ($store === 'save_bulk_attendance' && $method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    if (!$input || !isset($input['date']) || !isset($input['records'])) {
        http_response_code(400);
        echo json_encode(["error" => "Invalid payload"]);
        exit;
    }

    $date = $input['date'];
    $records = $input['records'];

    $db->exec("CREATE TABLE IF NOT EXISTS daily_attendance (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        employee_id INTEGER NOT NULL,
        date DATE NOT NULL,
        status TEXT NOT NULL,
        notes TEXT,
        UNIQUE(employee_id, date)
    )");

    try {
        $db->beginTransaction();
        $stmtCheck = $db->prepare("SELECT id FROM daily_attendance WHERE employee_id = ? AND date = ?");
        $stmtUpdate = $db->prepare("UPDATE daily_attendance SET status = ?, notes = ? WHERE id = ?");
        $stmtInsert = $db->prepare("INSERT INTO daily_attendance (employee_id, date, status, notes) VALUES (?, ?, ?, ?)");
        
        foreach ($records as $rec) {
            $stmtCheck->execute([$rec['employee_id'], $date]);
            $existing = $stmtCheck->fetch(PDO::FETCH_ASSOC);
            
            if ($existing) {
                $stmtUpdate->execute([
                    $rec['status'],
                    $rec['notes'] ?? '',
                    $existing['id']
                ]);
            } else {
                $stmtInsert->execute([
                    $rec['employee_id'],
                    $date,
                    $rec['status'],
                    $rec['notes'] ?? ''
                ]);
            }
        }
        $db->commit();
        echo json_encode(["success" => true, "message" => "تم حفظ الحضور والانصراف بنجاح"]);
    } catch (Exception $e) {
        $db->rollBack();
        http_response_code(500);
        echo json_encode(["error" => "Failed to save: " . $e->getMessage()]);
    }
    exit;
}

if ($store === 'get_monthly_absences' && $method === 'GET') {
    $month = isset($_GET['month']) ? $_GET['month'] : date('Y-m'); // format YYYY-MM
    
    // Ensure table exists just in case
    $db->exec("CREATE TABLE IF NOT EXISTS daily_attendance (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        employee_id INTEGER NOT NULL,
        date DATE NOT NULL,
        status TEXT NOT NULL,
        notes TEXT,
        UNIQUE(employee_id, date)
    )");

    $stmt = $db->prepare("SELECT employee_id, COUNT(*) as abs_count FROM daily_attendance WHERE status = 'غياب' AND date LIKE ? GROUP BY employee_id");
    $stmt->execute([$month . '%']);
    
    $data = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $data[$row['employee_id']] = (int)$row['abs_count'];
    }
    
    echo json_encode($data);
    exit;
}

if ($store === 'get_employee_absences' && $method === 'GET') {
    $emp_id = isset($_GET['emp_id']) ? (int)$_GET['emp_id'] : 0;
    $month = isset($_GET['month']) ? $_GET['month'] : '';
    
    // Ensure table exists just in case
    $db->exec("CREATE TABLE IF NOT EXISTS daily_attendance (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        employee_id INTEGER NOT NULL,
        date DATE NOT NULL,
        status TEXT NOT NULL,
        notes TEXT,
        UNIQUE(employee_id, date)
    )");

    if ($month) {
        $stmt = $db->prepare("SELECT date, status, notes FROM daily_attendance WHERE employee_id = ? AND date LIKE ? ORDER BY date DESC");
        $stmt->execute([$emp_id, $month . '%']);
    } else {
        $stmt = $db->prepare("SELECT date, status, notes FROM daily_attendance WHERE employee_id = ? ORDER BY date DESC");
        $stmt->execute([$emp_id]);
    }
    
    $data = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $data[] = $row;
    }
    
    echo json_encode($data);
    exit;
}

// ==========================================
// CONCRETE BATCH PROCESSING LOGIC
// ==========================================
if ($store === 'process_concrete_batch' && $method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    if (!$input) {
        http_response_code(400);
        echo json_encode(["error" => "Invalid JSON payload"]);
        exit;
    }

    $db->exec("CREATE TABLE IF NOT EXISTS concrete_invoices (id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT NOT NULL)");
    $db->exec("CREATE TABLE IF NOT EXISTS invoice_mixer_trips (id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT NOT NULL)");

    try {
        $db->beginTransaction();

        $target_id = $input['target_id'] ?? null;
        $client_type = $input['client_type'] ?? ''; // 'project' or 'contact'
        $mix_item_id = $input['mix_item_id'] ?? null;
        $pump_id = $input['pump_id'] ?? null;
        $pump_operator_id = $input['pump_operator_id'] ?? null;
        $total_qty = (float)($input['total_qty'] ?? 0);
        $billed_qty = (float)($input['billed_qty'] ?? $total_qty);
        $diesel_qty = (float)($input['diesel_qty'] ?? 0);
        $warehouse_id = $input['warehouse_id'] ?? null;
        $trips_array = $input['trips_array'] ?? [];
        $costs_map = $input['costs_map'] ?? [];
        $date = $input['date'] ?? date('Y-m-d H:i:s');

        if (!$target_id || !$mix_item_id || $total_qty <= 0 || !$warehouse_id) {
            throw new Exception("Missing required fields for concrete batch.");
        }

        // 1. Fetch the BOM and mapping
        $stmt = $db->query("SELECT id, data FROM items");
        $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $mix_item = null;
        $items_map = [];
        foreach ($items as $row) {
            $d = json_decode($row['data'], true);
            $items_map[$row['id']] = $d['name'] ?? "غير معروف";
            if ($row['id'] == $mix_item_id) {
                $mix_item = $d;
            }
        }

        if (!$mix_item) {
            throw new Exception("Mix design item not found.");
        }

        // Fetch warehouse name
        $warehouse_name = "مخزن محطة";
        $wh_stmt = $db->query("SELECT id, data FROM warehouses");
        foreach ($wh_stmt->fetchAll(PDO::FETCH_ASSOC) as $wh_row) {
            if ($wh_row['id'] == $warehouse_id) {
                $wh_data = json_decode($wh_row['data'], true);
                $warehouse_name = $wh_data['name'] ?? 'مخزن محطة';
                break;
            }
        }

        $components = $mix_item['bom'] ?? [];
        $total_material_cost = 0;
        $items_array = [];

        $extra_items = $input['extra_items'] ?? [];

        foreach ($components as $comp) {
            $comp_id = $comp['item_id'];
            $ratio = (float)($comp['qty'] ?? 0);
            $deduction_qty = $ratio * $total_qty;

            $cost_per_unit = isset($costs_map[$comp_id]) ? (float)$costs_map[$comp_id] : (isset($comp['cost']) ? (float)$comp['cost'] : 0);
            $line_cost = $deduction_qty * $cost_per_unit;
            $total_material_cost += $line_cost;

            $items_array[] = [
                "item_id" => $comp_id,
                "item_name" => $items_map[$comp_id] ?? $comp['item_name'] ?? "مادة رقم $comp_id",
                "qty" => $deduction_qty,
                "price" => $cost_per_unit,
                "unit" => $comp['unit'] ?? ""
            ];
        }

        foreach ($extra_items as $extra) {
            $extra_id = $extra['item_id'];
            $extra_qty = (float)($extra['qty'] ?? 0);
            if ($extra_id && $extra_qty > 0) {
                $extra_cost_unit = isset($costs_map[$extra_id]) ? (float)$costs_map[$extra_id] : 0;
                $extra_line_cost = $extra_qty * $extra_cost_unit;
                $total_material_cost += $extra_line_cost;

                $items_array[] = [
                    "item_id" => $extra_id,
                    "item_name" => $items_map[$extra_id] ?? "صنف إضافي $extra_id",
                    "qty" => $extra_qty,
                    "price" => $extra_cost_unit,
                    "unit" => ""
                ];
            }
        }

        // 2. Backflushing (Unified Inventory Document)
        $transaction_stmt = $db->prepare("INSERT INTO transactions (data) VALUES (:data)");
        
        $trans_data = json_encode([
            "type" => "manufacture",
            "date" => $date,
            "from_warehouse_id" => $warehouse_id,
            "from_warehouse_name" => $warehouse_name,
            "product_id" => (int)$mix_item_id,
            "produced_item_name" => "خرسانة جاهزة " . ($mix_item['name'] ?? ''),
            "produced_qty" => $total_qty,
            "produced_cost" => $total_material_cost,
            "to_warehouse_id" => null,
            "status" => "posted",
            "user_id" => $input['user_id'] ?? null,
            "user" => $input['user_name'] ?? 'النظام',
            "items" => $items_array,
            "notes" => "إنتاج وصرف خرسانة: $total_qty م٣ للخلطة $mix_item_id"
        ], JSON_UNESCAPED_UNICODE);
        
        $transaction_stmt->execute([':data' => $trans_data]);

        // 3. Routing Logic (Internal vs External)
        $is_internal = ($client_type === 'project'); // If it's a project, it's internal. If contact, external.
        
        $invoice_data = [
            "target_id" => $target_id,
            "client_type" => $client_type,
            "mix_item_id" => $mix_item_id,
            "pump_id" => $pump_id,
            "pump_operator_id" => $pump_operator_id,
            "total_qty" => $total_qty,
            "billed_qty" => $billed_qty,
            "diesel_qty" => $diesel_qty,
            "warehouse_id" => $warehouse_id,
            "date" => $date,
            "total_cost" => $total_material_cost,
            "is_internal" => $is_internal,
            "extra_items" => $extra_items
        ];

        // Fetch target name for journal entries
        $target_name = "مجهول";
        $target_table = $is_internal ? "projects" : "contacts";
        $t_stmt = $db->query("SELECT id, data FROM $target_table");
        foreach ($t_stmt->fetchAll(PDO::FETCH_ASSOC) as $t_row) {
            if ($t_row['id'] == $target_id) {
                $t_data = json_decode($t_row['data'], true);
                $target_name = $t_data['name'] ?? 'مجهول';
                break;
            }
        }

        // Helper function for dynamic accounts
        $accounts_map = [];
        $acc_stmt = $db->query("SELECT id, data FROM accounts");
        foreach ($acc_stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
            $d = json_decode($row['data'], true);
            if (!empty($d['name'])) {
                $accounts_map[$d['name']] = $row['id'];
            }
        }

        $inv_acc_id = $accounts_map['مخزون الخامات'] ?? ($accounts_map['المخزون'] ?? null);
        $proj_acc_id = $accounts_map['مشروعات تحت التنفيذ'] ?? ($accounts_map['تكلفة المشاريع'] ?? null);
        $client_acc_id = $accounts_map['العملاء'] ?? ($accounts_map['حسابات العملاء'] ?? null);
        $rev_acc_id = $accounts_map['إيرادات الخرسانة'] ?? ($accounts_map['إيرادات المبيعات'] ?? ($accounts_map['الإيرادات'] ?? ($accounts_map['المبيعات'] ?? null)));
        $cogs_acc_id = $accounts_map['تكلفة مبيعات الخرسانة'] ?? ($accounts_map['تكلفة البضاعة المباعة'] ?? ($accounts_map['تكلفة المبيعات'] ?? null));

        $journal_stmt = $db->prepare("INSERT INTO journal_entries (data) VALUES (:data)");
        
        if ($is_internal) {
            $invoice_data['type'] = 'توريد داخلي';
            $invoice_data['status'] = 'مسجل';

            if ($proj_acc_id && $inv_acc_id) {
                $je_data = json_encode([
                    "date" => $date,
                    "reference" => "خرسانة",
                    "desc" => "تكلفة خامات خرسانة لمحطة/مشروع: $target_name",
                    "status" => "draft",
                    "total" => $total_material_cost,
                    "rows" => [
                        [ "account_id" => $proj_acc_id, "debit" => $total_material_cost, "credit" => 0, "project_id" => $target_id, "contact_id" => null, "notes" => "تكلفة خامات خرسانة مشروع: $target_name" ],
                        [ "account_id" => $inv_acc_id, "debit" => 0, "credit" => $total_material_cost, "project_id" => null, "contact_id" => null, "notes" => "منصرف مخزون لمشروع: $target_name" ]
                    ]
                ], JSON_UNESCAPED_UNICODE);
                $journal_stmt->execute([':data' => $je_data]);
            }
        } else {
            $invoice_data['type'] = 'فاتورة مبيعات';
            $invoice_data['status'] = 'غير مسددة';
            
            $selling_price = isset($input['selling_price']) ? (float)$input['selling_price'] : (isset($mix_item['price']) ? (float)$mix_item['price'] : 0);
            $tax_percent = isset($input['tax']) ? (float)$input['tax'] : 0;
            
            $subtotal = $selling_price * $billed_qty;
            $tax_amount = $subtotal * ($tax_percent / 100);
            $total_revenue = $subtotal + $tax_amount;
            
            $invoice_data['total_revenue'] = $total_revenue;

            $sales_invoice_data = json_encode([
                "type" => "sales",
                "date" => $date,
                "contact_id" => $target_id,
                "contact_name" => $target_name,
                "from_warehouse_id" => $warehouse_id,
                "status" => "posted",
                "amount" => $subtotal,
                "tax_rate" => $tax_percent,
                "tax_amount" => $tax_amount,
                "total" => $total_revenue,
                "paid_amount" => 0,
                "items" => [
                    [
                        "item_id" => $mix_item_id,
                        "item_name" => "خرسانة جاهزة " . ($mix_item['name'] ?? ''),
                        "qty" => $billed_qty,
                        "price" => $selling_price,
                        "discount" => 0,
                        "discountType" => "value",
                        "total" => $subtotal
                    ]
                ],
                "notes" => "فاتورة مبيعات خرسانة للعميل: $target_name"
            ], JSON_UNESCAPED_UNICODE);
            $transaction_stmt->execute([':data' => $sales_invoice_data]);

            $tax_acc_id = null;
            foreach ($accounts_map as $name => $id) {
                if (mb_strpos($name, 'ضريب') !== false || mb_strpos($name, 'ضرائب') !== false) {
                    $tax_acc_id = $id;
                    break;
                }
            }

            if ($client_acc_id && $rev_acc_id) {
                $je_rows = [
                    [ "account_id" => $client_acc_id, "debit" => $total_revenue, "credit" => 0, "project_id" => null, "contact_id" => $target_id, "notes" => "قيمة مبيعات خرسانة للعميل: $target_name" ],
                    [ "account_id" => $rev_acc_id, "debit" => 0, "credit" => $subtotal, "project_id" => null, "contact_id" => null, "notes" => "إيراد مبيعات خرسانة" ]
                ];
                
                if ($tax_amount > 0 && $tax_acc_id) {
                    $je_rows[] = [ "account_id" => $tax_acc_id, "debit" => 0, "credit" => $tax_amount, "project_id" => null, "contact_id" => null, "notes" => "ضريبة مبيعات خرسانة" ];
                }

                $je_rev_data = json_encode([
                    "date" => $date,
                    "reference" => "خرسانة",
                    "desc" => "إيراد مبيعات خرسانة للعميل: $target_name",
                    "status" => "posted",
                    "total" => $total_revenue,
                    "rows" => $je_rows
                ], JSON_UNESCAPED_UNICODE);
                $journal_stmt->execute([':data' => $je_rev_data]);
            }

            if ($cogs_acc_id && $inv_acc_id) {
                $je_cost_data = json_encode([
                    "date" => $date,
                    "reference" => "خرسانة",
                    "desc" => "تكلفة مبيعات خرسانة للعميل: $target_name",
                    "status" => "posted",
                    "total" => $total_material_cost,
                    "rows" => [
                        [ "account_id" => $cogs_acc_id, "debit" => $total_material_cost, "credit" => 0, "project_id" => null, "contact_id" => null, "notes" => "تكلفة بضاعة مباعة مبيعات خرسانة" ],
                        [ "account_id" => $inv_acc_id, "debit" => 0, "credit" => $total_material_cost, "project_id" => null, "contact_id" => null, "notes" => "منصرف مخزون مبيعات خرسانة" ]
                    ]
                ], JSON_UNESCAPED_UNICODE);
                $journal_stmt->execute([':data' => $je_cost_data]);
            }
        }

        // Fix remaining concrete balance in warehouse
        $qty_to_deduct = $is_internal ? $total_qty : ($total_qty - $billed_qty);
        if ($qty_to_deduct > 0) {
            $waste_transaction = json_encode([
                "type" => "out",
                "date" => $date,
                "from_warehouse_id" => $warehouse_id,
                "from_warehouse_name" => $warehouse_name,
                "status" => "posted",
                "user" => $input['user_name'] ?? 'النظام',
                "items" => [
                    [
                        "item_id" => $mix_item_id,
                        "item_name" => "تسوية خرسانة جاهزة " . ($mix_item['name'] ?? ''),
                        "qty" => $qty_to_deduct,
                        "price" => 0,
                        "total" => 0
                    ]
                ],
                "notes" => $is_internal ? "صرف خرسانة لمشروع داخلي: $target_name" : "تسوية هالك خرسانة متبقي: $target_name"
            ], JSON_UNESCAPED_UNICODE);
            $transaction_stmt->execute([':data' => $waste_transaction]);
        }

        // Save Invoice / Transfer Document
        $inv_stmt = $db->prepare("INSERT INTO concrete_invoices (data) VALUES (:data)");
        $inv_stmt->execute([':data' => json_encode($invoice_data, JSON_UNESCAPED_UNICODE)]);
        $new_invoice_id = $db->lastInsertId();

        // 4. Save Mixer Trips
        $trip_stmt = $db->prepare("INSERT INTO invoice_mixer_trips (data) VALUES (:data)");
        foreach ($trips_array as $trip) {
            $trip_data = json_encode([
                "concrete_invoice_id" => $new_invoice_id,
                "mixer_id" => $trip['mixer_id'],
                "driver_id" => $trip['driver_id'] ?? null,
                "trips_count" => (int)($trip['trips_count'] ?? 1),
                "date" => $date
            ], JSON_UNESCAPED_UNICODE);
            $trip_stmt->execute([':data' => $trip_data]);
        }
        update_store_version('concrete_invoices');
        update_store_version('invoice_mixer_trips');
        update_store_version('transactions');
        update_store_version('journal_entries');
        
        $db->commit();
        echo json_encode(["status" => "success", "invoice_id" => $new_invoice_id, "message" => "تم معالجة فاتورة الخرسانة والمخازن بنجاح"]);

    } catch (Exception $ex) {
        $db->rollBack();
        http_response_code(500);
        echo json_encode(["error" => "Transaction failed: " . $ex->getMessage()]);
    }
    exit;
}
// ==========================================
// إنشاء الجدول إذا لم يكن موجوداً
$db->exec("CREATE TABLE IF NOT EXISTS $store (id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT NOT NULL)");

// إضافة البيانات الافتراضية (مدير عام ومخزن رئيسي) إذا كانت القاعدة فارغة
if ($store == 'users' || $store == 'warehouses') {
    $stmt = $db->query("SELECT COUNT(*) as count FROM $store");
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($row['count'] == 0) {
        if ($store == 'users') {
            $admin = json_encode(["username"=>"admin", "password"=>"123", "role"=>"مدير عام", "warehouse_id"=>null], JSON_UNESCAPED_UNICODE);
            $db->exec("INSERT INTO users (data) VALUES ('$admin')");
        } else if ($store == 'warehouses') {
            $wh = json_encode(["name"=>"المخزن الرئيسي", "location"=>"المقر الرئيسي"], JSON_UNESCAPED_UNICODE);
            $db->exec("INSERT INTO warehouses (data) VALUES ('$wh')");
        }
    }
}

// استقبال البيانات المرسلة من المتصفح
$input = json_decode(file_get_contents('php://input'), true);

// استخراج بيانات المستخدم من الـ Headers مع فك التشفير
$username = isset($_SERVER['HTTP_X_USERNAME']) ? urldecode($_SERVER['HTTP_X_USERNAME']) : 'System';
$user_id = isset($_SERVER['HTTP_X_USER_ID']) ? $_SERVER['HTTP_X_USER_ID'] : '0';

// دالة لتسجيل الحركات (Audit Log)
function logActivity($db, $store, $action, $record_id, $details, $user_id, $username) {
    if ($store === 'activity_logs' || $store === 'notifications') return; 
    
    // تأكد من وجود جدول السجل
    $db->exec("CREATE TABLE IF NOT EXISTS activity_logs (id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT NOT NULL)");
    
    $log_data = json_encode([
        "timestamp" => date('Y-m-d H:i:s'),
        "user_id" => $user_id,
        "username" => $username,
        "action" => $action,
        "store" => $store,
        "record_id" => $record_id,
        "details" => $details
    ], JSON_UNESCAPED_UNICODE);
    
    $stmt = $db->prepare("INSERT INTO activity_logs (data) VALUES (?)");
    $stmt->execute([$log_data]);
}

if ($method == 'GET') {
    if ($store === 'versions') {
        $versionFile = 'db_version.json';
        if (file_exists($versionFile)) {
            echo file_get_contents($versionFile);
        } else {
            echo json_encode(['_all' => 0]);
        }
        exit;
    }

    if ($store === 'all_data') {
        $all_data = [];
        foreach ($valid_stores as $s) {
            // Ensure table exists safely
            $db->exec("CREATE TABLE IF NOT EXISTS $s (id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT NOT NULL)");
            if ($s === 'activity_logs') {
                $stmt = $db->query("SELECT id, data FROM $s ORDER BY id DESC LIMIT 200");
            } else if ($s === 'notifications') {
                $stmt = $db->query("SELECT id, data FROM $s ORDER BY id DESC LIMIT 100");
            } else {
                $stmt = $db->query("SELECT id, data FROM $s");
            }
            $store_data = [];
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $data = json_decode($row['data'], true);
                if(is_array($data)) {
                    $data['id'] = $row['id'];
                    $store_data[] = $data;
                }
            }
            $all_data[$s] = $store_data;
        }
        echo json_encode($all_data);
        exit;
    }

    if ($store === 'concrete_invoice_details' && $id) {
        $response = [];
        
        $q1 = "SELECT id, data FROM concrete_invoices WHERE id = ?";
        $stmt1 = $db->prepare($q1);
        $stmt1->execute([$id]);
        $row = $stmt1->fetch(PDO::FETCH_ASSOC);

        if (!$row) {
            http_response_code(404);
            echo json_encode(["error" => "Order not found"]);
            exit;
        }

        $orderData = json_decode($row['data'], true);
        
        $orderInfo = [
            'order_id' => $row['id'],
            'order_date' => $orderData['date'] ?? '',
            'total_qty' => $orderData['total_qty'] ?? 0,
            'billed_qty' => $orderData['billed_qty'] ?? ($orderData['total_qty'] ?? 0),
            'mix_item_id' => $orderData['mix_item_id'] ?? null,
            'pump_id' => $orderData['pump_id'] ?? null,
            'extra_items' => $orderData['extra_items'] ?? [],
            'target_id' => $orderData['target_id'] ?? null,
            'client_type' => $orderData['client_type'] ?? '',
            'total_cost' => $orderData['total_cost'] ?? 0,
            'total_revenue' => $orderData['total_revenue'] ?? 0
        ];

        // Fetch Pump Name
        $orderInfo['pump_name'] = 'بدون مضخة';
        $orderInfo['pump_code'] = '';
        if ($orderInfo['pump_id']) {
            $ps = $db->prepare("SELECT data FROM pumps WHERE id = ?");
            $ps->execute([$orderInfo['pump_id']]);
            if ($pRow = $ps->fetch(PDO::FETCH_ASSOC)) {
                $pData = json_decode($pRow['data'], true);
                $orderInfo['pump_name'] = $pData['name'] ?? '';
                $orderInfo['pump_code'] = $pData['code'] ?? '';
            }
        }

        // Fetch Client Info
        $orderInfo['client_name'] = 'غير محدد';
        $orderInfo['project_location'] = 'غير محدد';
        
        if ($orderInfo['client_type'] === 'project' && $orderInfo['target_id']) {
            $ps = $db->prepare("SELECT data FROM projects WHERE id = ?");
            $ps->execute([$orderInfo['target_id']]);
            if ($ptRow = $ps->fetch(PDO::FETCH_ASSOC)) {
                $ptData = json_decode($ptRow['data'], true);
                $orderInfo['client_name'] = $ptData['name'] ?? 'مشروع غير معروف';
                $orderInfo['project_location'] = $ptData['location'] ?? 'غير محدد';
            }
        } elseif ($orderInfo['client_type'] === 'contact' && $orderInfo['target_id']) {
            $ps = $db->prepare("SELECT data FROM contacts WHERE id = ?");
            $ps->execute([$orderInfo['target_id']]);
            if ($ptRow = $ps->fetch(PDO::FETCH_ASSOC)) {
                $ptData = json_decode($ptRow['data'], true);
                $orderInfo['client_name'] = $ptData['name'] ?? 'عميل غير معروف';
                $orderInfo['project_location'] = $ptData['address'] ?? 'غير محدد';
            }
        }

        // Fetch Trips
        $q2 = "SELECT id, data FROM invoice_mixer_trips";
        $stmt2 = $db->query($q2);
        $allTrips = [];
        while ($tRow = $stmt2->fetch(PDO::FETCH_ASSOC)) {
            $tData = json_decode($tRow['data'], true);
            if (isset($tData['concrete_invoice_id']) && (string)($tData['concrete_invoice_id']) === (string)($id)) {
                $tData['trip_record_id'] = $tRow['id'];
                
                // Fetch Mixer Code
                $tData['mixer_code'] = '';
                if (!empty($tData['mixer_id'])) {
                    $ms = $db->prepare("SELECT data FROM mixers WHERE id = ?");
                    $ms->execute([$tData['mixer_id']]);
                    if ($mRow = $ms->fetch(PDO::FETCH_ASSOC)) {
                        $mData = json_decode($mRow['data'], true);
                        $tData['mixer_code'] = $mData['code'] ?? '';
                    }
                }
                
                // Fetch Driver Name
                $tData['driver_name'] = '';
                if (!empty($tData['driver_id'])) {
                    $ds = $db->prepare("SELECT data FROM employees WHERE id = ?");
                    $ds->execute([$tData['driver_id']]);
                    if ($dRow = $ds->fetch(PDO::FETCH_ASSOC)) {
                        $dData = json_decode($dRow['data'], true);
                        $tData['driver_name'] = $dData['name'] ?? '';
                    }
                }
                
                $allTrips[] = [
                    'trip_record_id' => $tData['trip_record_id'],
                    'trips_count' => $tData['trips_count'] ?? 1,
                    'mixer_code' => $tData['mixer_code'],
                    'driver_name' => $tData['driver_name']
                ];
            }
        }

        $response['orderInfo'] = $orderInfo;
        $response['trips'] = $allTrips;

        $cashExpenses = [];
        try {
            $ststmt = $db->query("SELECT data FROM transactions");
            while ($sRow = $ststmt->fetch(PDO::FETCH_ASSOC)) {
                $sData = json_decode($sRow['data'], true);
                if (isset($sData['type']) && ($sData['type'] === 'petty_cash_settlement' || $sData['type'] === 'settlement')) {
                    if (!empty($sData['items'])) {
                        foreach ($sData['items'] as $item) {
                            $savedOrderId = isset($item['concrete_order_id']) ? $item['concrete_order_id'] : (isset($item['batch_id']) ? $item['batch_id'] : null);
                            if ($savedOrderId == $id && $item['item_type'] === 'expense') {
                                $cashExpenses[] = [
                                    'description' => $item['expense_name'] ?? 'مصروف غير مسمى',
                                    'amount' => (float)($item['qty'] * $item['price']),
                                    'expense_date' => $sData['date'] ?? ''
                                ];
                            }
                        }
                    }
                }
            }
        } catch (Exception $e) { }
        $response['cashExpenses'] = $cashExpenses;

        echo json_encode($response, JSON_UNESCAPED_UNICODE);
        exit;
    }

    if ($id) {
        $stmt = $db->prepare("SELECT data FROM $store WHERE id = ?");
        $stmt->execute([$id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            $data = json_decode($row['data'], true);
            $data['id'] = $id;
            echo json_encode($data);
        } else {
            http_response_code(404);
            echo json_encode(["error" => "Not found"]);
        }
    } else {
        $stmt = $db->query("SELECT id, data FROM $store");
        $results = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $data = json_decode($row['data'], true);
            if(is_array($data)) {
                $data['id'] = $row['id']; // تأكيد أن الـ ID مطابق للجدول
                $results[] = $data;
            }
        }
        echo json_encode($results);
    }
} elseif ($method == 'POST') {
    // Inject token for new mixers
    $newToken = null;
    $status = 'active';
    $breakdown_notes = '';
    if ($store === 'mixers' && is_array($input)) {
        $newToken = bin2hex(random_bytes(16));
        $input['driver_token'] = $newToken;
        $status = isset($input['status']) ? $input['status'] : 'active';
        $breakdown_notes = isset($input['notes']) ? $input['notes'] : '';
    }

    $jsonStr = json_encode($input, JSON_UNESCAPED_UNICODE);
    
    if ($store === 'mixers') {
        $stmt = $db->prepare("INSERT INTO mixers (data, status, breakdown_notes, driver_token) VALUES (?, ?, ?, ?)");
        $stmt->execute([$jsonStr, $status, $breakdown_notes, $newToken]);
    } else {
        $stmt = $db->prepare("INSERT INTO $store (data) VALUES (?)");
        $stmt->execute([$jsonStr]);
    }
    
    $newId = $db->lastInsertId();
    
    if (is_array($input)) {
        $input['id'] = (int)$newId;
        $updatedJsonStr = json_encode($input, JSON_UNESCAPED_UNICODE);
        
        if ($store === 'mixers') {
            $updateStmt = $db->prepare("UPDATE mixers SET data = ?, status = ?, breakdown_notes = ?, driver_token = ? WHERE id = ?");
            $updateStmt->execute([$updatedJsonStr, $status, $breakdown_notes, $newToken, $newId]);
        } else {
            $updateStmt = $db->prepare("UPDATE $store SET data = ? WHERE id = ?");
            $updateStmt->execute([$updatedJsonStr, $newId]);
        }
    }
    
    // تسجيل الحركة
    logActivity($db, $store, 'إضافة', $newId, "تم إضافة عنصر جديد", $user_id, $username);
    
    update_store_version($store);
    
    http_response_code(201);
    echo json_encode(["id" => $newId, "message" => "Created successfully"]);
} elseif ($method == 'PUT') {
    if (!$id) {
        http_response_code(400);
        echo json_encode(["error" => "Missing ID"]);
        exit;
    }
    $input['id'] = $id;
    
    // Preserve token for mixers and update extra columns
    $existingToken = null;
    $status = 'active';
    $breakdown_notes = '';
    if ($store === 'mixers') {
        $ts = $db->prepare("SELECT driver_token FROM mixers WHERE id = ?");
        $ts->execute([$id]);
        $existingToken = $ts->fetchColumn();
        if (!$existingToken) $existingToken = bin2hex(random_bytes(16));
        
        $input['driver_token'] = $existingToken;
        $status = isset($input['status']) ? $input['status'] : 'active';
        $breakdown_notes = isset($input['notes']) ? $input['notes'] : '';
    }

    $jsonStr = json_encode($input, JSON_UNESCAPED_UNICODE);
    
    if ($store === 'mixers') {
        $stmt = $db->prepare("UPDATE mixers SET data = ?, status = ?, breakdown_notes = ?, driver_token = ? WHERE id = ?");
        $stmt->execute([$jsonStr, $status, $breakdown_notes, $existingToken, $id]);
    } else {
        $stmt = $db->prepare("UPDATE $store SET data = ? WHERE id = ?");
        $stmt->execute([$jsonStr, $id]);
    }
    
    // تسجيل الحركة
    logActivity($db, $store, 'تعديل', $id, "تم تعديل العنصر", $user_id, $username);
    
    update_store_version($store);
    
    echo json_encode(["success" => true, "message" => "Updated successfully"]);
} elseif ($method == 'DELETE') {
    if (!$id) {
        http_response_code(400);
        echo json_encode(["error" => "Missing ID"]);
        exit;
    }
    
    // جلب اسم أو تفاصيل العنصر قبل الحذف للتوثيق
    $stmtObj = $db->prepare("SELECT data FROM $store WHERE id = ?");
    $stmtObj->execute([$id]);
    $oldData = $stmtObj->fetch(PDO::FETCH_ASSOC);
    $oldName = "عنصر مجهول";
    if ($oldData) {
        $parsed = json_decode($oldData['data'], true);
        if (isset($parsed['name'])) $oldName = $parsed['name'];
        else if (isset($parsed['username'])) $oldName = $parsed['username'];
        else if (isset($parsed['desc'])) $oldName = $parsed['desc'];
    }
    
    $stmt = $db->prepare("DELETE FROM $store WHERE id = ?");
    $stmt->execute([$id]);
    
    // تسجيل الحركة
    logActivity($db, $store, 'حذف', $id, "تم حذف: " . $oldName, $user_id, $username);
    
    update_store_version($store);
    
    echo json_encode(["success" => true, "message" => "Deleted successfully"]);
}
?>
