<?php
/**
 * SkyClaim — Document Upload API for Claim Form
 * 
 * This endpoint is called by the claim form (easyjet-claim-funnel.html).
 * It finds the existing customer in the database by booking_ref + first_name + last_name
 * and saves the uploaded document to their row.
 * 
 * Endpoints:
 *   POST /upload.php?action=upload_doc   — Upload ID or travel doc for a customer
 *   POST /upload.php?action=delete_doc   — Delete a doc from a customer
 *   POST /upload.php?action=get_customers — Get customers by booking_ref (for form pre-fill)
 *   POST /upload.php?action=submit       — Mark claim as submitted
 */

// ===== CONFIG — EZEKET ÍRD ÁT! =====
$DB_HOST = 'localhost';
$DB_NAME = 'deeldabr_eu261';
$DB_USER = 'deeldabr_eu261';
$DB_PASS = 'ASDjaS(DCWEFHjewke3we4f@#';

$UPLOAD_DIR = __DIR__ . '/uploads/';

// ===== HEADERS =====
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

// ===== DB =====
try {
    $pdo = new PDO("mysql:host=$DB_HOST;dbname=$DB_NAME;charset=utf8mb4", $DB_USER, $DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
} catch (PDOException $e) {
    respond(500, 'Database connection failed');
}

if (!is_dir($UPLOAD_DIR)) { mkdir($UPLOAD_DIR, 0755, true); }

// ===== ROUTER =====
$action = $_GET['action'] ?? '';
switch ($action) {
    case 'upload_doc': uploadDoc(); break;
    case 'delete_doc': deleteDoc(); break;
    case 'get_customers': getCustomers(); break;
    case 'submit': submitClaim(); break;
    case 'save_draft': saveDraft(); break;
    case 'sync_passengers': syncPassengers(); break;
    default: respond(400, 'Unknown action');
}

// ==========================================================
// SYNC PASSENGERS — Removes passengers not in list, keeps main
// POST body (JSON): { booking_ref, passengers: [{first_name, last_name, ...}] }
// ==========================================================
function syncPassengers() {
    global $pdo;
    $input = getJsonInput();
    $booking = $input['booking_ref'] ?? '';
    $passengers = $input['passengers'] ?? [];
    
    if (!$booking) respond(400, 'booking_ref is required');
    
    // Get all current sub-passengers (not main)
    $stmt = $pdo->prepare("SELECT id, first_name, last_name, id_doc_path, travel_doc_path, assignment_path FROM customers WHERE booking_ref = ? AND is_main = 0");
    $stmt->execute([$booking]);
    $existing = $stmt->fetchAll();
    
    // Build list of names that should exist
    $keepNames = [];
    foreach ($passengers as $p) {
        $keepNames[] = strtolower(trim($p['first_name'] ?? '') . ' ' . trim($p['last_name'] ?? ''));
    }
    
    // Delete sub-passengers not in the list
    $deleted = 0;
    foreach ($existing as $row) {
        $name = strtolower($row['first_name'] . ' ' . $row['last_name']);
        if (!in_array($name, $keepNames)) {
            // Keep files on disk, only delete DB records
            $pdo->prepare("DELETE FROM mail_history WHERE customer_id = ?")->execute([$row['id']]);
            $pdo->prepare("DELETE FROM status_history WHERE customer_id = ?")->execute([$row['id']]);
            $pdo->prepare("DELETE FROM customers WHERE id = ?")->execute([$row['id']]);
            $deleted++;
        }
    }
    
    respond(200, 'Synced', ['deleted' => $deleted]);
}

// ==========================================================
// SAVE DRAFT — Auto-saves address data and creates new passengers
// POST body (JSON): { booking_ref, passengers: [{first_name, last_name, street, city, postal, country}] }
// ==========================================================
function saveDraft() {
    global $pdo;
    $input = getJsonInput();
    $booking = $input['booking_ref'] ?? '';
    $passengers = $input['passengers'] ?? [];
    
    if (!$booking || empty($passengers)) respond(400, 'booking_ref and passengers required');
    
    // Get main customer data for flight info
    $mainStmt = $pdo->prepare("SELECT * FROM customers WHERE booking_ref = ? AND is_main = 1 LIMIT 1");
    $mainStmt->execute([$booking]);
    $mainCust = $mainStmt->fetch();
    
    $saved = 0;
    foreach ($passengers as $p) {
        $fn = $p['first_name'] ?? '';
        $ln = $p['last_name'] ?? '';
        if (!$fn || !$ln) continue;
        
        $street = $p['street'] ?? '';
        $city = $p['city'] ?? '';
        $postal = $p['postal'] ?? '';
        $country = $p['country'] ?? '';
        
        // Check if exists
        $chk = $pdo->prepare("SELECT id FROM customers WHERE booking_ref = ? AND first_name = ? AND last_name = ?");
        $chk->execute([$booking, $fn, $ln]);
        $exists = $chk->fetch();
        
        if ($exists) {
            // Only update address if at least one field has data
            if ($street || $city || $postal || $country) {
                $pdo->prepare("UPDATE customers SET address_street=?, address_city=?, address_postal=?, address_country=?, updated_at=NOW() WHERE id=?")
                    ->execute([$street, $city, $postal, $country, $exists['id']]);
                $saved++;
            }
        } else if ($mainCust) {
            // Create new sub-passenger
            $custId = 'CU-' . strtoupper(substr(md5($fn.$ln.$booking.time().rand()), 0, 8));
            $pdo->prepare("INSERT INTO customers (customer_id, booking_ref, flight_number, flight_date, reason, departure, arrival, first_name, last_name, email, airline, distance_km, is_main, address_street, address_city, address_postal, address_country, status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,0,?,?,?,?,'doc_needed')")
                ->execute([
                    $custId, $booking, $mainCust['flight_number'], $mainCust['flight_date'],
                    $mainCust['reason'], $mainCust['departure'], $mainCust['arrival'],
                    $fn, $ln, '', $mainCust['airline'], $mainCust['distance_km'],
                    $street, $city, $postal, $country
                ]);
            $saved++;
        }
    }
    
    respond(200, 'Draft saved', ['saved' => $saved]);
}

// ==========================================================
// GET CUSTOMERS — Called when claim form loads
// Returns all customers matching a booking_ref
// POST body (JSON): { booking_ref }
// ==========================================================
function getCustomers() {
    global $pdo;
    $input = getJsonInput();
    $booking = $input['booking_ref'] ?? '';
    
    if (!$booking) respond(400, 'booking_ref is required');
    
    $stmt = $pdo->prepare("
        SELECT customer_id, first_name, last_name, is_main,
               id_doc_filename, travel_doc_filename
        FROM customers 
        WHERE booking_ref = ? 
        ORDER BY is_main DESC, id ASC
    ");
    $stmt->execute([$booking]);
    $rows = $stmt->fetchAll();
    
    respond(200, 'OK', ['customers' => $rows]);
}

// ==========================================================
// UPLOAD DOC — Called immediately when user uploads a file
// Finds customer by booking_ref + first_name + last_name
// POST multipart: booking_ref, first_name, last_name, doc_type (id|travel), file
// ==========================================================
function uploadDoc() {
    global $pdo, $UPLOAD_DIR;
    
    $fieldId   = $_POST['field_id'] ?? '';
    $booking   = $_POST['booking_ref'] ?? '';
    $firstName = $_POST['first_name'] ?? '';
    $lastName  = $_POST['last_name'] ?? '';
    $docType   = $_POST['doc_type'] ?? '';
    
    // field_id can also be used to extract info: upload_BOOKING_FIRST_LAST_DOCTYPE
    // But we also accept explicit fields as fallback
    if (!$booking && $fieldId) {
        // Parse field_id: upload_UHK739_Marla_Kate_id
        $parts = explode('_', $fieldId);
        if (count($parts) >= 5 && $parts[0] === 'upload') {
            $booking = $parts[1];
            $firstName = $parts[2];
            $lastName = $parts[3];
            $docType = $parts[4];
        }
    }
    
    if (!$booking || !$firstName || !$lastName || !in_array($docType, ['id', 'travel'])) {
        respond(400, 'field_id or booking_ref + first_name + last_name + doc_type required');
    }
    
    if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        respond(400, 'File upload failed');
    }
    
    // Find customer
    $stmt = $pdo->prepare("SELECT id, customer_id FROM customers WHERE booking_ref = ? AND first_name = ? AND last_name = ?");
    $stmt->execute([$booking, $firstName, $lastName]);
    $customer = $stmt->fetch();
    
    if (!$customer) {
        // Auto-create sub-passenger from main customer's flight data
        $mainStmt = $pdo->prepare("SELECT * FROM customers WHERE booking_ref = ? AND is_main = 1 LIMIT 1");
        $mainStmt->execute([$booking]);
        $mainCust = $mainStmt->fetch();
        if ($mainCust) {
            $custId = 'CU-' . strtoupper(substr(md5($firstName.$lastName.$booking.time().rand()), 0, 8));
            $pdo->prepare("INSERT INTO customers (customer_id, booking_ref, flight_number, flight_date, reason, departure, arrival, first_name, last_name, email, airline, distance_km, is_main, status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,0,'doc_needed')")
                ->execute([$custId, $booking, $mainCust['flight_number'], $mainCust['flight_date'], $mainCust['reason'], $mainCust['departure'], $mainCust['arrival'], $firstName, $lastName, '', $mainCust['airline'], $mainCust['distance_km']]);
            $customer = ['id' => $pdo->lastInsertId(), 'customer_id' => $custId];
        } else {
            respond(404, 'Customer not found and no main passenger exists');
        }
    }
    
    $file = $_FILES['file'];
    $allowedTypes = ['application/pdf', 'image/jpeg', 'image/png', 'image/jpg'];
    
    if (!in_array($file['type'], $allowedTypes)) {
        respond(400, 'Only PDF, JPG, and PNG files are allowed');
    }
    
    if ($file['size'] > 10 * 1024 * 1024) {
        respond(400, 'File too large (max 10MB)');
    }
    
    // Keep old file on disk (never delete uploads), just update DB reference
    $col = ($docType === 'id') ? 'id_doc' : 'travel_doc';
    
    // Save new file — unique name: customerid_doctype_timestamp_random.ext
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $storedName = $customer['customer_id'] . "_{$docType}_" . time() . "_" . bin2hex(random_bytes(4)) . ".{$ext}";
    
    if (!move_uploaded_file($file['tmp_name'], $UPLOAD_DIR . $storedName)) {
        respond(500, 'Failed to save file');
    }
    
    // Update customer row
    $stmt = $pdo->prepare("UPDATE customers SET {$col}_filename = ?, {$col}_path = ?, updated_at = NOW() WHERE id = ?");
    $stmt->execute([$file['name'], $storedName, $customer['id']]);
    
    // Stop remarketing when ID is uploaded
    if ($docType === 'id') {
        try {
            $pdo->prepare("UPDATE customers SET remarketing_active = 0, remarketing_stopped_at = NOW(), remarketing_stopped_reason = 'ID uploaded' WHERE id = ? AND remarketing_active = 1")->execute([$customer['id']]);
            $pdo->prepare("UPDATE customers SET remarketing_active = 0, remarketing_stopped_at = NOW(), remarketing_stopped_reason = 'ID uploaded' WHERE booking_ref = ? AND is_main = 1 AND remarketing_active = 1")->execute([$booking]);
        } catch (Exception $e) {
            // Fallback if stopped columns don't exist
            $pdo->prepare("UPDATE customers SET remarketing_active = 0 WHERE id = ? AND remarketing_active = 1")->execute([$customer['id']]);
            $pdo->prepare("UPDATE customers SET remarketing_active = 0 WHERE booking_ref = ? AND is_main = 1 AND remarketing_active = 1")->execute([$booking]);
        }
    }
    
    // Check if all customers in this booking now have ID docs
    $allHaveId = checkAllIdsUploaded($pdo, $booking);
    
    respond(200, 'Document uploaded', [
        'customer_id' => $customer['customer_id'],
        'doc_type' => $docType,
        'filename' => $file['name'],
        'all_ids_uploaded' => $allHaveId
    ]);
}

// ==========================================================
// DELETE DOC
// POST body (JSON): { booking_ref, first_name, last_name, doc_type }
// ==========================================================
function deleteDoc() {
    global $pdo, $UPLOAD_DIR;
    $input = getJsonInput();
    
    $booking   = $input['booking_ref'] ?? '';
    $firstName = $input['first_name'] ?? '';
    $lastName  = $input['last_name'] ?? '';
    $docType   = $input['doc_type'] ?? '';
    
    $stmt = $pdo->prepare("SELECT id FROM customers WHERE booking_ref = ? AND first_name = ? AND last_name = ?");
    $stmt->execute([$booking, $firstName, $lastName]);
    $customer = $stmt->fetch();
    
    if (!$customer) respond(404, 'Customer not found');
    
    $col = ($docType === 'id') ? 'id_doc' : 'travel_doc';
    
    // Keep file on disk, only clear DB reference
    $stmt = $pdo->prepare("UPDATE customers SET {$col}_filename = NULL, {$col}_path = NULL, updated_at = NOW() WHERE id = ?");
    $stmt->execute([$customer['id']]);
    
    respond(200, 'Document removed');
}

// ==========================================================
// SUBMIT — Mark all customers in booking as doc_needed (docs uploaded, awaiting review)
// POST body (JSON): { booking_ref }
// ==========================================================
function submitClaim() {
    global $pdo;
    $input = getJsonInput();
    $booking = $input['booking_ref'] ?? '';
    // Accept both 'addresses' (old) and 'passengers' (new) format
    $passengers = $input['addresses'] ?? $input['passengers'] ?? [];
    
    if (!$booking) respond(400, 'booking_ref is required');
    
    // Get main customer data for flight info (needed to create sub-passengers)
    $mainStmt = $pdo->prepare("SELECT * FROM customers WHERE booking_ref = ? AND is_main = 1 LIMIT 1");
    $mainStmt->execute([$booking]);
    $mainCust = $mainStmt->fetch();
    
    // Build list of names that should exist
    $keepNames = [];
    foreach ($passengers as $p) {
        $keepNames[] = strtolower(trim($p['first_name'] ?? '') . ' ' . trim($p['last_name'] ?? ''));
    }
    
    // Delete sub-passengers that are NOT in the submitted list
    $stmt = $pdo->prepare("SELECT id, first_name, last_name, id_doc_path, travel_doc_path, assignment_path FROM customers WHERE booking_ref = ? AND is_main = 0");
    $stmt->execute([$booking]);
    $existing = $stmt->fetchAll();
    $uploadDir = __DIR__ . '/uploads/';
    foreach ($existing as $row) {
        $name = strtolower($row['first_name'] . ' ' . $row['last_name']);
        if (!in_array($name, $keepNames)) {
            // Keep files on disk, only delete DB records
            $pdo->prepare("DELETE FROM mail_history WHERE customer_id = ?")->execute([$row['id']]);
            $pdo->prepare("DELETE FROM status_history WHERE customer_id = ?")->execute([$row['id']]);
            $pdo->prepare("DELETE FROM customers WHERE id = ?")->execute([$row['id']]);
        }
    }
    
    // Ensure all passengers exist in DB — create sub-passengers if missing
    foreach ($passengers as $p) {
        $fn = $p['first_name'] ?? '';
        $ln = $p['last_name'] ?? '';
        $street = $p['street'] ?? '';
        $city = $p['city'] ?? '';
        $postal = $p['postal'] ?? '';
        $country = $p['country'] ?? '';
        if (!$fn || !$ln) continue;
        
        // Check if customer exists
        $chk = $pdo->prepare("SELECT id FROM customers WHERE booking_ref = ? AND first_name = ? AND last_name = ?");
        $chk->execute([$booking, $fn, $ln]);
        $exists = $chk->fetch();
        
        if ($exists) {
            // Update address if provided
            if ($street || $city || $postal || $country) {
                $pdo->prepare("UPDATE customers SET address_street=?, address_city=?, address_postal=?, address_country=?, updated_at=NOW() WHERE id=?")
                    ->execute([$street, $city, $postal, $country, $exists['id']]);
            }
        } else if ($mainCust) {
            // Create new sub-passenger with flight data from main customer
            $custId = 'CU-' . strtoupper(substr(md5($fn.$ln.$booking.time().rand()), 0, 8));
            $pdo->prepare("INSERT INTO customers (customer_id, booking_ref, flight_number, flight_date, reason, departure, arrival, first_name, last_name, email, airline, distance_km, is_main, address_street, address_city, address_postal, address_country, status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,0,?,?,?,?,'doc_needed')")
                ->execute([
                    $custId, $booking, $mainCust['flight_number'], $mainCust['flight_date'],
                    $mainCust['reason'], $mainCust['departure'], $mainCust['arrival'],
                    $fn, $ln, '', $mainCust['airline'], $mainCust['distance_km'],
                    $street, $city, $postal, $country
                ]);
        }
    }
    
    // Generate assignment for each customer who has ID doc uploaded
    require_once __DIR__ . '/generate_assignment.php';
    $templatePath = __DIR__ . '/assignment_template.docx';
    $uploadDir = __DIR__ . '/uploads/';
    
    if (file_exists($templatePath)) {
        $stmt = $pdo->prepare("SELECT id FROM customers WHERE booking_ref = ? AND id_doc_filename IS NOT NULL");
        $stmt->execute([$booking]);
        while ($row = $stmt->fetch()) {
            generateAssignment($pdo, $row['id'], $uploadDir, $templatePath);
        }
    }
    
    // Get main customer's customer_id for the ref code
    $stmt = $pdo->prepare("SELECT customer_id FROM customers WHERE booking_ref = ? AND is_main = 1 LIMIT 1");
    $stmt->execute([$booking]);
    $main = $stmt->fetch();
    
    // ===== SEND ADMIN NOTIFICATION EMAIL WITH ATTACHMENTS =====
    $adminEmail = 'easyjet@eu261compensation.com';
    $subject = "Documents - $booking";
    
    // Gather all passengers and their docs
    $allPax = $pdo->prepare("SELECT * FROM customers WHERE booking_ref = ? ORDER BY is_main DESC, id ASC");
    $allPax->execute([$booking]);
    $allPaxRows = $allPax->fetchAll();
    
    // Build HTML body
    $flightInfo = $mainCust ? ($mainCust['flight_number'] . ' | ' . $mainCust['departure'] . ' → ' . $mainCust['arrival'] . ' | ' . $mainCust['flight_date']) : '';
    $reason = $mainCust['reason'] ?? '';
    if (is_numeric($reason)) $reason = "Delayed ({$reason} min)";
    
    $htmlBody = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body style="font-family:Arial,sans-serif;color:#1B2A4A;padding:20px;">';
    $htmlBody .= '<h2 style="color:#FF6B35;margin:0 0 4px;">New Claim Submitted</h2>';
    $htmlBody .= '<p style="font-size:13px;color:#6B7280;margin:0 0 20px;">Booking: <strong>' . htmlspecialchars($booking) . '</strong></p>';
    $htmlBody .= '<table style="width:100%;border-collapse:collapse;font-size:13px;margin-bottom:20px;">';
    $htmlBody .= '<tr style="background:#F8F9FB;"><td style="padding:8px 12px;font-weight:600;color:#6B7280;">Flight</td><td style="padding:8px 12px;">' . htmlspecialchars($flightInfo) . '</td></tr>';
    $htmlBody .= '<tr><td style="padding:8px 12px;font-weight:600;color:#6B7280;">Reason</td><td style="padding:8px 12px;">' . htmlspecialchars($reason) . '</td></tr>';
    $htmlBody .= '<tr style="background:#F8F9FB;"><td style="padding:8px 12px;font-weight:600;color:#6B7280;">Passengers</td><td style="padding:8px 12px;">' . count($allPaxRows) . '</td></tr>';
    $htmlBody .= '</table>';
    
    // List each passenger with doc status
    $htmlBody .= '<h3 style="font-size:14px;margin:0 0 10px;color:#1B2A4A;">Passengers & Documents</h3>';
    $htmlBody .= '<table style="width:100%;border-collapse:collapse;font-size:12px;border:1px solid #E5E7EB;">';
    $htmlBody .= '<tr style="background:#1B2A4A;color:#fff;"><th style="padding:8px 10px;text-align:left;">Name</th><th style="padding:8px 10px;text-align:left;">Type</th><th style="padding:8px 10px;text-align:left;">Email</th><th style="padding:8px 10px;text-align:left;">ID Doc</th><th style="padding:8px 10px;text-align:left;">Address</th></tr>';
    
    $attachments = [];
    foreach ($allPaxRows as $i => $pax) {
        $bg = $i % 2 === 0 ? '#fff' : '#F8F9FB';
        $type = $pax['is_main'] ? 'Main' : 'Sub';
        $addr = implode(', ', array_filter([$pax['address_street'], $pax['address_postal'], $pax['address_city'], $pax['address_country']]));
        $idDoc = $pax['id_doc_filename'] ? '✓ ' . htmlspecialchars($pax['id_doc_filename']) : '✗ Missing';
        $idColor = $pax['id_doc_filename'] ? '#059669' : '#DC2626';
        
        $htmlBody .= '<tr style="background:' . $bg . ';">';
        $htmlBody .= '<td style="padding:6px 10px;font-weight:600;">' . htmlspecialchars($pax['first_name'] . ' ' . $pax['last_name']) . '</td>';
        $htmlBody .= '<td style="padding:6px 10px;">' . $type . '</td>';
        $htmlBody .= '<td style="padding:6px 10px;">' . htmlspecialchars($pax['email'] ?: '—') . '</td>';
        $htmlBody .= '<td style="padding:6px 10px;color:' . $idColor . ';">' . $idDoc . '</td>';
        $htmlBody .= '<td style="padding:6px 10px;font-size:11px;color:#6B7280;">' . htmlspecialchars($addr ?: '—') . '</td>';
        $htmlBody .= '</tr>';
        
        // Collect ID doc attachments
        if ($pax['id_doc_path']) {
            $filePath = $uploadDir . $pax['id_doc_path'];
            if (file_exists($filePath)) {
                $attachments[] = [
                    'path' => $filePath,
                    'name' => $pax['first_name'] . '_' . $pax['last_name'] . '_ID.' . pathinfo($pax['id_doc_filename'], PATHINFO_EXTENSION)
                ];
            }
        }
    }
    $htmlBody .= '</table>';
    $htmlBody .= '<p style="font-size:11px;color:#9CA3AF;margin-top:20px;">This is an automated notification from SkyClaim.</p>';
    $htmlBody .= '</body></html>';
    
    // Send email with attachments using PHP mail()
    $boundary = md5(time() . rand());
    $headers = "From: SkyClaim <easyjet@eu261compensation.com>\r\n";
    $headers .= "Reply-To: easyjet@eu261compensation.com\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: multipart/mixed; boundary=\"{$boundary}\"\r\n";
    
    $body = "--{$boundary}\r\n";
    $body .= "Content-Type: text/html; charset=UTF-8\r\n";
    $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
    $body .= chunk_split(base64_encode($htmlBody)) . "\r\n";
    
    // Add attachments
    foreach ($attachments as $att) {
        $fileData = file_get_contents($att['path']);
        $mimeType = mime_content_type($att['path']) ?: 'application/octet-stream';
        $body .= "--{$boundary}\r\n";
        $body .= "Content-Type: {$mimeType}; name=\"{$att['name']}\"\r\n";
        $body .= "Content-Disposition: attachment; filename=\"{$att['name']}\"\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
        $body .= chunk_split(base64_encode($fileData)) . "\r\n";
    }
    $body .= "--{$boundary}--\r\n";
    
    @mail($adminEmail, $subject, $body, $headers);
    
    respond(200, 'Claim submitted', [
        'customer_id' => $main ? $main['customer_id'] : '',
        'booking_ref' => $booking
    ]);
}

// ===== HELPERS =====
function checkAllIdsUploaded($pdo, $booking) {
    $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM customers WHERE booking_ref = ?");
    $stmt->execute([$booking]);
    $total = $stmt->fetch()['total'];
    
    $stmt = $pdo->prepare("SELECT COUNT(*) as uploaded FROM customers WHERE booking_ref = ? AND id_doc_filename IS NOT NULL");
    $stmt->execute([$booking]);
    $uploaded = $stmt->fetch()['uploaded'];
    
    return $uploaded >= $total;
}

function getJsonInput() {
    return json_decode(file_get_contents('php://input'), true) ?? [];
}

function respond($code, $message, $data = []) {
    http_response_code($code);
    echo json_encode(array_merge(['status' => $code, 'message' => $message], $data));
    exit;
}