<?php
// shamcash/create_invoice_shamcash.php
// ينشئ الفاتورة ويعيد رقمها للسائق ليكتبه في الملاحظات

include "../../jwtconnect.php"; 

try {
    $driverID   = filterRequest("driverID");
    $amount_raw = filterRequest("amount");
    $phone      = filterRequest("phone");

    $amount = is_numeric($amount_raw) ? (float) $amount_raw : 0.0;

    if (empty($driverID) || $amount <= 0) {
        printFailure("Required: driverID, amount");
        exit;
    }

    // البحث عن فاتورة معلقة لنفس السائق والمبلغ (لتجنب التكرار)
    $stmt = $con->prepare("SELECT id, invoice_number FROM invoices_shamcash WHERE driverID = ? AND amount = ? AND status = 'pending' LIMIT 1");
    $stmt->execute([$driverID, $amount]);
    $existing = $stmt->fetch(PDO::FETCH_ASSOC);

    $invoice_number = 0;

    if ($existing) {
        // استخدام الفاتورة الموجودة وتحديث وقتها
        $invoice_number = $existing['invoice_number'];
        $con->prepare("UPDATE invoices_shamcash SET created_at=NOW() WHERE id=?")->execute([$existing['id']]);
    } else {
        // إنشاء فاتورة جديدة برقم عشوائي
        $invoice_number = random_int(100000, 999999);
        $stmtIns = $con->prepare("INSERT INTO invoices_shamcash (invoice_number, driverID, phone, amount, status, created_at) VALUES (?, ?, ?, ?, 'pending', NOW())");
        $stmtIns->execute([$invoice_number, $driverID, $phone ?: null, $amount]);
    }

    echo json_encode([
        "status" => "success", 
        "message" => "Invoice created. Please use invoice_number in ShamCash Notes.", 
        "invoice_number" => $invoice_number 
    ]);

} catch (PDOException $e) {
    printFailure("DB Error: " . $e->getMessage());
}
?>