<?php
// إعدادات الـ Headers للسماح بالاتصال
ini_set('display_errors', 1);
error_reporting(E_ALL);
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;
}


// ==========================================
// FCM Push Notification Logic
// ==========================================

if ($store === 'user_tokens' && $method === 'POST') {
    require_once 'db_config.php';
    try {
        $db->exec("CREATE TABLE IF NOT EXISTS user_tokens_v3 (id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(100), token TEXT)");
        $data = json_decode(file_get_contents("php://input"), true);
        if (isset($data['username']) && isset($data['token'])) {
            $user = $data['username'];
            $token = $data['token'];
            
            // Delete old token for same user if exists
            $stmt = $db->prepare("DELETE FROM user_tokens_v3 WHERE username = ? AND token = ?");
            $stmt->execute([$user, $token]);
            
            // Insert new token
            $stmt = $db->prepare("INSERT INTO user_tokens_v3 (username, token) VALUES (?, ?)");
            $stmt->execute([$user, $token]);
            
            echo json_encode(['success' => true]);
        }
    } catch(Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
    exit;
}

if ($store === 'send_push' && $method === 'POST') {
    require_once 'db_config.php';
    try {
        $data = json_decode(file_get_contents("php://input"), true);
        $user = $data['user'] ?? '';
        $title = $data['title'] ?? 'EasyERP';
        $body = $data['body'] ?? '';
        $link = $data['link'] ?? '';
        
        $stmt = $db->prepare("SELECT token FROM user_tokens_v3 WHERE username = ?");
        $stmt->execute([$user]);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if ($rows && count($rows) > 0) {
            $serviceAccountFile = __DIR__ . '/Firebase.json';
            
            if (!file_exists($serviceAccountFile)) {
                echo json_encode(['error' => 'Service account file missing']);
                exit;
            }
            
            $key_data = json_decode(file_get_contents($serviceAccountFile), true);
            $header = json_encode(['alg' => 'RS256', 'typ' => 'JWT']);
            $now = time();
            $payload = json_encode([
                'iss' => $key_data['client_email'],
                'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
                'aud' => $key_data['token_uri'],
                'exp' => $now + 3600,
                'iat' => $now
            ]);
            
            $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
            $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
            
            openssl_sign($base64UrlHeader . "." . $base64UrlPayload, $signature, $key_data['private_key'], "sha256WithRSAEncryption");
            $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
            
            $jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $key_data['token_uri']);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=' . $jwt);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($ch);
            curl_close($ch);
            $oauth = json_decode($response, true);
            $access_token = $oauth['access_token'] ?? '';
            
            if ($access_token) {
                $fcmUrl = 'https://fcm.googleapis.com/v1/projects/' . $key_data['project_id'] . '/messages:send';
                $fcmResponses = [];
                $successCount = 0;
                
                foreach ($rows as $row) {
                    $token = $row['token'];
                    if (empty($token)) continue;
                    
                    $fcmPayload = [
                        'message' => [
                            'token' => $token,
                            'notification' => [
                                'title' => $title,
                                'body' => $body
                            ],
                            'webpush' => [
                                'fcm_options' => [
                                    'link' => $link ? 'https://fatmyacab.com/easyerp/index.html' : 'https://fatmyacab.com/easyerp/index.html'
                                ]
                            ]
                        ]
                    ];
                    
                    $ch2 = curl_init();
                    curl_setopt($ch2, CURLOPT_URL, $fcmUrl);
                    curl_setopt($ch2, CURLOPT_POST, true);
                    curl_setopt($ch2, CURLOPT_HTTPHEADER, [
                        'Authorization: Bearer ' . $access_token,
                        'Content-Type: application/json'
                    ]);
                    curl_setopt($ch2, CURLOPT_POSTFIELDS, json_encode($fcmPayload));
                    curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
                    $fcmResponse = curl_exec($ch2);
                    curl_close($ch2);
                    $fcmDecoded = json_decode($fcmResponse, true);
                    
                    if (isset($fcmDecoded['error']) && isset($fcmDecoded['error']['details'])) {
                        foreach ($fcmDecoded['error']['details'] as $detail) {
                            if (isset($detail['errorCode']) && $detail['errorCode'] === 'UNREGISTERED') {
                                $delStmt = $db->prepare("DELETE FROM user_tokens_v3 WHERE token = ?");
                                $delStmt->execute([$token]);
                            }
                        }
                    } else if (isset($fcmDecoded['name'])) {
                        $successCount++;
                    }
                    $fcmResponses[] = $fcmDecoded;
                }
                
                if ($successCount > 0) {
                    echo json_encode(['success' => true, 'status' => 'sent_to_' . $successCount]);
                } else {
                    echo json_encode(['success' => false, 'details' => 'No valid tokens']);
                }
            } else {
                echo json_encode(['success' => false, 'details' => 'Failed to get access token']);
            }
        } else {
            echo json_encode(['success' => false, 'details' => 'User token not found']);
        }
    } catch(Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
    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', 'whatsapp_orders'
];

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 {
        require_once 'db_config.php';
        $db_temp = $db;
        foreach ($requested as $s) {
            if (in_array($s, $valid_stores)) {
                $db_temp->exec("CREATE TABLE IF NOT EXISTS $s (id INT AUTO_INCREMENT PRIMARY KEY, data LONGTEXT)");
                
                // --- 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 VARCHAR(50) 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;
}

// الاتصال بقاعدة بيانات MySQL باستخدام ملف الإعدادات
require_once 'db_config.php';
try {
    // $db is already instantiated in db_config.php
    
    // 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 VARCHAR(50) 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 INT AUTO_INCREMENT PRIMARY KEY,
        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 INT AUTO_INCREMENT PRIMARY KEY,
        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 INT AUTO_INCREMENT PRIMARY KEY,
        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 INT AUTO_INCREMENT PRIMARY KEY,
        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 INT AUTO_INCREMENT PRIMARY KEY, data LONGTEXT NOT NULL)");
    $db->exec("CREATE TABLE IF NOT EXISTS invoice_mixer_trips (id INT AUTO_INCREMENT PRIMARY KEY, data LONGTEXT 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;
        $station_operator_id = $input['station_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] > 0) ? (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,
            "station_operator_id" => $station_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,
            "extra_lumpsum" => isset($extra_lumpsum) ? $extra_lumpsum : 0,
            "extra_lumpsum_desc" => isset($extra_lumpsum_desc) ? $extra_lumpsum_desc : ""
        ];

        // 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;
            
            $extra_lumpsum = isset($input['extra_lumpsum']) ? (float)$input['extra_lumpsum'] : 0;
            $extra_lumpsum_desc = isset($input['extra_lumpsum_desc']) && $input['extra_lumpsum_desc'] !== '' ? $input['extra_lumpsum_desc'] : 'مبلغ إضافي';
            
            $subtotal = $selling_price * $billed_qty;
            $tax_amount = $subtotal * ($tax_percent / 100);
            $total_revenue = $subtotal + $tax_amount + $extra_lumpsum;
            
            $invoice_data['total_revenue'] = $total_revenue;
            $invoice_data['extra_lumpsum'] = $extra_lumpsum;
            $invoice_data['extra_lumpsum_desc'] = $extra_lumpsum_desc;

            $sales_invoice_items = [
                    [
                        "item_id" => $mix_item_id,
                        "item_name" => "خرسانة جاهزة " . ($mix_item['name'] ?? ''),
                        "qty" => $billed_qty,
                        "price" => $selling_price,
                        "discount" => 0,
                        "discountType" => "value",
                        "total" => $subtotal
                    ]
                ];
                if ($extra_lumpsum > 0) {
                    $sales_invoice_items[] = [
                        "item_id" => null,
                        "item_name" => $extra_lumpsum_desc,
                        "qty" => 1,
                        "price" => $extra_lumpsum,
                        "discount" => 0,
                        "discountType" => "value",
                        "total" => $extra_lumpsum
                    ];
                }

            $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" => $sales_invoice_items,
                "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 + $extra_lumpsum, "project_id" => null, "contact_id" => null, "notes" => "إيراد مبيعات خرسانة" . ($extra_lumpsum > 0 ? " ومبالغ إضافية" : "") ]
                ];
                
                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 INT AUTO_INCREMENT PRIMARY KEY, data LONGTEXT 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 INT AUTO_INCREMENT PRIMARY KEY, data LONGTEXT 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 INT AUTO_INCREMENT PRIMARY KEY, data LONGTEXT 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,
            'pump_operator_id' => $orderData['pump_operator_id'] ?? null,
            'station_operator_id' => $orderData['station_operator_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,
            'extra_lumpsum' => $orderData['extra_lumpsum'] ?? 0,
            'extra_lumpsum_desc' => $orderData['extra_lumpsum_desc'] ?? ''
        ];

        // Fetch Pump Name
        $orderInfo['pump_name'] = 'بدون مضخة';
        $orderInfo['pump_code'] = '';
        if ($orderInfo['pump_id']) {
            $ps = $db->prepare("SELECT data FROM mixers 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 Warehouse (Station) Info
        $orderInfo['warehouse_name'] = 'غير محدد';
        if (isset($orderData['warehouse_id'])) {
            $ws = $db->prepare("SELECT data FROM warehouses WHERE id = ?");
            $ws->execute([$orderData['warehouse_id']]);
            if ($wRow = $ws->fetch(PDO::FETCH_ASSOC)) {
                $wData = json_decode($wRow['data'], true);
                $orderInfo['warehouse_name'] = $wData['name'] ?? 'غير محدد';
            }
        }

        // 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'] : '';
    }

    // [OCC] Add last_updated timestamp on creation
    if (is_array($input)) {
        $input['_last_updated'] = time();
    }
    $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);
    $lu = isset($input['_last_updated']) ? $input['_last_updated'] : time();
    $respData = ["id" => $newId, "message" => "Created successfully", "_last_updated" => $lu];
    if (isset($input['driver_token'])) {
        $respData['driver_token'] = $input['driver_token'];
    }
    echo json_encode($respData);
} elseif ($method == 'PUT') {
    if (!$id) {
        http_response_code(400);
        echo json_encode(["error" => "Missing ID"]);
        exit;
    }
    $input['id'] = $id;

    // [OCC] Optimistic Concurrency Control Check
    if ($store !== 'mixers') { // Skip complex custom logic for mixers for now
        $stmtCheck = $db->prepare("SELECT data FROM $store WHERE id = ?");
        $stmtCheck->execute([$id]);
        $existingRow = $stmtCheck->fetch(PDO::FETCH_ASSOC);
        
        if ($existingRow) {
            $existingData = json_decode($existingRow['data'], true);
            $clientTime = isset($input['_last_updated']) ? (int)$input['_last_updated'] : 0;
            $serverTime = isset($existingData['_last_updated']) ? (int)$existingData['_last_updated'] : 0;
            
            // If the server has a newer timestamp than what the client sent, it's a conflict!
            if ($serverTime > 0 && $clientTime > 0 && $serverTime !== $clientTime) {
                http_response_code(409); // 409 Conflict
                echo json_encode(["error" => "تضارب بيانات! تم التعديل من قبل مستخدم آخر.", "conflict" => true]);
                exit;
            }
        }
        
        // Update the timestamp to now for this successful edit
        $input['_last_updated'] = time();
    }
    
    // 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);
    
    $lu = isset($input['_last_updated']) ? $input['_last_updated'] : time();
    $respData = ["success" => true, "message" => "Updated successfully", "_last_updated" => $lu];
    if (isset($input['driver_token'])) {
        $respData['driver_token'] = $input['driver_token'];
    }
    echo json_encode($respData);
} 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"]);
}
?>
