<?php
/**
 * SkyClaim — Document Upload API for Wizz Air Claim Form
 * 
 * This endpoint is called by wizzair-claim-funnel.html.
 * It works with the wz_passengers + wz_bookings tables (NOT the customers table).
 * 
 * Endpoints:
 *   POST /wizzair-upload.php?action=upload_doc     — Upload ID or travel doc for a passenger
 *   POST /wizzair-upload.php?action=delete_doc     — Delete a doc from a passenger
 *   POST /wizzair-upload.php?action=get_customers  — Get passengers by PNR (for form pre-fill)
 *   POST /wizzair-upload.php?action=submit         — Mark claim as submitted
 *   POST /wizzair-upload.php?action=save_draft     — Auto-save address data
 *   POST /wizzair-upload.php?action=sync_passengers — Remove passengers not in list
 */

// ===== CONFIG =====
$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');
}


// ==========================================================
// HELPER: find booking by PNR
// ==========================================================
function findBooking($pnr) {
    global $pdo;
    $st = $pdo->prepare("SELECT b.*, a.id AS acc_id, a.email AS acc_email, a.holder_name
                          FROM wz_bookings b
                          JOIN wz_accounts a ON b.account_id = a.id
                          WHERE b.pnr = ? LIMIT 1");
    $st->execute([$pnr]);
    return $st->fetch();
}


// ==========================================================
// SYNC PASSENGERS — Removes passengers not in list, keeps holder
// ==========================================================
function syncPassengers() {
    global $pdo;
    $input = getJsonInput();
    $pnr = $input['booking_ref'] ?? '';
    $passengers = $input['passengers'] ?? [];

    if (!$pnr) respond(400, 'booking_ref is required');

    $bk = findBooking($pnr);
    if (!$bk) respond(404, 'Booking not found');

    // Current non-holder passengers
    $stmt = $pdo->prepare("SELECT id, first_name, last_name FROM wz_passengers WHERE booking_id = ? AND is_holder = 0");
    $stmt->execute([$bk['id']]);
    $existing = $stmt->fetchAll();

    $keepNames = [];
    foreach ($passengers as $p) {
        $keepNames[] = strtolower(trim($p['first_name'] ?? '') . ' ' . trim($p['last_name'] ?? ''));
    }

    $deleted = 0;
    foreach ($existing as $row) {
        $name = strtolower($row['first_name'] . ' ' . $row['last_name']);
        if (!in_array($name, $keepNames)) {
            try { $pdo->prepare("DELETE FROM mail_history WHERE customer_id = ?")->execute([$row['id']]); } catch (Exception $e) {}
            try { $pdo->prepare("DELETE FROM status_history WHERE customer_id = ?")->execute([$row['id']]); } catch (Exception $e) {}
            $pdo->prepare("DELETE FROM wz_passengers WHERE id = ?")->execute([$row['id']]);
            $deleted++;
        }
    }

    respond(200, 'Synced', ['deleted' => $deleted]);
}


// ==========================================================
// SAVE DRAFT — Auto-saves address data and creates new passengers
// ==========================================================
function saveDraft() {
    global $pdo;
    $input = getJsonInput();
    $pnr = $input['booking_ref'] ?? '';
    $passengers = $input['passengers'] ?? [];

    if (!$pnr || empty($passengers)) respond(400, 'booking_ref and passengers required');

    $bk = findBooking($pnr);
    if (!$bk) respond(404, 'Booking not found');

    $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'] ?? '';
        $addressFull = implode(', ', array_filter([$street, $postal, $city, $country]));

        $chk = $pdo->prepare("SELECT id FROM wz_passengers WHERE booking_id = ? AND first_name = ? AND last_name = ?");
        $chk->execute([$bk['id'], $fn, $ln]);
        $exists = $chk->fetch();

        if ($exists) {
            if ($addressFull) {
                $pdo->prepare("UPDATE wz_passengers SET address = ?, updated_at = NOW() WHERE id = ?")
                    ->execute([$addressFull, $exists['id']]);
                $saved++;
            }
        } else {
            // Create new sub-passenger
            $pdo->prepare("INSERT INTO wz_passengers (booking_id, account_id, passenger_name, first_name, last_name, is_holder, address, status) VALUES (?, ?, ?, ?, ?, 0, ?, 'doc_needed')")
                ->execute([$bk['id'], $bk['acc_id'], "$fn $ln", $fn, $ln, $addressFull]);
            $saved++;
        }
    }

    respond(200, 'Draft saved', ['saved' => $saved]);
}


