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

try {
    $userId   = filterRequest("user_id");     
    $userType = filterRequest("user_type");   
    $amount   = filterRequest("amount");
    $cliqPhone = filterRequest("cliq_phone");

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

    $con->beginTransaction();

    $sel = $con->prepare("
        SELECT id, invoice_number
        FROM cliq_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 cliq_invoices
               SET amount = :amount,
                   cliq_phone = :cliq_phone,
                   updated_at = NOW()
             WHERE id = :id
        ");
        $upd->execute([
            ':amount'     => $amount,
            ':cliq_phone' => $cliqPhone,
            ':id'         => $existing['id'],
        ]);

        $con->commit();

        echo json_encode([
            "status"         => "success",
            "message"        => "Invoice updated.",
            "invoice_number" => $existing['invoice_number'],
            "mode"           => "updated"
        ]);
    } else {
        $invoiceNumber = "CLIQ-" . time() . mt_rand(100, 999);

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

        $con->commit();

        $cliqAlias = $_ENV['CLIQ_ALIAS'] ?? getenv('CLIQ_ALIAS') ?: 'siro_cliq';

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

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