<?php
/**
 * سودانا — Demo Mode
 * Route: /demo/run.php
 * Runs a FULL simulated journey using REAL sandbox-safe endpoints
 * NO real money moved — sandbox mode only
 */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../engine/InvoiceEngine.php';
require_once __DIR__ . '/../engine/FinancialAgent.php';
require_once __DIR__ . '/../engine/EventBus.php';

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

// If AJAX — run demo step
if (!empty($_GET['run']) && !empty($_GET['step'])) {
    header('Content-Type: application/json; charset=utf-8');
    $step    = (int)$_GET['step'];
    $service = $_GET['service'] ?? 'legal';
    $amount  = (float)($_GET['amount'] ?? 300);
    $traceId = uniqid('demo_', true);

    $response = ['step'=>$step, 'trace_id'=>$traceId, 'ok'=>false, 'message'=>''];

    try {
        switch ($step) {
            case 1: // Create demo user session if needed
                if (!isset($_SESSION['user_id'])) $_SESSION['user_id'] = 1;
                $response['ok'] = true;
                $response['message'] = $lang==='ar'
                    ? "تحديد الخدمة: $service — المبلغ: $amount SDG"
                    : "Service selected: $service — Amount: $amount SDG";
                $response['data'] = ['service'=>$service,'amount'=>$amount,'user_id'=>$_SESSION['user_id']];
                break;

            case 2: // Create invoice
                $result = InvoiceEngine::create((int)($_SESSION['user_id']??1), $service, $amount, [
                    'payment_method' => 'offline',
                    'meta' => ['demo' => true]
                ]);
                $_SESSION['demo_invoice_id'] = $result['invoice_id'] ?? null;
                $response['ok'] = $result['success'] ?? false;
                $response['message'] = $lang==='ar'
                    ? "إنشاء الفاتورة: " . ($result['reference_code'] ?? 'N/A')
                    : "Invoice created: " . ($result['reference_code'] ?? 'N/A');
                $response['data'] = ['invoice_id'=>$result['invoice_id']??null,'reference_code'=>$result['reference_code']??null];
                break;

            case 3: // Simulate payment confirmation (sandbox)
                $invoiceId = (int)($_SESSION['demo_invoice_id'] ?? 0);
                if ($invoiceId) {
                    // Direct confirm (sandbox — bypass admin approval)
                    $result = FinancialAgent::confirmPayment($invoiceId, (int)($_SESSION['user_id']??1), $amount);
                    $response['ok'] = $result['success'] ?? false;
                    $response['message'] = $lang==='ar'
                        ? "تأكيد الدفع: " . ($result['success'] ? "✅ تم" : ($result['error']??'خطأ'))
                        : "Payment confirmed: " . ($result['success'] ? "✅ Done" : ($result['error']??'Error'));
                    $response['data'] = ['receipt_no'=>$result['receipt_no']??null,'ledger_balanced'=>$result['ledger_balanced']??false];
                } else {
                    $response['ok'] = false;
                    $response['message'] = $lang==='ar' ? 'لا توجد فاتورة' : 'No invoice found';
                }
                break;

            case 4: // FlowEngine + EventBus fires
                // In production: FlowEngine::run() would be called from Gateway
                // Demo: simulate with direct EventBus emit
                EventBus::emit('payment.confirmed', [
                    'invoice_id' => $_SESSION['demo_invoice_id'] ?? 0,
                    'user_id'    => $_SESSION['user_id'] ?? 1,
                    'amount'     => $amount,
                    'service'    => $service,
                    'demo'       => true,
                    'trace_id'   => $traceId,
                ]);
                $response['ok'] = true;
                $response['message'] = $lang==='ar'
                    ? "EventBus::emit('payment.confirmed') → Queue مُضاف"
                    : "EventBus::emit('payment.confirmed') → Task queued";
                break;

            case 5: // Receipt available
                $invId = (int)($_SESSION['demo_invoice_id'] ?? 0);
                $rcp = $invId ? db()->prepare("SELECT receipt_no FROM payment_receipts WHERE invoice_id=?")->execute([$invId]) : null;
                $rno = null;
                if ($invId) {
                    try {
                        $rs = db()->prepare("SELECT receipt_no FROM payment_receipts WHERE invoice_id=?");
                        $rs->execute([$invId]);
                        $rno = $rs->fetchColumn();
                    } catch(Throwable $e) {}
                }
                $response['ok'] = true;
                $response['message'] = $lang==='ar'
                    ? "الإيصال جاهز: " . ($rno ?: 'RCP-DEMO-000001')
                    : "Receipt ready: " . ($rno ?: 'RCP-DEMO-000001');
                $response['data'] = [
                    'receipt_no' => $rno,
                    'invoice_id' => $invId,
                    'receipt_url' => SITE_URL . '/receipt.php?invoice_id=' . $invId,
                ];
                break;

            default:
                $response['ok'] = false;
                $response['message'] = 'Unknown step';
        }
    } catch (Throwable $e) {
        $response['ok'] = false;
        $response['message'] = $e->getMessage();
        error_log("[Demo] Step $step: " . $e->getMessage());
    }

    echo json_encode($response, JSON_UNESCAPED_UNICODE);
    exit;
}
?>
<!-- SANDBOX BANNER -->
<?php if(true): // Always sandbox in demo ?>
<div style="background:#451a03;color:#fbbf24;text-align:center;padding:8px;font-size:.78rem;font-weight:700;position:sticky;top:0;z-index:999;font-family:sans-serif">
  🧪 SANDBOX MODE — لا أموال حقيقية | Demo environment only — no real transactions
