<?php
// create_invoice_passenger.php

header('Content-Type: application/json; charset=utf-8');

// -------------------------------------
// تضمين الاتصال
// -------------------------------------
include "../jwtconnect.php";
error_log("[CreateInvoicePassenger] Included 'jwtconnect.php'");

error_log("[CreateInvoicePassenger] --- Request Started ---");

try {
    // -------------------------------------
    // 1) قراءة المدخلات
    // -------------------------------------
    $passengerID = filterRequest("passengerID");
    $user_phone  = filterRequest("user_phone");
    $phone       = filterRequest("phone");
    $amount_raw  = filterRequest("amount");
    error_log("[CreateInvoicePassenger] Read inputs (passengerID, user_phone, amount)");

    // -------------------------------------
    // 2) تحويل/التحقق من المبلغ
    // -------------------------------------
    $amount = is_numeric($amount_raw) ? (float)$amount_raw : 0.0;
    if (empty($passengerID) || empty($user_phone) || $amount <= 0) {
        error_log("[CreateInvoicePassenger] Validation failed: missing/invalid parameters");
        printFailure("passengerID, user_phone and a valid amount are required.");
        exit;
    }
    error_log("[CreateInvoicePassenger] Input validation passed");

    // -------------------------------------
    // 3) التحقق من وجود فاتورة معلّقة لنفس الراكب ونفس الهاتف
    // -------------------------------------
    $sql_check = "
        SELECT id, invoice_number
        FROM invoices_sms_passenger
        WHERE passengerID = :passengerID
          AND user_phone  = :user_phone
          AND status      = 'pending'
        ORDER BY created_at DESC
        LIMIT 1
    ";
    $stmt_check = $con->prepare($sql_check);
    $stmt_check->execute([
        'passengerID' => $passengerID,
        'user_phone'  => $user_phone
    ]);
    $existing = $stmt_check->fetch(PDO::FETCH_ASSOC);
    error_log("[CreateInvoicePassenger] Checked for existing pending invoice");

    // -------------------------------------
    // 4) توليد رقم فاتورة جديد (6 أرقام)
    // -------------------------------------
    $new_invoice_number = random_int(100000, 999999);
    error_log("[CreateInvoicePassenger] Generated invoice number");

    if ($existing) {
        // -------------------------------------
        // 4a) تحديث الفاتورة المعلّقة الحالية
        // -------------------------------------
        error_log("[CreateInvoicePassenger] Existing pending invoice found. Updating...");
        $sql_update = "
            UPDATE invoices_sms_passenger
            SET invoice_number = :invoice_number,
                phone          = :phone,
                amount         = :amount,
                created_at     = NOW()
            WHERE id = :id
        ";
        $stmt_update = $con->prepare($sql_update);
        $stmt_update->execute([
            ':invoice_number' => $new_invoice_number,
            ':phone'          => $phone ?: null,
            ':amount'         => $amount,
            ':id'             => $existing['id']
        ]);
        error_log("[CreateInvoicePassenger] Invoice updated successfully");

        echo json_encode([
            "status"         => "success",
            "message"        => "Pending passenger invoice updated.",
            "invoice_number" => $new_invoice_number
        ]);
        error_log("[CreateInvoicePassenger] Response sent (update)");
    } else {
        // -------------------------------------
        // 4b) إنشاء فاتورة جديدة
        // -------------------------------------
        error_log("[CreateInvoicePassenger] No existing invoice. Creating new one...");
        $sql_insert = "
            INSERT INTO invoices_sms_passenger (invoice_number, passengerID, phone, user_phone, amount, status)
            VALUES (:invoice_number, :passengerID, :phone, :user_phone, :amount, 'pending')
        ";
        $stmt_insert = $con->prepare($sql_insert);
        $ok = $stmt_insert->execute([
            ':invoice_number' => $new_invoice_number,
            ':passengerID'    => $passengerID,
            ':phone'          => $phone ?: null,
            ':user_phone'     => $user_phone,
            ':amount'         => $amount
        ]);

        if ($ok) {
            error_log("[CreateInvoicePassenger] New invoice created successfully");
            echo json_encode([
                "status"         => "success",
                "message"        => "New passenger invoice created.",
                "invoice_number" => $new_invoice_number
            ]);
            error_log("[CreateInvoicePassenger] Response sent (insert)");
        } else {
            error_log("[CreateInvoicePassenger] Failed to create passenger invoice (DB insert)");
            printFailure("Failed to create passenger invoice.");
        }
    }

} catch (PDOException $e) {
    error_log("[CreateInvoicePassenger] Database exception: " . $e->getMessage());
    printFailure("Database error: " . $e->getMessage());

} catch (Throwable $e) {
    error_log("[CreateInvoicePassenger] Unexpected exception: " . $e->getMessage());
    printFailure("An unexpected server error occurred.");
}

error_log("[CreateInvoicePassenger] --- Request Ended ---");