<?php
/**
 * GET /api/payment/status.php?ref=SD-xxx
 * WAVE E — Full Kernel Replace
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../../engine/FinancialAgent.php';

$ctx = Kernel::handle(['auth' => true]);
$uid = (int)$ctx['user']['id'];

$ref = trim($_GET['ref'] ?? '');
$id  = (int)($_GET['invoice_id'] ?? 0);

if (!$ref && !$id) {
    Kernel::fail('missing_params', 'يجب تحديد ref أو invoice_id', 400);
}

try {
    if ($ref) {
        $inv = db()->prepare("SELECT * FROM invoices WHERE reference_code=? AND user_id=? LIMIT 1");
        $inv->execute([$ref, $uid]);
    } else {
        $inv = db()->prepare("SELECT * FROM invoices WHERE id=? AND user_id=? LIMIT 1");
        $inv->execute([$id, $uid]);
    }
    $invoice = $inv->fetch();
    if (!$invoice) Kernel::fail('not_found', 'الفاتورة غير موجودة', 404);

    // Ledger balance verification (read-only)
    $lb = db()->prepare(
        "SELECT COALESCE(SUM(CASE WHEN type='debit' THEN amount ELSE 0 END),0) d,
                COALESCE(SUM(CASE WHEN type='credit' THEN amount ELSE 0 END),0) c
         FROM ledger WHERE reference_id=?"
    );
    $lb->execute([$invoice['id']]);
    $lbRow = $lb->fetch();

    Kernel::respond([
        'invoice_id'      => (int)$invoice['id'],
        'reference_code'  => $invoice['reference_code'],
        'amount'          => (float)$invoice['amount'],
        'status'          => $invoice['status'],
        'payment_method'  => $invoice['payment_method'],
        'created_at'      => $invoice['created_at'],
        'paid_at'         => $invoice['paid_at'],
        'ledger_debit'    => (float)($lbRow['d'] ?? 0),
        'ledger_credit'   => (float)($lbRow['c'] ?? 0),
    ]);

} catch (Throwable $e) {
    Logger::error('payment_status_failed', ['user_id' => $uid, 'error' => $e->getMessage()]);
    Kernel::fail('fetch_failed', 'تعذّر تحميل حالة الدفع', 500);
}
