<?php
// create_invoice.php

// --- بداية التسجيل: تأكيد بدء تشغيل السكربت ---
//error_log("[CreateInvoice] --- Request Started ---");

// تضمين ملف الاتصال والإعدادات الخاص بك
// تأكد من أن هذا الملف لا يحتوي على أخطاء قد تسبب مشكلة Parse
include "../jwtconnect.php"; 
//error_log("[CreateInvoice] Included 'jwtconnect.php'");

try {
    // --- 1. تسجيل واستقبال المدخلات ---
    // تسجيل البيانات الخام القادمة من الطلب لمعرفة ما يصل بالضبط
   // error_log("[CreateInvoice] Raw POST data: " . json_encode($_POST));

    $driverID   = filterRequest("driverID");
    $user_phone = filterRequest("user_phone");
    $phone      = filterRequest("phone");
    $amount_raw = filterRequest("amount");

    // تسجيل البيانات بعد الفلترة
    //error_log("[CreateInvoice] Filtered Input: driverID={$driverID}, user_phone={$user_phone}, amount_raw={$amount_raw}");

    // تأكيد المبلغ كرقم
    $amount = is_numeric($amount_raw) ? (float) $amount_raw : 0.0;

    // --- 2. التحقق الأساسي من المدخلات ---
    if (empty($driverID) || empty($user_phone) || $amount <= 0) {
        error_log("[CreateInvoice] Validation Failed: Missing or invalid required parameters.");
        printFailure("driverID, user_phone and a valid amount are required.");
        exit;
    }
   // error_log("[CreateInvoice] Input validation passed.");

    // --- 3. التحقق من وجود فاتورة معلقة ---
   // error_log("[CreateInvoice] Checking for existing pending invoice for driverID: {$driverID}");
    $sql_check = "SELECT id, invoice_number FROM invoices_sms WHERE driverID = :driverID AND user_phone = :user_phone AND status = 'pending' ORDER BY created_at DESC LIMIT 1";
    $stmt_check = $con->prepare($sql_check);
    $stmt_check->execute(['driverID' => $driverID, 'user_phone' => $user_phone]);
    $existing = $stmt_check->fetch(PDO::FETCH_ASSOC);

    // إنشاء رقم فاتورة جديد ومميز
    $new_invoice_number = random_int(100000, 999999);

    if ($existing) {
        // --- 4a. تحديث الفاتورة المعلقة الحالية ---
    //    error_log("[CreateInvoice] Found existing pending invoice (ID: {$existing['id']}). Updating it.");
        
        $sql_update = "UPDATE invoices_sms 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("[CreateInvoice] Invoice updated. New invoice number: {$new_invoice_number}");
        echo json_encode([
            "status"         => "success",
            "message"        => "Pending invoice updated.",
            "invoice_number" => $new_invoice_number
        ]);

    } else {
        // --- 4b. إنشاء فاتورة جديدة ---
      //  error_log("[CreateInvoice] No pending invoice found. Creating a new one.");

        $sql_insert = "INSERT INTO invoices_sms (invoice_number, driverID, phone, user_phone, amount, status) VALUES (:invoice_number, :driverID, :phone, :user_phone, :amount, 'pending')";
        $stmt_insert = $con->prepare($sql_insert);
        $ok = $stmt_insert->execute([
            ':invoice_number' => $new_invoice_number,
            ':driverID'       => $driverID,
            ':phone'          => $phone ?: null,
            ':user_phone'     => $user_phone,
            ':amount'         => $amount
        ]);

        if ($ok) {
           // error_log("[CreateInvoice] New invoice created successfully. Invoice number: {$new_invoice_number}");
            echo json_encode([
                "status"         => "success",
                "message"        => "New invoice created.",
                "invoice_number" => $new_invoice_number
            ]);
        } else {
           // error_log("[CreateInvoice] CRITICAL: Failed to execute INSERT statement.");
            printFailure("Failed to create invoice.");
        }
    }

} catch (PDOException $e) {
    // تسجيل أخطاء قاعدة البيانات
  //  error_log("[CreateInvoice] PDOException: " . $e->getMessage());
    printFailure("Database error: " . $e->getMessage());

} catch (Throwable $e) {
    // تسجيل أي أخطاء أخرى غير متوقعة
   // error_log("[CreateInvoice] Throwable Exception: " . $e->getMessage());
    printFailure("An unexpected server error occurred.");
}

//error_log("[CreateInvoice] --- Request Ended ---");
?>

