<?php
/**
 * سودانا — Payment Screen
 * Route: /payment.php?invoice_id=X
 *        /payment.php?service=legal&amount=500
 * Handles: Invoice creation (if new) + Bank transfer instructions + Proof upload
 */
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/engine/FinancialAgent.php';
require_once __DIR__ . '/engine/InvoiceEngine.php';

session_start();
$u      = current_user();
$userId = (int)($u['id'] ?? 0);
$lang   = $_SESSION['lang'] ?? 'ar';
$dir    = $lang === 'ar' ? 'rtl' : 'ltr';

$invoice    = null;
$step       = 'pay'; // pay | upload | status
$error      = '';

// ── Load or create invoice ─────────────────────────────────────────────
$invoiceId = (int)($_GET['invoice_id'] ?? $_POST['invoice_id'] ?? 0);
$service   = htmlspecialchars($_GET['service'] ?? 'general', ENT_QUOTES, 'UTF-8');
$amount    = (float)($_GET['amount'] ?? $_POST['amount'] ?? 0);

if ($invoiceId) {
    try {
        $q = db()->prepare("SELECT * FROM invoices WHERE id=? AND user_id=?");
        $q->execute([$invoiceId, $userId ?: 999999]); // 999999 blocks if no user
        $invoice = $q->fetch(PDO::FETCH_ASSOC);
        if ($invoice) {
            $service = $invoice['service'];
            $amount  = $invoice['amount'];
            // Determine step from status
            if (in_array($invoice['status'], ['proof_uploaded','under_review'])) $step = 'status';
            elseif ($invoice['status'] === 'paid') $step = 'receipt';
            elseif ($invoice['status'] === 'rejected') $step = 'rejected';
            elseif (!empty($invoice['expires_at']) && strtotime($invoice['expires_at']) < time() && $invoice['status'] !== 'paid') $step = 'expired';
        }
    } catch (Throwable $e) {}
} elseif (!$userId) {
    // Guest: redirect to login
    header('Location: ' . SITE_URL . '/');
    exit;
}

// ── Service labels ─────────────────────────────────────────────────────
$serviceLabels = [
    'legal'      => ['ar'=>'استشارة قانونية',  'en'=>'Legal Consultation'],
    'medical'    => ['ar'=>'استشارة طبية',      'en'=>'Medical Consultation'],
    'business'   => ['ar'=>'استشارة أعمال',    'en'=>'Business Consulting'],
    'engineering'=> ['ar'=>'استشارة هندسية',   'en'=>'Engineering Consulting'],
    'agriculture'=> ['ar'=>'استشارة زراعية',   'en'=>'Agriculture Consulting'],
    'general'    => ['ar'=>'خدمة سودانا',       'en'=>'Sudanna Service'],
];
$serviceLabel = $serviceLabels[$service][$lang] ?? $serviceLabels['general'][$lang];

