<?php
// --- create_mtn_invoice.php ---
// إذا كانت هناك فاتورة Pending لليوم نفسه لنفس المستخدم: نُحدّثها
// غير ذلك: نُنشئ فاتورة جديدة

include "../../connect.php";
header('Content-Type: application/json');

try {
    $userId   = filterRequest("user_id");     // driverID أو passengerID
    $userType = filterRequest("user_type");   // 'driver' أو 'passenger'
    $amount   = filterRequest("amount");
    $mtnPhone = filterRequest("mtn_phone");

    if (empty($userId) || empty($userType) || !is_numeric($amount) || $amount <= 0 || empty($mtnPhone)) {
        echo json_encode(["status" => "failure", "message" => "Invalid input provided."]);
        exit;
    }

    // نضمن اتساق العمليات
    $con->beginTransaction();

    // ابحث عن فاتورة PENDING لنفس المستخدم، منشأة "اليوم"
    // ملاحظة: يتطلب وجود عمود created_at (TIMESTAMP) في الجدول
    $sel = $con->prepare("
        SELECT id, invoice_number
        FROM mtn_invoices
        WHERE user_id = :uid
          AND user_type = :utype
          AND status = 'pending'
          AND DATE(created_at) = CURRENT_DATE
        ORDER BY id DESC
        LIMIT 1
    ");
    $sel->execute([
        ':uid'   => $userId,
        ':utype' => $userType,
    ]);
    $existing = $sel->fetch(PDO::FETCH_ASSOC);

    if ($existing) {
        // يوجد سجل لليوم: نحدّث على نفس الفاتورة
        $upd = $con->prepare("
            UPDATE mtn_invoices
               SET amount = :amount,
                   mtn_phone = :mtn_phone,
                   updated_at = NOW()
             WHERE id = :id
        ");
        $upd->execute([
            ':amount'   => $amount,
            ':mtn_phone'=> $mtnPhone,
            ':id'       => $existing['id'],
        ]);

        $con->commit();

        echo json_encode([
            "status"         => "success",
            "message"        => "Invoice updated (pending, same day).",
            "invoice_number" => $existing['invoice_number'],
            "mode"           => "updated"
        ]);
    } else {
        // لا يوجد سجل لليوم: ننشئ فاتورة جديدة
        $invoiceNumber = "MTN-" . time() . mt_rand(100, 999);

        $ins = $con->prepare("
            INSERT INTO mtn_invoices
               (invoice_number, user_id, user_type, amount, mtn_phone, status, created_at, updated_at)
            VALUES
               (:invoice_number, :user_id, :user_type, :amount, :mtn_phone, 'pending', NOW(), NOW())
        ");
        $ins->execute([
            ':invoice_number' => $invoiceNumber,
            ':user_id'        => $userId,
            ':user_type'      => $userType,
            ':amount'         => $amount,
            ':mtn_phone'      => $mtnPhone
        ]);

        $con->commit();

        // تحديد الرقم أو الاسم المستعار للدفع
        $mtnPaymentNumber = $_ENV['MTN_PAYMENT_NUMBER'] ?? getenv('MTN_PAYMENT_NUMBER') ?: '0930000000';

        echo json_encode([
            "status"         => "success",
            "message"        => "Invoice created successfully.",
            "invoice_number" => $invoiceNumber,
            "mtn_payment_number" => $mtnPaymentNumber,
            "mode"           => "inserted"
        ]);
    }

} catch (Throwable $e) {
    if ($con && $con->inTransaction()) { $con->rollBack(); }
    error_log("Error in create_mtn_invoice.php: " . $e->getMessage());
    echo json_encode(["status" => "failure", "message" => "An internal server error occurred."]);
}