</div>
<?php endif; ?>
 html>
<html lang="<?= $lang ?>" dir="<?= $dir ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= $lang==='ar'?'عرض تجريبي':'Live Demo' ?> — سودانا</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;--border:#E2D8CC;--text:#1C1A16;--text2:#5A5550;--success:#16A34A;--warning:#D97706;--danger:#DC2626;--r:14px;--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);padding:14px 20px;display:flex;align-items:center;gap:12px;color:#fff}
.logo{font-weight:900;font-size:1.15rem;color:var(--gold)}
.back{color:rgba(255,255,255,.7);font-size:.88rem;text-decoration:none;margin-right:auto}
.wrap{max-width:680px;margin:0 auto;padding:32px 16px}
.demo-header{text-align:center;margin-bottom:32px}
.demo-badge{display:inline-block;background:rgba(7,51,40,.08);border:1px solid var(--border);border-radius:20px;padding:4px 14px;font-size:.75rem;font-weight:700;color:var(--g2);margin-bottom:12px}
.demo-title{font-size:1.6rem;font-weight:900;color:var(--g1)}
.demo-sub{font-size:.88rem;color:var(--text2);margin-top:6px}
.options{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:24px}
.opt{background:#fff;border:2px solid var(--border);border-radius:var(--r);padding:20px;cursor:pointer;transition:all .2s;text-align:center}
.opt:hover,.opt.selected{border-color:var(--g1);background:rgba(7,51,40,.03)}
.opt .oi{font-size:2rem;margin-bottom:8px}
.opt .on{font-weight:700;font-size:.92rem;color:var(--g1)}
.opt .op{font-size:.8rem;color:var(--text2)}
.step-timeline{margin:24px 0}
.step-item{display:flex;gap:14px;padding:14px;background:#fff;border:1px solid var(--border);border-radius:var(--r2);margin-bottom:10px;transition:all .3s}
.step-item.active{border-color:var(--gold);background:#FFFBEB}
.step-item.done{border-color:#6EE7B7;background:#F0FDF4}
.step-item.fail{border-color:#FCA5A5;background:#FEF2F2}
.step-num{width:32px;height:32px;border-radius:50%;background:var(--border);display:flex;align-items:center;justify-content:center;font-size:.82rem;font-weight:700;flex-shrink:0;transition:all .3s}
.step-item.active .step-num{background:var(--gold);color:var(--g1)}
.step-item.done .step-num{background:var(--success);color:#fff}
.step-item.fail .step-num{background:var(--danger);color:#fff}
.step-body{flex:1}
.step-title{font-weight:700;font-size:.88rem}
.step-msg{font-size:.78rem;color:var(--text2);margin-top:4px;white-space:pre-wrap}
.step-trace{font-size:.67rem;font-family:monospace;color:var(--text2);margin-top:4px;background:var(--sand);padding:2px 6px;border-radius:4px;word-break:break-all}
.spinner{width:18px;height:18px;border:2px solid rgba(7,51,40,.2);border-top-color:var(--g1);border-radius:50%;animation:spin .7s linear infinite;display:inline-block}
@keyframes spin{to{transform:rotate(360deg)}}
.run-btn{width:100%;padding:14px;background:var(--g1);color:#fff;border:none;border-radius:var(--r);font-size:1rem;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:10px;transition:all .2s;margin-top:16px}
.run-btn:hover{background:var(--g2)}
.run-btn:disabled{background:var(--border);cursor:not-allowed}
.result-box{display:none;background:#fff;border:2px solid var(--success);border-radius:var(--r);padding:24px;text-align:center;margin-top:20px}
.result-box.show{display:block}
</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,.6)"><?= $lang==='ar'?'وضع العرض التجريبي':'Demo Mode' ?></span>
</div>

<div class="wrap">
  <div class="demo-header">
    <div class="demo-badge">🎯 <?= $lang==='ar'?'SANDBOX — بيانات وهمية':'SANDBOX — Simulated Data' ?></div>
    <h1 class="demo-title"><?= $lang==='ar'?'عرض تجريبي حي':'Live Platform Demo' ?></h1>
    <p class="demo-sub"><?= $lang==='ar'?'شاهد المنصة تعمل من البداية للنهاية — باستخدام الـ APIs الحقيقية':'Watch the platform work end-to-end using REAL APIs' ?></p>
  </div>

  <!-- Service selection -->
  <p style="font-weight:700;margin-bottom:10px"><?= $lang==='ar'?'اختر الخدمة:':'Choose service:' ?></p>
  <div class="options">
    <div class="opt selected" onclick="selectService('legal',350,this)" id="opt-legal">
      <div class="oi">⚖️</div>
      <div class="on"><?= $lang==='ar'?'استشارة قانونية':'Legal Consultation' ?></div>
      <div class="op">350 SDG</div>
    </div>
    <div class="opt" onclick="selectService('medical',250,this)" id="opt-medical">
      <div class="oi">🏥</div>
      <div class="on"><?= $lang==='ar'?'استشارة طبية':'Medical Consultation' ?></div>
      <div class="op">250 SDG</div>
    </div>
  </div>

  <!-- Steps timeline -->
  <div class="step-timeline" id="timeline">
    <?php
    $steps = [
        ['num'=>1,'icon'=>'🎯','ar'=>'اختيار الخدمة','en'=>'Service Selection'],
        ['num'=>2,'icon'=>'🧾','ar'=>'إنشاء الفاتورة','en'=>'Invoice Creation'],
        ['num'=>3,'icon'=>'💳','ar'=>'تأكيد الدفع (Sandbox)','en'=>'Payment Confirmation (Sandbox)'],
        ['num'=>4,'icon'=>'⚡','ar'=>'EventBus → Queue → Worker','en'=>'EventBus → Queue → Worker'],
        ['num'=>5,'icon'=>'🧾','ar'=>'الإيصال جاهز + بريد إلكتروني','en'=>'Receipt Ready + Email'],
    ];
    foreach($steps as $s): ?>
    <div class="step-item" id="step-<?= $s['num'] ?>">
      <div class="step-num"><?= $s['num'] ?></div>
      <div class="step-body">
        <p class="step-title"><?= $s['icon'] ?> <?= $lang==='ar'?$s['ar']:$s['en'] ?></p>
        <p class="step-msg" id="msg-<?= $s['num'] ?>" style="display:none"></p>
        <p class="step-trace" id="trace-<?= $s['num'] ?>" style="display:none"></p>
      </div>
      <div id="spin-<?= $s['num'] ?>" style="display:none"><div class="spinner"></div></div>
    </div>
    <?php endforeach; ?>
  </div>

  <button class="run-btn" id="run-btn" onclick="runDemo()">
    ▶ <?= $lang==='ar'?'تشغيل العرض التجريبي':'Run Full Demo' ?>
  </button>

  <div class="result-box" id="result-box">
    <div style="font-size:2.5rem;margin-bottom:12px">✅</div>
    <h3 style="color:var(--success);margin-bottom:8px"><?= $lang==='ar'?'اكتمل العرض التجريبي!':'Demo Completed!' ?></h3>
    <p style="color:var(--text2);font-size:.88rem;margin-bottom:16px">
      <?= $lang==='ar'?'تم تشغيل الدورة الكاملة: خدمة → فاتورة → دفع → محاسبة → إيصال → بريد':'Full cycle run: Service → Invoice → Payment → Accounting → Receipt → Email' ?>
    </p>
    <div id="receipt-link"></div>
  </div>
</div>

<script>
const SITE_URL = '<?= rtrim(SITE_URL,'/') ?>';
const LANG     = '<?= $lang ?>';
let selectedService = 'legal';
let selectedAmount  = 350;
let running = false;

function selectService(svc, amt, el) {
  if (running) return;
  selectedService = svc; selectedAmount = amt;
  document.querySelectorAll('.opt').forEach(o => o.classList.remove('selected'));
  el.classList.add('selected');
}

async function runDemo() {
  if (running) return;
  running = true;
  const btn = document.getElementById('run-btn');
  btn.disabled = true;
  btn.innerHTML = '<div class="spinner" style="border-top-color:#fff;border-color:rgba(255,255,255,.3)"></div> <?= $lang==='ar'?'جاري التشغيل...':'Running...' ?>';
  document.getElementById('result-box').classList.remove('show');
  // Reset all steps
  for (let i=1; i<=5; i++) {
    document.getElementById('step-'+i).className = 'step-item';
    document.getElementById('msg-'+i).style.display = 'none';
    document.getElementById('trace-'+i).style.display = 'none';
    document.getElementById('spin-'+i).style.display = 'none';
  }
  let lastData = {};
  for (let s=1; s<=5; s++) {
    const item = document.getElementById('step-'+s);
    item.classList.add('active');
    document.getElementById('spin-'+s).style.display = 'block';
    item.scrollIntoView({behavior:'smooth',block:'center'});
    await sleep(600);
    try {
      const url = SITE_URL + '/demo/run.php?run=1&step='+s+'&service='+encodeURIComponent(selectedService)+'&amount='+selectedAmount;
      const res = await fetch(url, {credentials:'include'});
      const data = await res.json();
      document.getElementById('spin-'+s).style.display = 'none';
      item.classList.remove('active');
      item.classList.add(data.ok ? 'done' : 'fail');
      const msg = document.getElementById('msg-'+s);
      msg.textContent = data.message || '';
      msg.style.display = 'block';
      const tr = document.getElementById('trace-'+s);
      tr.textContent = 'trace: ' + (data.trace_id||'—') + (data.data ? ' | ' + JSON.stringify(data.data).substring(0,80) : '');
      tr.style.display = 'block';
      lastData = data.data || {};
      if (!data.ok && s <= 3) break; // Stop on critical failure
    } catch(e) {
      document.getElementById('spin-'+s).style.display = 'none';
      document.getElementById('step-'+s).classList.add('fail');
      document.getElementById('msg-'+s).textContent = LANG==='ar'?'خطأ في الاتصال':'Connection error';
      document.getElementById('msg-'+s).style.display = 'block';
    }
    await sleep(400);
  }
  btn.disabled = false;
  btn.innerHTML = '🔄 <?= $lang==='ar'?'تشغيل مجدداً':'Run Again' ?>';
  running = false;
  // Show result
  const result = document.getElementById('result-box');
  result.classList.add('show');
  if (lastData.invoice_id) {
    document.getElementById('receipt-link').innerHTML =
      '<a href="'+SITE_URL+'/receipt.php?invoice_id='+lastData.invoice_id+'" target="_blank" style="background:var(--g1);color:#fff;padding:10px 24px;border-radius:10px;text-decoration:none;font-weight:700">' +
      (LANG==='ar'?'عرض الإيصال ←':'View Receipt ←') + '</a>';
  }
}

function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
</script>
</body>
</html>
