<?php
/**
 * سودانا — Receipt Screen
 * Route: /receipt.php?invoice_id=X  OR  ?ref=SD-xxx
 */
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/engine/FinancialAgent.php';

session_start();
$lang = $_SESSION['lang'] ?? 'ar';
$dir  = $lang === 'ar' ? 'rtl' : 'ltr';

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

$invoice = null; $receipt = null; $ledger = null;
try {
    if ($invoiceId) {
        $q = db()->prepare("SELECT * FROM invoices WHERE id=?");
        $q->execute([$invoiceId]);
    } elseif ($ref) {
        $q = db()->prepare("SELECT * FROM invoices WHERE reference_code=?");
        $q->execute([$ref]);
    }
    $invoice = $q ? $q->fetch(PDO::FETCH_ASSOC) : null;

    if ($invoice) {
        $rq = db()->prepare("SELECT * FROM payment_receipts WHERE invoice_id=?");
        $rq->execute([$invoice['id']]);
        $receipt = $rq->fetch(PDO::FETCH_ASSOC);

        $lv = FinancialAgent::verifyLedger();
        $ledger = $lv;
    }
} catch (Throwable $e) { $error = $e->getMessage(); }

$serviceLabels = [
    'legal'=>['ar'=>'استشارة قانونية','en'=>'Legal Consultation'],
    'medical'=>['ar'=>'استشارة طبية','en'=>'Medical Consultation'],
    'business'=>['ar'=>'استشارة أعمال','en'=>'Business Consulting'],
    'general'=>['ar'=>'خدمة سودانا','en'=>'Sudanna Service'],
];
$sl = $invoice ? ($serviceLabels[$invoice['service'] ?? 'general'][$lang] ?? 'Service') : '';
?>
<!DOCTYPE html>
<html lang="<?= $lang ?>" dir="<?= $dir ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= $lang==='ar' ? 'إيصال الدفع' : 'Payment Receipt' ?> — سودانا</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;--sand:#FAF6EF;--sand2:#F0E8DC;--border:#E2D8CC;--text:#1C1A16;--text2:#5A5550;--success:#16A34A;--r:16px;--r2:10px}
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:'Cairo',sans-serif;background:var(--sand);color:var(--text);min-height:100vh}
.topbar{background:var(--g1);color:#fff;padding:14px 20px;display:flex;align-items:center;gap:12px}
.topbar .logo{font-weight:900;font-size:1.15rem;color:var(--gold)}
.topbar .back{color:rgba(255,255,255,.7);font-size:.88rem;text-decoration:none;margin-right:auto}
.wrap{max-width:560px;margin:0 auto;padding:24px 16px}
.receipt-card{background:#fff;border:2px solid var(--g2);border-radius:var(--r);overflow:hidden;box-shadow:0 8px 32px rgba(7,51,40,.12)}
.receipt-header{background:var(--g1);color:#fff;padding:24px;text-align:center}
.receipt-header .logo-lg{font-size:1.6rem;font-weight:900;color:var(--gold)}
.receipt-header p{font-size:.82rem;color:rgba(255,255,255,.7);margin-top:4px}
.rcp-no{display:inline-block;background:var(--gold);color:var(--g1);font-weight:900;font-size:.88rem;padding:4px 14px;border-radius:20px;margin-top:10px}
.receipt-body{padding:24px}
.row{display:flex;justify-content:space-between;align-items:center;padding:10px 0;border-bottom:1px solid var(--sand2)}
.row:last-child{border:none}
.rl{font-size:.85rem;color:var(--text2)}
.rv{font-size:.9rem;font-weight:600;text-align:left}
.rv.big{font-size:1.6rem;font-weight:900;color:var(--g1)}
.rv.mono{font-family:monospace;font-size:.8rem;background:var(--sand);padding:3px 8px;border-radius:5px;word-break:break-all}
.badge-ok{background:#D1FAE5;color:#065F46;padding:4px 12px;border-radius:20px;font-size:.8rem;font-weight:700}
.badge-pending{background:#FEF3C7;color:#92400E;padding:4px 12px;border-radius:20px;font-size:.8rem;font-weight:700}
.receipt-footer{background:var(--sand);border-top:1px solid var(--border);padding:16px 24px;text-align:center;font-size:.78rem;color:var(--text2)}
.actions{display:flex;gap:10px;margin:16px 0;flex-wrap:wrap}
.action-btn{flex:1;padding:10px 16px;border-radius:var(--r2);font-weight:700;font-size:.85rem;border:1.5px solid var(--g2);background:transparent;color:var(--g2);cursor:pointer;display:flex;align-items:center;justify-content:center;gap:6px;transition:all .2s;text-decoration:none}
.action-btn:hover{background:var(--g2);color:#fff}
.action-btn.primary{background:var(--g1);color:#fff;border-color:var(--g1)}
.action-btn.primary:hover{background:var(--g2)}
.not-found{text-align:center;padding:48px 20px}
.not-found h2{color:var(--text2);margin-bottom:12px}

/* ── PRINT ─────────────────────────── */
@media print {
  .topbar, .actions, .action-btn { display:none !important; }
  body { background:#fff; }
  .receipt-card { box-shadow:none; border:1px solid #ccc; }
}
/* ── LOADING ─────────────────────────── */
@keyframes fadeIn { from{opacity:0;transform:translateY(8px)} to{opacity:1;transform:none} }
.receipt-card { animation:fadeIn .4s ease; }
@media(max-width:560px){ .wrap{padding:16px 10px} .row{flex-direction:column;gap:2px} }
</style>
</head>
<body>
<div class="topbar">
  <span class="logo">🇸🇩 سودانا</span>
  <a href="<?= SITE_URL ?>/" class="back">← <?= $lang==='ar' ? 'العودة' : 'Back' ?></a>
  <span style="font-size:.82rem;color:rgba(255,255,255,.7)"><?= $lang==='ar' ? 'إيصال الدفع' : 'Receipt' ?></span>
</div>

<div class="wrap">
<?php if (!$invoice): ?>
<div class="not-found">
  <h2>🔍 <?= $lang==='ar' ? 'الفاتورة غير موجودة' : 'Invoice not found' ?></h2>
  <p style="color:var(--text2)"><?= $lang==='ar' ? 'تحقق من الرمز المرجعي' : 'Check the reference code' ?></p>
</div>
<?php else: ?>
<div class="receipt-card">
  <div class="receipt-header">
    <div class="logo-lg">🇸🇩 سودانا</div>
    <p><?= $lang==='ar' ? 'إيصال دفع رسمي' : 'Official Payment Receipt' ?></p>
    <?php if ($receipt): ?>
    <div class="rcp-no"><?= htmlspecialchars($receipt['receipt_no']) ?></div>
    <?php endif; ?>
  </div>
  <div class="receipt-body">
    <?php if ($receipt): ?>
    <div class="row"><span class="rl"><?= $lang==='ar' ? 'رقم الإيصال' : 'Receipt No.' ?></span><span class="rv mono"><?= htmlspecialchars($receipt['receipt_no']) ?></span></div>
    <?php endif; ?>
    <div class="row"><span class="rl"><?= $lang==='ar' ? 'رقم الفاتورة' : 'Invoice ID' ?></span><span class="rv">#<?= $invoice['id'] ?></span></div>
    <div class="row"><span class="rl"><?= $lang==='ar' ? 'الرمز المرجعي' : 'Reference' ?></span><span class="rv mono"><?= htmlspecialchars($invoice['reference_code'] ?? '—') ?></span></div>
    <div class="row"><span class="rl"><?= $lang==='ar' ? 'الخدمة' : 'Service' ?></span><span class="rv"><?= $sl ?></span></div>
    <div class="row">
      <span class="rl"><?= $lang==='ar' ? 'المبلغ' : 'Amount' ?></span>
      <span class="rv big"><?= number_format($invoice['amount'],2) ?> <small style="font-size:.9rem;font-weight:600">SDG</small></span>
    </div>
    <div class="row"><span class="rl"><?= $lang==='ar' ? 'طريقة الدفع' : 'Payment Method' ?></span>
      <span class="rv"><?= ($invoice['payment_method']??'offline') === 'gateway' ? ($lang==='ar'?'دفع إلكتروني':'Online Payment') : ($lang==='ar'?'تحويل بنكي':'Bank Transfer') ?></span>
    </div>
    <div class="row"><span class="rl"><?= $lang==='ar' ? 'حالة الدفع' : 'Status' ?></span>
      <span class="<?= $invoice['status']==='paid' ? 'badge-ok' : 'badge-pending' ?>">
        <?= $invoice['status']==='paid' ? ($lang==='ar'?'✅ مدفوع':'✅ Paid') : ($lang==='ar'?'⏳ معلق':'⏳ Pending') ?>
      </span>
    </div>
    <?php if ($invoice['paid_at']): ?>
    <div class="row"><span class="rl"><?= $lang==='ar' ? 'وقت الدفع' : 'Paid At' ?></span><span class="rv"><?= date('d/m/Y — h:i A', strtotime($invoice['paid_at'])) ?></span></div>
    <?php endif; ?>
    <div class="row">
      <span class="rl"><?= $lang==='ar' ? 'التوازن المحاسبي' : 'Ledger Balance' ?></span>
      <span class="<?= ($ledger['balanced']??false) ? 'badge-ok' : 'badge-pending' ?>">
        <?= ($ledger['balanced']??false) ? '✅ متوازن' : '⚠️ قيد المراجعة' ?>
      </span>
    </div>
  </div>
  <div class="receipt-footer">
    <?= $lang==='ar' ? 'هذا الإيصال أُرسل إلكترونياً من' : 'This receipt was sent electronically from' ?>
    <strong>finance@sudanna.ai</strong>
  </div>
</div>

<!-- Execution trace badge -->
<?php
$execMeta = json_decode($invoice['notes'] ?? '{}', true);
$execId   = $execMeta['execution_id'] ?? null;
?>
<?php if($execId): ?>
<div style="font-size:.68rem;color:var(--text3);font-family:monospace;padding:6px 12px;background:var(--sand);border-radius:6px;margin-bottom:12px;display:flex;align-items:center;gap:8px">
  🔍 <span id="exec-id-val"><?= htmlspecialchars($execId) ?></span>
  <button onclick="navigator.clipboard.writeText('<?= htmlspecialchars($execId) ?>');this.textContent='✓ نُسخ'" style="border:none;background:none;font-size:.65rem;color:var(--g3);cursor:pointer;font-family:Cairo,sans-serif">⎘ نسخ</button>
</div>
<?php endif; ?>

<div class="actions">
  <button class="action-btn" onclick="printReceipt()">🖨️ <?= $lang==='ar' ? 'طباعة' : 'Print' ?></button>
  <button class="action-btn" onclick="resendEmail()">📧 <?= $lang==='ar' ? 'إعادة الإرسال' : 'Resend Email' ?></button>
  <a href="<?= SITE_URL ?>/" class="action-btn primary">🏠 <?= $lang==='ar' ? 'الرئيسية' : 'Home' ?></a>

    <?php if ($receipt && ($invoice['status'] ?? '') === 'paid'): ?>
    <a href="https://wa.me/?text=<?= rawurlencode('إيصال سودانا '.($receipt['receipt_no']??'').' - '.number_format((float)($invoice['amount_sdg']??0),2).' SDG') ?>" target="_blank" class="action-btn" style="background:#25D366;color:#fff;border-color:#25D366">
      📤 <?= $lang==='ar'?'شارك':'Share' ?>
    </a>
    <?php endif; ?>
</div>
<?php endif; ?>
</div>

<script>
function printReceipt() { window.print(); }
function resendEmail() {
  alert('<?= $lang==='ar' ? 'سيُرسَل الإيصال لبريدك الإلكتروني خلال لحظات' : 'Receipt will be emailed to you shortly' ?>');
}
</script>
</body>
</html>