// ==========================================================
// GET CUSTOMERS — Called when claim form loads
// ==========================================================
function getCustomers() {
    global $pdo;
    $input = getJsonInput();
    $pnr = $input['booking_ref'] ?? '';

    if (!$pnr) respond(400, 'booking_ref is required');

    $bk = findBooking($pnr);
    if (!$bk) respond(200, 'OK', ['customers' => []]);

    $stmt = $pdo->prepare("
        SELECT CONCAT('WZ-', id) AS customer_id,
               first_name, last_name,
               is_holder AS is_main,
               id_doc_filename, travel_doc_filename
        FROM wz_passengers
        WHERE booking_id = ?
        ORDER BY is_holder DESC, id ASC
    ");
    $stmt->execute([$bk['id']]);
    $rows = $stmt->fetchAll();

    respond(200, 'OK', ['customers' => $rows]);
}


// ==========================================================
// UPLOAD DOC — Called immediately when user uploads a file
// ==========================================================
function uploadDoc() {
    global $pdo, $UPLOAD_DIR;

    $fieldId   = $_POST['field_id'] ?? '';
    $pnr       = $_POST['booking_ref'] ?? '';
    $firstName = $_POST['first_name'] ?? '';
    $lastName  = $_POST['last_name'] ?? '';
    $docType   = $_POST['doc_type'] ?? '';

    // Parse field_id fallback: upload_PNR_FIRST_LAST_DOCTYPE
    if (!$pnr && $fieldId) {
        $parts = explode('_', $fieldId);
        if (count($parts) >= 5 && $parts[0] === 'upload') {
            $pnr       = $parts[1];
            $firstName = $parts[2];
            $lastName  = $parts[3];
            $docType   = $parts[4];
        }
    }

    if (!$pnr || !$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');
    }

    $bk = findBooking($pnr);
    if (!$bk) respond(404, 'Booking not found');

    // Find passenger
    $stmt = $pdo->prepare("SELECT id FROM wz_passengers WHERE booking_id = ? AND first_name = ? AND last_name = ?");
    $stmt->execute([$bk['id'], $firstName, $lastName]);
    $passenger = $stmt->fetch();

    if (!$passenger) {
        // Auto-create sub-passenger
        $pdo->prepare("INSERT INTO wz_passengers (booking_id, account_id, passenger_name, first_name, last_name, is_holder, status) VALUES (?, ?, ?, ?, ?, 0, 'doc_needed')")
            ->execute([$bk['id'], $bk['acc_id'], "$firstName $lastName", $firstName, $lastName]);
        $passenger = ['id' => $pdo->lastInsertId()];
    }

    $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)');
    }

    $col = ($docType === 'id') ? 'id_doc' : 'travel_doc';

    // Save file
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $storedName = "wz_{$passenger['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 passenger row
    $pdo->prepare("UPDATE wz_passengers SET {$col}_filename = ?, {$col}_path = ?, updated_at = NOW() WHERE id = ?")
        ->execute([$file['name'], $storedName, $passenger['id']]);

    // Stop remarketing when ID is uploaded
    if ($docType === 'id') {
        try {
            $pdo->prepare("UPDATE wz_passengers SET remarketing_active = 0, remarketing_stopped_at = NOW(), remarketing_stopped_reason = 'ID uploaded' WHERE id = ? AND remarketing_active = 1")
                ->execute([$passenger['id']]);
            $pdo->prepare("UPDATE wz_passengers SET remarketing_active = 0, remarketing_stopped_at = NOW(), remarketing_stopped_reason = 'ID uploaded' WHERE booking_id = ? AND is_holder = 1 AND remarketing_active = 1")
                ->execute([$bk['id']]);
        } catch (Exception $e) {
            // Fallback if stopped columns don't exist
            $pdo->prepare("UPDATE wz_passengers SET remarketing_active = 0 WHERE id = ? AND remarketing_active = 1")
                ->execute([$passenger['id']]);
            $pdo->prepare("UPDATE wz_passengers SET remarketing_active = 0 WHERE booking_id = ? AND is_holder = 1 AND remarketing_active = 1")
                ->execute([$bk['id']]);
        }
    }

    // Check if all passengers have ID docs
    $allHaveId = checkAllIdsUploaded($pdo, $bk['id']);

    respond(200, 'Document uploaded', [
        'customer_id' => 'WZ-' . $passenger['id'],
        'doc_type'    => $docType,
        'filename'    => $file['name'],
        'all_ids_uploaded' => $allHaveId
    ]);
}


