<?php
// shamcash/passenger/create_invoice.php

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

try {
    $passengerID = filterRequest("passengerID");
    $amount_raw  = filterRequest("amount");
    $phone       = filterRequest("phone");
    $amount      = is_numeric($amount_raw) ? (float) $amount_raw : 0.0;

    if (empty($passengerID) || $amount <= 0) {
        printFailure("Required: passengerID and valid amount");
        exit;
    }

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

    $invoice_number = 0;

    if ($existing) {
        $invoice_number = $existing['invoice_number'];
        $con->prepare("UPDATE invoices_shamcash_passenger SET created_at=NOW() WHERE id=?")->execute([$existing['id']]);
    } else {
        $invoice_number = random_int(100000, 999999);
        $stmtIns = $con->prepare("INSERT INTO invoices_shamcash_passenger (invoice_number, passengerID, phone, amount, status, created_at) VALUES (?, ?, ?, ?, 'pending', NOW())");
        $stmtIns->execute([$invoice_number, $passengerID, $phone ?: null, $amount]);
    }

    echo json_encode([
        "status" => "success", 
        "message" => "Invoice created", 
        "invoice_number" => $invoice_number 
    ]);

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