$t = [
    'ar' => [
        'title' => 'الدفع',
        'invoice_for' => 'فاتورة',
        'amount' => 'المبلغ',
        'bank' => 'البنك',
        'account' => 'رقم الحساب',
        'ref' => 'الرمز المرجعي',
        'copy' => 'نسخ',
        'copied' => 'تم النسخ ✓',
        'expires' => 'تنتهي الصلاحية',
        'upload_title' => 'ارفع صورة الإيصال',
        'upload_hint' => 'اسحب الصورة هنا أو اضغط للرفع — JPG, PNG حتى 5MB',
        'upload_btn' => 'رفع الإيصال',
        'status_pending' => 'قيد المراجعة',
        'status_ok' => 'تم قبول الدفعة',
        'step1' => 'تفاصيل الفاتورة',
        'step2' => 'رفع الإيصال',
        'step3' => 'تأكيد الدفع',
        'next' => 'التالي',
        'receipt_btn' => 'عرض الإيصال',
        'create_invoice' => 'إنشاء الفاتورة',
    ],
    'en' => [
        'title' => 'Payment',
        'invoice_for' => 'Invoice for',
        'amount' => 'Amount',
        'bank' => 'Bank',
        'account' => 'Account Number',
        'ref' => 'Reference Code',
        'copy' => 'Copy',
        'copied' => 'Copied ✓',
        'expires' => 'Expires',
        'upload_title' => 'Upload Payment Proof',
        'upload_hint' => 'Drag image here or click to upload — JPG, PNG up to 5MB',
        'upload_btn' => 'Upload Proof',
        'status_pending' => 'Under Review',
        'status_ok' => 'Payment Confirmed',
        'step1' => 'Invoice Details',
        'step2' => 'Upload Proof',
        'step3' => 'Confirmation',
        'next' => 'Next',
        'receipt_btn' => 'View Receipt',
        'create_invoice' => 'Create Invoice',
    ],
];
$T = $t[$lang] ?? $t['ar'];
?>
<!DOCTYPE html>
<html lang="<?= $lang ?>" dir="<?= $dir ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= $T['title'] ?> — سودانا</title>
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;900&display=swap" rel="stylesheet">
<style>
:root{--g1:#073328;--g2:#0B4D3B;--g3:#1a7255;--gold:#D4AF37;--amber:#E8A020;
--sand:#FAF6EF;--sand2:#F0E8DC;--border:#E2D8CC;--text:#1C1A16;--text2:#5A5550;
--success:#16A34A;--warning:#D97706;--danger:#DC2626;--info:#2563EB;
--r:16px;--r2:10px;--sh:0 4px 24px rgba(7,51,40,.10)}
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:'Cairo',sans-serif;background:var(--sand);color:var(--text);min-height:100vh;display:flex;flex-direction:column}
/* ── Top bar ── */
.pay-topbar{background:var(--g1);color:#fff;padding:14px 20px;display:flex;align-items:center;gap:12px}
.pay-topbar .logo{font-weight:900;font-size:1.15rem;color:var(--gold)}
.pay-topbar .back{color:rgba(255,255,255,.7);font-size:.88rem;text-decoration:none;margin-right:auto}
.pay-topbar .back:hover{color:#fff}
/* ── Progress ── */
.pay-progress{background:#fff;border-bottom:1px solid var(--border);padding:16px 20px}
.progress-steps{display:flex;align-items:center;max-width:480px;margin:0 auto}
.ps-item{flex:1;display:flex;flex-direction:column;align-items:center;position:relative}
.ps-item:not(:last-child)::after{content:'';position:absolute;top:12px;
  right: <?= $dir==='rtl' ? 'auto' : '50%' ?>;
  left: <?= $dir==='rtl' ? '50%' : 'auto' ?>;
  width:100%;height:2px;background:var(--border);z-index:0}
.ps-item.done:not(:last-child)::after{background:var(--g3)}
.ps-dot{width:24px;height:24px;border-radius:50%;border:2px solid var(--border);background:#fff;
display:flex;align-items:center;justify-content:center;font-size:.72rem;font-weight:700;z-index:1;transition:all .3s}
.ps-dot.done{background:var(--g1);border-color:var(--g1);color:#fff}
.ps-dot.active{background:var(--gold);border-color:var(--gold);color:var(--g1);box-shadow:0 0 0 4px rgba(212,175,55,.2)}
.ps-label{font-size:.7rem;color:var(--text2);margin-top:5px;text-align:center}
.ps-item.active .ps-label{color:var(--g1);font-weight:700}
/* ── Content ── */
.pay-wrap{flex:1;padding:24px 16px;max-width:560px;margin:0 auto;width:100%}
.pay-card{background:#fff;border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--sh);overflow:hidden;margin-bottom:16px}
.pay-card-header{background:var(--g1);color:#fff;padding:16px 20px;display:flex;align-items:center;gap:10px}
.pay-card-header .icon{font-size:1.3rem}
.pay-card-header h2{font-size:1rem;font-weight:700}
.pay-card-body{padding:20px}
/* ── Invoice row ── */
.inv-row{display:flex;justify-content:space-between;align-items:center;padding:10px 0;border-bottom:1px solid var(--sand2)}
.inv-row:last-child{border:none}
.inv-label{font-size:.85rem;color:var(--text2)}
.inv-val{font-size:.92rem;font-weight:600}
.inv-val.big{font-size:1.5rem;font-weight:900;color:var(--g1)}
.inv-val.ref{font-family:monospace;font-size:.82rem;background:var(--sand);padding:4px 10px;border-radius:6px;letter-spacing:.03em}
/* ── Copy button ── */
.copy-btn{background:none;border:1px solid var(--border);border-radius:6px;padding:4px 10px;font-size:.75rem;color:var(--g2);cursor:pointer;transition:all .2s;margin-right:8px}
.copy-btn:hover{background:var(--g2);color:#fff;border-color:var(--g2)}
/* ── Countdown ── */
.countdown{display:inline-flex;align-items:center;gap:6px;background:var(--sand);border:1px solid var(--border);border-radius:20px;padding:4px 12px;font-size:.8rem;font-weight:600;color:var(--warning)}
.countdown.urgent{color:var(--danger);border-color:#FCA5A5;background:#FEE2E2}
/* ── Upload zone ── */
.upload-zone{border:2px dashed var(--border);border-radius:var(--r);padding:32px 20px;text-align:center;background:var(--sand);cursor:pointer;transition:all .25s;position:relative}
.upload-zone:hover,.upload-zone.dragover{border-color:var(--g3);background:#fff}
.upload-zone input[type=file]{position:absolute;inset:0;opacity:0;cursor:pointer;width:100%;height:100%}
.upload-zone .uz-icon{font-size:2.5rem;margin-bottom:10px}
.upload-zone p{font-size:.88rem;color:var(--text2)}
.upload-zone p strong{color:var(--g2)}
/* ── Preview ── */
.proof-preview{display:none;border:1px solid var(--border);border-radius:var(--r2);padding:14px;align-items:center;gap:12px;margin-top:12px}
.proof-preview.show{display:flex}
.proof-preview img{width:60px;height:60px;object-fit:cover;border-radius:8px;border:1px solid var(--border)}
.proof-preview .pf-info{flex:1}
.proof-preview .pf-name{font-size:.85rem;font-weight:600}
.proof-preview .pf-size{font-size:.75rem;color:var(--text2)}
.proof-preview .pf-hash{font-size:.68rem;font-family:monospace;color:var(--text3);word-break:break-all}
/* ── Status states ── */
.status-badge{display:inline-flex;align-items:center;gap:8px;padding:10px 18px;border-radius:20px;font-weight:700;font-size:.88rem}
.status-pending{background:#FEF3C7;color:#92400E}
.status-reviewing{background:#DBEAFE;color:#1E40AF}
.status-paid{background:#D1FAE5;color:#065F46}
.status-rejected{background:#FEE2E2;color:#991B1B}
/* ── Buttons ── */
.btn{display:flex;align-items:center;justify-content:center;gap:8px;padding:12px 24px;border-radius:var(--r2);font-weight:700;font-size:.92rem;border:none;cursor:pointer;width:100%;transition:all .2s;margin-top:12px}
.btn-primary{background:var(--g1);color:#fff}
.btn-primary:hover{background:var(--g2)}
.btn-primary:disabled{background:var(--border);color:var(--text2);cursor:not-allowed}
.btn-gold{background:var(--gold);color:var(--g1)}
.btn-gold:hover{background:var(--amber)}
/* ── Alert ── */
.alert{padding:12px 16px;border-radius:var(--r2);font-size:.85rem;margin-bottom:16px;display:flex;gap:10px}
.alert-warning{background:#FEF3C7;border:1px solid #FCD34D;color:#92400E}
.alert-success{background:#D1FAE5;border:1px solid #6EE7B7;color:#065F46}
.alert-danger{background:#FEE2E2;border:1px solid #FCA5A5;color:#991B1B}
/* ── Trust strip ── */
.trust-strip{display:flex;gap:16px;flex-wrap:wrap;justify-content:center;padding:16px;background:var(--sand);border-radius:var(--r2);font-size:.78rem;color:var(--text2);margin-top:8px}
.trust-item{display:flex;align-items:center;gap:4px}
/* ── Loading ── */
.spinner{width:20px;height:20px;border:3px solid rgba(255,255,255,.3);border-top-color:#fff;border-radius:50%;animation:spin .7s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}}
/* ── Toast ── */
#toast{position:fixed;bottom:24px;left:50%;transform:translateX(-50%) translateY(100px);background:#fff;border:1px solid var(--border);border-radius:12px;padding:12px 20px;box-shadow:var(--sh);font-size:.88rem;font-weight:600;display:flex;align-items:center;gap:8px;z-index:1000;transition:transform .3s}
#toast.show{transform:translateX(-50%) translateY(0)}
#toast.success{border-color:#6EE7B7;color:#065F46}
#toast.error{border-color:#FCA5A5;color:#991B1B}

/* Responsive additions */
@media(max-width:640px){
  .payment-form{padding:20px 16px!important}
  .pay-header{padding:20px 16px!important}
  .pay-amount{font-size:2rem!important}
  .pay-methods{flex-direction:column!important}
  .pay-method-btn{width:100%!important}
}
.payment-card{border-radius:16px;box-shadow:0 4px 20px rgba(0,0,0,.15);overflow:hidden}
.pay-header{background:linear-gradient(135deg,#073328,#0a2a1a);padding:24px 28px;color:#fff}
.pay-amount{font-size:2.5rem;font-weight:900;color:#00d97e;margin:8px 0}
.pay-btn{transition:.2s;background:linear-gradient(135deg,#00d97e,#059669)}
.pay-btn:hover{transform:translateY(-1px);box-shadow:0 4px 12px rgba(0,217,126,.35)}
.skel{background:linear-gradient(90deg,#f0f0f0 25%,#e8e8e8 50%,#f0f0f0 75%);background-size:200% 100%;animation:skel 1.4s infinite;border-radius:6px;height:14px;margin:6px 0}
@keyframes skel{0%{background-position:200% 0}100%{background-position:-200% 0}}
</style>
</head>
<body>

<div class="pay-topbar">
  <span class="logo">🇸🇩 سودانا</span>
  <a href="<?= SITE_URL ?>/" class="back">← العودة</a>
  <span style="font-size:.82rem;color:rgba(255,255,255,.7)"><?= $T['title'] ?></span>
</div>

<!-- Progress -->
<div class="pay-progress">
  <div class="progress-steps">
    <div class="ps-item <?= in_array($step,['pay','upload','status','receipt']) ? 'done' : '' ?> <?= $step==='pay' ? 'active' : '' ?>">
      <div class="ps-dot <?= in_array($step,['upload','status','receipt']) ? 'done' : ($step==='pay' ? 'active' : '') ?>">
        <?= in_array($step,['upload','status','receipt']) ? '✓' : '1' ?>
      </div>
      <p class="ps-label"><?= $T['step1'] ?></p>
    </div>
    <div class="ps-item <?= in_array($step,['upload','status','receipt']) ? 'done' : '' ?> <?= $step==='upload' ? 'active' : '' ?>">
      <div class="ps-dot <?= in_array($step,['status','receipt']) ? 'done' : ($step==='upload' ? 'active' : '') ?>">
        <?= in_array($step,['status','receipt']) ? '✓' : '2' ?>
      </div>
      <p class="ps-label"><?= $T['step2'] ?></p>
    </div>
    <div class="ps-item <?= $step==='receipt' ? 'done' : '' ?> <?= in_array($step,['status','receipt']) ? 'active' : '' ?>">
      <div class="ps-dot <?= $step==='receipt' ? 'done' : (in_array($step,['status','receipt']) ? 'active' : '') ?>">
        <?= $step==='receipt' ? '✓' : '3' ?>
      </div>
      <p class="ps-label"><?= $T['step3'] ?></p>
    </div>
  </div>
</div>

<div class="pay-wrap">

<?php if ($error): ?>
  <div class="alert alert-danger">⚠️ <?= htmlspecialchars($error) ?></div>
<?php endif; ?>

<?php if ($step === 'pay'): ?>
<!-- ══ STEP 1: Invoice Details + Create if needed ══ -->
<div class="pay-card" id="step-pay">
  <div class="pay-card-header">
    <span class="icon">🧾</span>
    <h2><?= $T['invoice_for'] ?>: <?= $serviceLabel ?></h2>
  </div>
  <div class="pay-card-body" id="invoice-body">
    <?php if (!$invoice && $userId && $amount > 0): ?>
    <!-- Will be created via JS -->
    <div id="creating-inv" style="text-align:center;padding:20px">
      <div class="spinner" style="border-top-color:var(--g1);border-color:rgba(7,51,40,.2);margin:0 auto 12px"></div>
      <p style="color:var(--text2)"><?= $T['create_invoice'] ?>...</p>
    </div>
    <?php elseif ($invoice): ?>
    <div class="inv-row">
      <span class="inv-label"><?= $T['amount'] ?></span>
      <span class="inv-val big"><?= number_format($invoice['amount'],2) ?> <small style="font-size:.8rem">SDG</small></span>
    </div>
    <div class="inv-row">
      <span class="inv-label"><?= $T['bank'] ?></span>
      <span class="inv-val">بنك الخرطوم</span>
    </div>
    <div class="inv-row">
      <span class="inv-label"><?= $T['account'] ?></span>
      <span style="display:flex;align-items:center;gap:6px">
        <button class="copy-btn" onclick="copyText('1821425','<?= $T['copied'] ?>')" id="copy-acc"><?= $T['copy'] ?></button>
        <span class="inv-val ref">1821425</span>
      </span>
    </div>
    <div class="inv-row">
      <span class="inv-label"><?= $T['ref'] ?></span>
      <span style="display:flex;align-items:center;gap:6px">
        <button class="copy-btn" onclick="copyText('<?= htmlspecialchars($invoice['reference_code']) ?>','<?= $T['copied'] ?>')" id="copy-ref"><?= $T['copy'] ?></button>
        <span class="inv-val ref"><?= htmlspecialchars($invoice['reference_code'] ?? '') ?></span>
      </span>
    </div>
    <?php if (!empty($invoice['expires_at'])): ?>
    <div class="inv-row">
      <span class="inv-label"><?= $T['expires'] ?></span>
      <span class="countdown" id="countdown-timer">⏳ --:--:--</span>
    </div>
    <?php endif; ?>
    <!-- SLA info -->
    <div style="background:var(--sand);border-radius:var(--r2);padding:10px 14px;margin-top:12px;font-size:.78rem;color:var(--text2)">
      <?= $lang==='ar'
        ? '⏱️ الأوفلاين: 2-4 ساعات (مراجعة يدوية) | 💳 Gateway: 3-8 ثوانٍ (تلقائي)'
        : '⏱️ Offline: 2-4 hours (manual review) | 💳 Gateway: 3-8 seconds (automated)'
      ?>
    </div>
    <button class="btn btn-primary" onclick="goToUpload(<?= $invoice['id'] ?>)">
      <?= $T['next'] ?> →
    </button>
    <?php else: ?>
    <p style="color:var(--text2);text-align:center;padding:20px">
      <?= $lang==='ar' ? 'جاري تحضير الفاتورة...' : 'Preparing invoice...' ?>
    </p>
    <?php endif; ?>
  </div>
</div>

<!-- ══ HOLD MODEL — BANK CRITICAL ══ -->
<div style="background:#D1FAE5;border:1px solid #6EE7B7;border-radius:var(--r);padding:16px 18px;margin-bottom:12px;border-right:4px solid #16A34A">
  <p style="font-weight:700;color:#065F46;margin-bottom:4px">🔒 <?= $lang==='ar'?'هذا المبلغ محجوز فقط':'This amount is reserved only' ?></p>
  <p style="font-size:.85rem;color:#065F46;margin-bottom:4px"><?= $lang==='ar'?'لن يتم خصمه إلا بعد اكتمال الخدمة':'Will not be charged until service is completed' ?></p>
  <p style="font-size:.82rem;color:#065F46">✔ <?= $lang==='ar'?'في حال الإلغاء → استرجاع فوري للمحجوز':'Cancellation → immediate release of held funds' ?></p>
</div>

<!-- ══ BALANCE BREAKDOWN (async) ══ -->
<div id="balance-breakdown" style="background:var(--sand);border:1px solid var(--border);border-radius:var(--r2);padding:14px;margin-bottom:12px;display:none">
  <div style="display:flex;justify-content:space-between;font-size:.85rem;margin-bottom:6px">
    <span style="color:var(--text2)"><?= $lang==='ar'?'رصيدك الحالي:':'Your balance:' ?></span>
    <span id="bb-balance" style="font-weight:700">—</span>
  </div>
  <div style="display:flex;justify-content:space-between;font-size:.85rem;margin-bottom:6px">
    <span style="color:var(--text2)"><?= $lang==='ar'?'المحجوز (هذه الخدمة):':'Reserved (this service):' ?></span>
    <span id="bb-held" style="font-weight:700;color:var(--warning)">—</span>
  </div>
  <div style="height:1px;background:var(--border);margin:6px 0"></div>
  <div style="display:flex;justify-content:space-between;font-size:.88rem">
    <span style="color:var(--text2);font-weight:600"><?= $lang==='ar'?'المتاح بعد التنفيذ:':'Available after execution:' ?></span>
    <span id="bb-after" style="font-weight:700;color:var(--success)">—</span>
  </div>
</div>

<div class="trust-strip">
  <span class="tb" data-tip="<?= $lang==='ar'?'سودانا لا تحتفظ بأموالك — البنك هو مصدر الحقيقة':'Sudanna does not hold your funds — bank is source of truth' ?>">🏦 NO_CUSTODY</span>
  <span class="tb" data-tip="<?= $lang==='ar'?'التوقيع الرقمي HMAC-SHA256 لكل معاملة':'HMAC-SHA256 signature on every transaction' ?>">🔐 HMAC ✓</span>
  <span class="tb" data-tip="<?= $lang==='ar'?'إعادة المحاولة آمنة — بدون تكرار':'Retries are safe — no duplicates' ?>">🔄 Idempotent</span>
  <span class="tb" data-tip="<?= $lang==='ar'?'إيصال رسمي من finance@sudanna.ai':'Official receipt from finance@sudanna.ai' ?>">🧾 Receipt ✓</span>
  <span class="tb" style="background:#D1FAE5;border-color:#6EE7B7;color:#065F46">✔ <?= $lang==='ar'?'تنفيذ مضمون أو استرجاع':'Guaranteed or refund' ?></span>
</div>
<p style="font-size:.72rem;color:var(--text3);text-align:center;margin-top:8px">
  <?= $lang==='ar'
    ? 'سودانا تُنسّق المدفوعات. الأموال تُحتجز وتُسوَّى عبر البنك الشريك. سودانا لا تحتفظ بأموال المستخدمين.'
    : 'Sudanna orchestrates payments. Funds are held and settled by partner bank(s). Sudanna does not custody user funds.'
  ?>
</p>

<?php elseif ($step === 'upload'): ?>
<!-- ══ STEP 2: Proof Upload ══ -->
<div class="pay-card">
  <div class="pay-card-header">
    <span class="icon">📎</span>
    <h2><?= $T['upload_title'] ?></h2>
  </div>
  <div class="pay-card-body">
    <input type="hidden" id="upload-invoice-id" value="<?= $invoiceId ?>">

    <div class="alert alert-warning">
      <span>⚠️</span>
      <span><?= $lang==='ar' ? 'تأكد أن الإيصال يحتوي على الرمز المرجعي ورقم الحساب بوضوح' : 'Ensure the receipt clearly shows the reference code and account number' ?></span>
    </div>

    <div class="upload-zone" id="upload-zone">
      <input type="file" id="proof-file" accept="image/jpeg,image/png,image/jpg,image/webp">
      <div class="uz-icon">📎</div>
      <p><?= $T['upload_hint'] ?></p>
    </div>

    <div class="proof-preview" id="proof-preview">
      <img id="preview-img" src="" alt="">
      <div class="pf-info">
        <p class="pf-name" id="preview-name"></p>
        <p class="pf-size" id="preview-size"></p>
        <p class="pf-hash" id="preview-hash"></p>
      </div>
    </div>

    <button class="btn btn-primary" id="upload-btn" onclick="submitProof()" disabled>
      <span id="upload-btn-text"><?= $T['upload_btn'] ?></span>
      <div class="spinner" id="upload-spinner" style="display:none"></div>
    </button>
  </div>
</div>

<?php else: // status / receipt ?>
<!-- ══ STEP 3: Status / Confirmation ══ -->
<div class="pay-card">
  <div class="pay-card-header">
    <span class="icon"><?= $invoice && $invoice['status']==='paid' ? '✅' : '⏳' ?></span>
    <h2><?= $invoice && $invoice['status']==='paid' ? $T['status_ok'] : $T['status_pending'] ?></h2>
  </div>
  <div class="pay-card-body" style="text-align:center;padding:32px">
    <?php if ($invoice && $invoice['status'] === 'paid'): ?>
    <div class="status-badge status-paid" style="margin:0 auto 16px">✅ <?= $lang==='ar' ? 'تم قبول الدفعة' : 'Payment Confirmed' ?></div>
    <p style="color:var(--text2);margin-bottom:20px;font-size:.9rem">
      <?= $lang==='ar' ? 'تم إضافة الرصيد لمحفظتك. شكراً لاستخدامك سودانا!' : 'Balance added to your wallet. Thank you for using Sudanna!' ?>
    </p>
    <a href="<?= SITE_URL ?>/receipt.php?invoice_id=<?= $invoiceId ?>" class="btn btn-primary" style="text-decoration:none">
      <?= $T['receipt_btn'] ?> →
    </a>
    <?php else: ?>
    <div class="status-badge status-reviewing" style="margin:0 auto 16px">🔄 <?= $lang==='ar' ? 'قيد المراجعة' : 'Under Review' ?></div>
    <p style="color:var(--text2);margin-bottom:16px;font-size:.9rem">
      <?= $lang==='ar' ? 'تم استلام إيصالك. سيتم التحقق وإرسال إشعار خلال ساعتين.' : 'Receipt received. We will verify and notify you within 2 hours.' ?>
    </p>
    <button class="btn btn-primary" onclick="checkStatus(<?= $invoiceId ?>)">
      <?= $lang==='ar' ? 'تحقق من الحالة' : 'Check Status' ?>
    </button>
    <?php endif; ?>
  </div>
</div>
<?php endif; ?>

</div><!-- end pay-wrap -->

<div id="toast">
  <span id="toast-icon"></span>
  <span id="toast-msg"></span>
</div>

<script>
const SITE_URL = '<?= rtrim(SITE_URL,'/') ?>';
const LANG     = '<?= $lang ?>';
const INV_AMT  = <?= $invoice['amount'] ?? $amount ?? 0 ?>;

// ── Load balance breakdown (if user logged in) ────────────────
(function loadBalanceBreakdown() {
  fetch(SITE_URL + '/api/wallet/summary.php?period=7d', {credentials:'include'})
    .then(r => r.json())
    .then(data => {
      const cf = data.cashflow || {};
      const bal  = parseFloat(cf.balance_sdg || 0);
      const held = parseFloat(data.reserved_sdg || 0) + INV_AMT;
      const after = Math.max(0, bal - held);
      const fmt = n => n.toLocaleString('en-US', {minimumFractionDigits:2, maximumFractionDigits:2}) + ' SDG';
      document.getElementById('bb-balance').textContent = fmt(bal);
      document.getElementById('bb-held').textContent    = fmt(INV_AMT);
      document.getElementById('bb-after').textContent   = fmt(Math.max(0, bal - INV_AMT));
      document.getElementById('balance-breakdown').style.display = 'block';
    })
    .catch(() => {}); // silent — balance display is enhancement only
})();

// ── Toast ────────────────────────────────────────────────────────────
function showToast(msg, type='success') {
  const t = document.getElementById('toast');
  const icons = {success:'✅', error:'❌', info:'ℹ️'};
  t.className = type;
  document.getElementById('toast-icon').textContent = icons[type] || '';
  document.getElementById('toast-msg').textContent  = msg;
  t.classList.add('show');
  setTimeout(() => t.classList.remove('show'), 3500);
}

// ── Copy helper ────────────────────────────────────────────────────────
function copyText(text, label) {
  navigator.clipboard.writeText(text).then(() => showToast(label, 'success'));
}

// ── Countdown ─────────────────────────────────────────────────────────
(function() {
  const el = document.getElementById('countdown-timer');
  if (!el) return;
  const expiresAt = new Date('<?= $invoice['expires_at'] ?? '' ?>').getTime();
  if (!expiresAt) return;
  function tick() {
    const diff = expiresAt - Date.now();
    if (diff <= 0) { el.textContent = LANG==='ar' ? 'انتهت الصلاحية' : 'Expired'; el.classList.add('urgent'); return; }
    const h = Math.floor(diff/3600000);
    const m = Math.floor((diff%3600000)/60000);
    const s = Math.floor((diff%60000)/1000);
    el.textContent = `⏳ ${String(h).padStart(2,'0')}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`;
    if (diff < 7200000) el.classList.add('urgent');
  }
  tick(); setInterval(tick, 1000);
})();

// ── Create invoice if not exists ───────────────────────────────────────
(function() {
  const creating = document.getElementById('creating-inv');
  if (!creating) return;
  const service = '<?= $service ?>';
  const amount  = <?= $amount ?: 0 ?>;
  if (!service || !amount) { creating.innerHTML = '<p style="color:var(--danger)">❌ بيانات ناقصة</p>'; return; }

  fetch(SITE_URL + '/api/payment/create_invoice.php', {
    method: 'POST',
    headers: {'Content-Type':'application/json'},
    credentials: 'include',
    body: JSON.stringify({service, amount, method:'offline'})
  })
  .then(r => r.json())
  .then(data => {
    if (data.success && data.invoice_id) {
      // Redirect with the new invoice_id
      window.location.href = SITE_URL + '/payment.php?invoice_id=' + data.invoice_id;
    } else {
      creating.innerHTML = `<p style="color:var(--danger)">❌ ${data.error || 'خطأ في إنشاء الفاتورة'}</p>`;
    }
  })
  .catch(() => { creating.innerHTML = '<p style="color:var(--danger)">❌ خطأ في الاتصال</p>'; });
})();

// ── Go to upload step ──────────────────────────────────────────────────
function goToUpload(invId) {
  window.location.href = SITE_URL + '/payment.php?invoice_id=' + invId + '&step=upload';
}

// ── File handling ─────────────────────────────────────────────────────
const fileInput = document.getElementById('proof-file');
const uploadZone = document.getElementById('upload-zone');

if (fileInput) {
  fileInput.addEventListener('change', () => handleFile(fileInput.files[0]));

  uploadZone.addEventListener('dragover', e => { e.preventDefault(); uploadZone.classList.add('dragover'); });
  uploadZone.addEventListener('dragleave', () => uploadZone.classList.remove('dragover'));
  uploadZone.addEventListener('drop', e => {
    e.preventDefault(); uploadZone.classList.remove('dragover');
    const f = e.dataTransfer.files[0];
    if (f) { fileInput.files = e.dataTransfer.files; handleFile(f); }
  });
}

async function handleFile(file) {
  if (!file) return;
  const maxMB = 5;
  if (file.size > maxMB * 1024 * 1024) {
    showToast(LANG==='ar' ? 'الملف أكبر من 5MB' : 'File exceeds 5MB', 'error'); return;
  }
  const allowed = ['image/jpeg','image/png','image/jpg','image/webp'];
  if (!allowed.includes(file.type)) {
    showToast(LANG==='ar' ? 'نوع ملف غير مسموح — JPG/PNG فقط' : 'Invalid type — JPG/PNG only', 'error'); return;
  }

  // Preview
  const reader = new FileReader();
  reader.onload = e => {
    document.getElementById('preview-img').src = e.target.result;
    document.getElementById('preview-name').textContent = file.name;
    document.getElementById('preview-size').textContent = (file.size / 1024).toFixed(1) + ' KB';
    document.getElementById('proof-preview').classList.add('show');
  };
  reader.readAsDataURL(file);

  // Compute SHA256 hash
  const buf  = await file.arrayBuffer();
  const hash = await crypto.subtle.digest('SHA-256', buf);
  const hex  = Array.from(new Uint8Array(hash)).map(b => b.toString(16).padStart(2,'0')).join('');
  document.getElementById('preview-hash').textContent = 'SHA256: ' + hex.substring(0,16) + '...';
  fileInput._hash = hex;

  document.getElementById('upload-btn').disabled = false;
}

// ── Submit proof ───────────────────────────────────────────────────────
function submitProof() {
  const btn  = document.getElementById('upload-btn');
  const spin = document.getElementById('upload-spinner');
  const txt  = document.getElementById('upload-btn-text');
  const invId = document.getElementById('upload-invoice-id')?.value;
  const file  = fileInput?.files[0];
  if (!file || !invId) return;

  btn.disabled = true;
  spin.style.display = 'block';
  txt.textContent = LANG==='ar' ? 'جاري الرفع...' : 'Uploading...';

  const fd = new FormData();
  fd.append('invoice_id', invId);
  fd.append('proof', file);

  fetch(SITE_URL + '/api/payment/upload_proof.php', {
    method: 'POST',
    credentials: 'include',
    body: fd
  })
  .then(r => r.json())
  .then(data => {
    spin.style.display = 'none';
    if (data.success) {
      showToast(LANG==='ar' ? 'تم رفع الإيصال بنجاح ✅' : 'Proof uploaded ✅', 'success');
      setTimeout(() => {
        window.location.href = SITE_URL + '/payment.php?invoice_id=' + invId + '&step=status';
      }, 1500);
    } else {
      btn.disabled = false;
      txt.textContent = LANG==='ar' ? 'أعد المحاولة' : 'Retry';
      const msg = data.code === 'DUPLICATE_PROOF'
        ? (LANG==='ar' ? 'هذه الصورة مستخدمة مسبقاً' : 'This image was already used')
        : (data.error || 'Upload failed');
      showToast(msg, 'error');
    }
  })
  .catch(() => {
    spin.style.display='none'; btn.disabled=false;
    txt.textContent = LANG==='ar' ? 'أعد المحاولة' : 'Retry';
    showToast(LANG==='ar' ? 'خطأ في الاتصال' : 'Connection error', 'error');
  });
}

// ── Check status ───────────────────────────────────────────────────────
function checkStatus(invId) {
  fetch(SITE_URL + '/api/payment/status.php?invoice_id=' + invId, {credentials:'include'})
  .then(r => r.json())
  .then(data => {
    if (data.status === 'paid') window.location.reload();
    else showToast(LANG==='ar' ? `الحالة: ${data.status}` : `Status: ${data.status}`, 'info');
  });
}
</script>
</body>
</html>