// ==========================================================
// DELETE DOC
// ==========================================================
function deleteDoc() {
    global $pdo;
    $input = getJsonInput();

    $pnr       = $input['booking_ref'] ?? '';
    $firstName = $input['first_name'] ?? '';
    $lastName  = $input['last_name'] ?? '';
    $docType   = $input['doc_type'] ?? '';

    $bk = findBooking($pnr);
    if (!$bk) respond(404, 'Booking not found');

    $stmt = $pdo->prepare("SELECT id FROM wz_passengers WHERE booking_id = ? AND first_name = ? AND last_name = ?");
    $stmt->execute([$bk['id'], $firstName, $lastName]);
    $passenger = $stmt->fetch();

    if (!$passenger) respond(404, 'Passenger not found');

    $col = ($docType === 'id') ? 'id_doc' : 'travel_doc';

    $pdo->prepare("UPDATE wz_passengers SET {$col}_filename = NULL, {$col}_path = NULL, updated_at = NOW() WHERE id = ?")
        ->execute([$passenger['id']]);

    respond(200, 'Document removed');
}


// ==========================================================
// SUBMIT — Mark claim as submitted, send admin notification
// ==========================================================
function submitClaim() {
    global $pdo, $UPLOAD_DIR;
    $input = getJsonInput();
    $pnr = $input['booking_ref'] ?? '';
    $passengers = $input['passengers'] ?? [];

    if (!$pnr) respond(400, 'booking_ref is required');

    $bk = findBooking($pnr);
    if (!$bk) respond(404, 'Booking not found');

    // Build keep-list
    $keepNames = [];
    foreach ($passengers as $p) {
        $keepNames[] = strtolower(trim($p['first_name'] ?? '') . ' ' . trim($p['last_name'] ?? ''));
    }

    // Delete sub-passengers NOT in the list
    $stmt = $pdo->prepare("SELECT id, first_name, last_name FROM wz_passengers WHERE booking_id = ? AND is_holder = 0");
    $stmt->execute([$bk['id']]);
    foreach ($stmt->fetchAll() as $row) {
        $name = strtolower($row['first_name'] . ' ' . $row['last_name']);
        if (!in_array($name, $keepNames)) {
            try { $pdo->prepare("DELETE FROM mail_history WHERE customer_id = ?")->execute([$row['id']]); } catch (Exception $e) {}
            try { $pdo->prepare("DELETE FROM status_history WHERE customer_id = ?")->execute([$row['id']]); } catch (Exception $e) {}
            $pdo->prepare("DELETE FROM wz_passengers WHERE id = ?")->execute([$row['id']]);
        }
    }

    // Ensure all passengers exist
    foreach ($passengers as $p) {
        $fn = $p['first_name'] ?? '';
        $ln = $p['last_name'] ?? '';
        if (!$fn || !$ln) continue;

        $chk = $pdo->prepare("SELECT id FROM wz_passengers WHERE booking_id = ? AND first_name = ? AND last_name = ?");
        $chk->execute([$bk['id'], $fn, $ln]);
        if (!$chk->fetch()) {
            $pdo->prepare("INSERT INTO wz_passengers (booking_id, account_id, passenger_name, first_name, last_name, is_holder, status) VALUES (?, ?, ?, ?, ?, 0, 'doc_needed')")
                ->execute([$bk['id'], $bk['acc_id'], "$fn $ln", $fn, $ln]);
        }
    }

    // Try generating assignments
    $templatePath = __DIR__ . '/assignment_template.docx';
    if (file_exists($templatePath) && file_exists(__DIR__ . '/generate_assignment.php')) {
        require_once __DIR__ . '/generate_assignment.php';
        $paxStmt = $pdo->prepare("SELECT id FROM wz_passengers WHERE booking_id = ? AND id_doc_filename IS NOT NULL");
        $paxStmt->execute([$bk['id']]);
        while ($row = $paxStmt->fetch()) {
            try { generateAssignment($pdo, $row['id'], $UPLOAD_DIR, $templatePath); } catch (Exception $e) {}
        }
    }

    // Get holder for ref code
    $holderStmt = $pdo->prepare("SELECT id FROM wz_passengers WHERE booking_id = ? AND is_holder = 1 LIMIT 1");
    $holderStmt->execute([$bk['id']]);
    $holder = $holderStmt->fetch();
    $refCode = $holder ? 'WZ-' . $holder['id'] : 'WZ-' . $pnr;

    // ===== ADMIN NOTIFICATION EMAIL WITH ATTACHMENTS =====
    $adminEmail = 'wizzair@eu261compensation.com';
    $subject = "Documents - $pnr (Wizz Air)";

    $allPaxStmt = $pdo->prepare("SELECT * FROM wz_passengers WHERE booking_id = ? ORDER BY is_holder DESC, id ASC");
    $allPaxStmt->execute([$bk['id']]);
    $allPaxRows = $allPaxStmt->fetchAll();

    $flightInfo = $bk['flight_number'] . ' | ' . $bk['origin'] . ' → ' . $bk['destination'] . ' | ' . $bk['flight_date'];
    $reason = $bk['reason'] ?? '';

    $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:#E5007D;margin:0 0 4px;">New Wizz Air Claim Submitted</h2>';
    $htmlBody .= '<p style="font-size:13px;color:#6B7280;margin:0 0 20px;">PNR: <strong>' . htmlspecialchars($pnr) . '</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>';

    $htmlBody .= '<h3 style="font-size:14px;margin:0 0 10px;">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></tr>';

    $attachments = [];
    foreach ($allPaxRows as $i => $pax) {
        $bg = $i % 2 === 0 ? '#fff' : '#F8F9FB';
        $type = $pax['is_holder'] ? 'Holder' : 'Sub';
        $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 .= '</tr>';

        if ($pax['id_doc_path']) {
            $filePath = $UPLOAD_DIR . $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;">Automated notification — SkyClaim (Wizz Air)</p>';
    $htmlBody .= '</body></html>';

    // Send with attachments
    $boundary = md5(time() . rand());
    $headers  = "From: SkyClaim <wizzair@eu261compensation.com>\r\n";
    $headers .= "Reply-To: wizzair@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";

    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' => $refCode,
        'booking_ref' => $pnr
    ]);
}


// ===== HELPERS =====
function checkAllIdsUploaded($pdo, $bookingId) {
    $total = $pdo->prepare("SELECT COUNT(*) as c FROM wz_passengers WHERE booking_id = ?");
    $total->execute([$bookingId]);
    $t = $total->fetch()['c'];

    $uploaded = $pdo->prepare("SELECT COUNT(*) as c FROM wz_passengers WHERE booking_id = ? AND id_doc_filename IS NOT NULL");
    $uploaded->execute([$bookingId]);
    $u = $uploaded->fetch()['c'];

    return $u >= $t;
}

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;
}