<?php
require_once dirname(__DIR__).'/config.php';
$u = current_user(); if(!$u){header('Location: ' . url('?login=1'));exit;}
?>
/**
 * سودانا — Booking Flow UI
 * Route: /app/flow.php?category=legal&amount=350
 * Connects to StepController via visitor_ask.php
 */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../engine/InvoiceEngine.php';
session_start();
$lang     = $_SESSION['lang'] ?? 'ar';
$dir      = $lang === 'ar' ? 'rtl' : 'ltr';
$userId   = (int)($_SESSION['user_id'] ?? 0);
$category = htmlspecialchars($_GET['category'] ?? 'legal', ENT_QUOTES);
$amount   = max(0, (float)($_GET['amount'] ?? 300));

$steps_ar = [
    ['num'=>1,'label'=>'نوع الخدمة','icon'=>'📋'],
    ['num'=>2,'label'=>'المعلومات','icon'=>'📝'],
    ['num'=>3,'label'=>'اختيار المزوّد','icon'=>'👤'],
    ['num'=>4,'label'=>'تأكيد + دفع','icon'=>'💳'],
];
$steps_en = [
    ['num'=>1,'label'=>'Service Type','icon'=>'📋'],
    ['num'=>2,'label'=>'Your Details','icon'=>'📝'],
    ['num'=>3,'label'=>'Select Provider','icon'=>'👤'],
    ['num'=>4,'label'=>'Confirm + Pay','icon'=>'💳'],
];
$steps = $lang==='ar' ? $steps_ar : $steps_en;

$svcNames = [
    'medical'=>['ar'=>'الاستشارة الطبية','en'=>'Medical Consultation'],
    'legal'=>['ar'=>'الاستشارة القانونية','en'=>'Legal Consultation'],
    'business'=>['ar'=>'استشارة الأعمال','en'=>'Business Consulting'],
    'education'=>['ar'=>'الدعم التعليمي','en'=>'Educational Support'],
    'engineering'=>['ar'=>'الاستشارة الهندسية','en'=>'Engineering Consulting'],
    'agriculture'=>['ar'=>'الاستشارة الزراعية','en'=>'Agriculture Consulting'],
];
$svcName = $svcNames[$category][$lang] ?? ucfirst($category);
?>
<!DOCTYPE html>
<html lang="<?= $lang ?>" dir="<?= $dir ?>">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= htmlspecialchars($svcName) ?> — سودانا</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;--r:14px;--r2:10px;--success:#16A34A}
.exec-banner{display:flex;align-items:center;gap:10px;padding:9px 20px;font-size:.85rem;font-weight:600;transition:background .4s,color .3s;border-bottom:1px solid rgba(0,0,0,.06)}
.exec-init   {background:#FEF3C7;color:#92400E}
.exec-running{background:#DBEAFE;color:#1E40AF}
.exec-success{background:#D1FAE5;color:#065F46}
.exec-failed {background:#FEE2E2;color:#991B1B}
.exec-banner.show{animation:bannerIn .3s ease}
@keyframes bannerIn{from{opacity:0;transform:translateY(-6px)}to{opacity:1;transform:none}}

*{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}
.topbar .logo{font-weight:900;font-size:1.1rem;color:var(--gold)}
.topbar a{color:rgba(255,255,255,.7);font-size:.85rem;text-decoration:none}
.progress-bar{background:#fff;border-bottom:1px solid var(--border);padding:16px 20px}
.steps{display:flex;align-items:center;max-width:520px;margin:0 auto}
.step{flex:1;text-align:center;position:relative}
.step:not(:last-child)::after{content:'';position:absolute;top:12px;<?= $dir==='rtl'?'right':'left' ?>:50%;width:100%;height:2px;background:var(--border)}
.step.done:not(:last-child)::after{background:var(--g3)}
.step-dot{width:26px;height:26px;border-radius:50%;border:2px solid var(--border);background:#fff;display:inline-flex;align-items:center;justify-content:center;font-size:.72rem;font-weight:700;position:relative;z-index:1;transition:all .3s}
.step-dot.done{background:var(--g1);border-color:var(--g1);color:#fff}
.step-dot.active{background:var(--gold);border-color:var(--gold);color:var(--g1);box-shadow:0 0 0 4px rgba(212,175,55,.2)}
.step-label{font-size:.68rem;color:var(--text2);margin-top:5px;display:block}
.step.active .step-label{color:var(--g1);font-weight:700}
.wrap{max-width:560px;margin:0 auto;padding:24px 16px}
.flow-card{background:#fff;border:1px solid var(--border);border-radius:var(--r);padding:24px;margin-bottom:16px;box-shadow:0 4px 20px rgba(7,51,40,.08)}
.flow-card h2{font-size:1.05rem;font-weight:700;color:var(--g1);margin-bottom:16px;display:flex;align-items:center;gap:8px}
.option-grid{display:flex;flex-direction:column;gap:10px}
.option-btn{padding:12px 16px;border:1.5px solid var(--border);border-radius:var(--r2);background:#fff;text-align:right;cursor:pointer;transition:all .2s;font-family:'Cairo',sans-serif;font-size:.9rem;display:flex;align-items:center;gap:10px}
.option-btn:hover{border-color:var(--g3);background:var(--sand)}
.option-btn.selected{border-color:var(--g1);background:rgba(7,51,40,.05)}
.option-btn .opt-icon{font-size:1.3rem}
.provider-card{border:1.5px solid var(--border);border-radius:var(--r2);padding:14px;display:flex;align-items:center;gap:12px;cursor:pointer;transition:all .2s;background:#fff;margin-bottom:10px}
.provider-card:hover{border-color:var(--g3);background:var(--sand)}
.provider-card.selected{border-color:var(--g1);background:rgba(7,51,40,.04)}
.prov-avatar{width:44px;height:44px;border-radius:50%;background:var(--g2);color:var(--gold);display:flex;align-items:center;justify-content:center;font-weight:900;font-size:1rem;flex-shrink:0}
.prov-body{flex:1}
.prov-name{font-weight:700;font-size:.92rem}
.prov-spec{font-size:.78rem;color:var(--text2)}
.prov-meta{display:flex;gap:10px;margin-top:4px;font-size:.75rem;color:var(--text2)}
.prov-rating{color:var(--gold);font-weight:700}
.prov-price{color:var(--g2);font-weight:700}
.summary-card{background:var(--sand2);border:1px solid var(--border);border-radius:var(--r2);padding:14px;margin-bottom:14px}
.sum-row{display:flex;justify-content:space-between;font-size:.88rem;padding:6px 0;border-bottom:1px solid var(--border)}
.sum-row:last-child{border:none;font-weight:700;font-size:1rem;color:var(--g1)}
.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:10px}
.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-outline{background:transparent;border:1.5px solid var(--g2);color:var(--g2)}

/* Responsive + Gradient additions */
.flow-hero{background:linear-gradient(135deg,#073328,#0a1628)}
.flow-card{transition:.2s}
.flow-card:hover{transform:translateY(-2px);box-shadow:0 4px 16px rgba(0,217,126,.15)}
.skel{background:linear-gradient(90deg,#f0f0f0 25%,#e8e8e8 50%,#f0f0f0 75%);background-size:200% 100%;animation:skel 1.4s infinite;border-radius:8px;height:14px;margin-bottom:8px}
@keyframes skel{0%{background-position:200% 0}100%{background-position:-200% 0}}
@media(max-width:640px){
  .flow-steps{flex-direction:column!important}
  .container{padding:14px!important}
  .step-card{margin-bottom:10px}
}
</style>
</head>
<body>
<div class="topbar">
  <span class="logo">🇸🇩 سودانا</span>
  <a href="<?= SITE_URL ?>/app/service.php?category=<?= $category ?>">← <?= $lang==='ar'?'رجوع':'Back' ?></a>
  <span style="margin-right:auto;font-size:.82rem;color:rgba(255,255,255,.7)"><?= htmlspecialchars($svcName) ?></span>
</div>

<div class="progress-bar">
  <div class="steps">
    <?php foreach($steps as $i => $step): ?>
    <div class="step <?= $i===0?'active':'' ?>" id="step-nav-<?= $step['num'] ?>">
      <div class="step-dot <?= $i===0?'active':'' ?>" id="dot-<?= $step['num'] ?>"><?= $step['icon'] ?></div>
      <span class="step-label"><?= $step['label'] ?></span>
    </div>
    <?php endforeach; ?>
  </div>
</div>

<!-- EXECUTION STATE BANNER -->
<div id="exec-state-banner" class="exec-banner exec-init" style="display:none">
  <span id="exec-state-icon">⚙️</span>
  <span id="exec-state-text"></span>
  <span id="exec-id-mini" style="font-family:monospace;font-size:.62rem;margin-right:auto;opacity:.7"></span>
</div>

<div class="wrap">

<!-- STEP 1: Service Type -->
<div class="flow-card" id="card-1">
  <h2>📋 <?= $lang==='ar'?'ما نوع استشارتك؟':'What type of consultation?' ?></h2>
  <div class="option-grid">
    <?php
    $options = [
      'medical'     => ['ar'=>['نزاع طبي','وصفة دواء','استشارة أعراض','متابعة حالة'], 'en'=>['Medical dispute','Prescription','Symptom consultation','Follow-up']],
      'legal'       => ['ar'=>['نزاع عمالي','قضية أسرية','عقد تجاري','استشارة جنائية'], 'en'=>['Labor dispute','Family case','Commercial contract','Criminal advice']],
      'business'    => ['ar'=>['خطة عمل','تسويق رقمي','فرصة استثمارية','عقد شراكة'], 'en'=>['Business plan','Digital marketing','Investment opportunity','Partnership']],
      'education'   => ['ar'=>['رياضيات','علوم','لغة عربية','لغة إنجليزية'], 'en'=>['Mathematics','Science','Arabic','English']],
      'engineering' => ['ar'=>['تصميم مباني','كهرباء','ميكانيكا','تقنية'], 'en'=>['Building design','Electrical','Mechanical','Tech']],
      'agriculture' => ['ar'=>['زراعة محاصيل','تربية حيوانات','ري وتربة','آفات ومبيدات'], 'en'=>['Crop farming','Livestock','Irrigation','Pest control']],
    ];
    $opts = $options[$category] ?? $options['business'];
    foreach($opts[$lang] as $i => $opt): ?>
    <button class="option-btn" onclick="selectOption(this,<?= $i ?>)" data-val="<?= htmlspecialchars($opt) ?>">
      <span class="opt-icon"><?= ['📋','📝','📊','📌'][$i%4] ?></span>
      <?= htmlspecialchars($opt) ?>
    </button>
    <?php endforeach; ?>
  </div>
  <button class="btn btn-primary" id="btn-1" onclick="nextStep(1,2)" disabled><?= $lang==='ar'?'التالي ←':'Next →' ?></button>
</div>

<!-- STEP 2: Details (hidden) -->
<div class="flow-card" id="card-2" style="display:none">
  <h2>📝 <?= $lang==='ar'?'أخبرنا أكثر':'Tell us more' ?></h2>
  <textarea id="user-details" rows="4" style="width:100%;border:1.5px solid var(--border);border-radius:var(--r2);padding:12px;font-family:'Cairo',sans-serif;font-size:.9rem;resize:none;outline:none" placeholder="<?= $lang==='ar'?'اشرح موقفك أو استفساراتك...':'Describe your situation or questions...' ?>"></textarea>
  <div style="display:flex;gap:8px">
    <button class="btn btn-outline" onclick="prevStep(2,1)"><?= $lang==='ar'?'→ السابق':'← Back' ?></button>
    <button class="btn btn-primary" id="btn-2" onclick="nextStep(2,3)"><?= $lang==='ar'?'التالي ←':'Next →' ?></button>
  </div>
</div>

<!-- STEP 3: Provider Selection (hidden) -->
<div class="flow-card" id="card-3" style="display:none">
  <h2>👤 <?= $lang==='ar'?'اختر مزوّدك':'Select your provider' ?></h2>
  <div id="providers-list">
    <?php
    // ── Real providers from DB ─────────────────────────────────────────
    $providers = [];
    try {
        $pq = db()->prepare("
            SELECT u.id, u.name, u.provider_specialization,
                   COALESCE(AVG(br.rating), 4.5) AS avg_rating,
                   COUNT(DISTINCT b.id) AS booking_count
            FROM users u
            LEFT JOIN bookings b ON b.provider_id = u.id AND b.status = 'completed'
            LEFT JOIN booking_ratings br ON br.booking_id = b.id
            WHERE u.provider_verified = 1
              AND u.user_type IN ('doctor','lawyer','teacher','engineer','agronomist','service_provider')
            GROUP BY u.id
            ORDER BY booking_count DESC, u.id ASC
            LIMIT 6
        ");
        $pq->execute();
        $providers = $pq->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) { /* fallback below */ }

    // ── Fallback if DB empty ──────────────────────────────────────────
    if (empty($providers)) {
        $providers = [
            ['id'=>10,'name'=>$lang==='ar'?'د. أحمد إبراهيم':'Dr. Ahmed Ibrahim','provider_specialization'=>$lang==='ar'?'طب عام':'General Medicine','avg_rating'=>4.8,'booking_count'=>47],
            ['id'=>11,'name'=>$lang==='ar'?'د. فاطمة مصطفى':'Dr. Fatima Mustafa','provider_specialization'=>$lang==='ar'?'طب أطفال':'Pediatrics','avg_rating'=>4.9,'booking_count'=>89],
            ['id'=>20,'name'=>$lang==='ar'?'أ. خالد النور':'Mr. Khalid Al-Nour','provider_specialization'=>$lang==='ar'?'قانون تجاري':'Commercial Law','avg_rating'=>4.7,'booking_count'=>31],
        ];
    }
    foreach($providers as $i => $prov):
        $name   = htmlspecialchars($prov['name'] ?? '—');
        $spec   = htmlspecialchars($prov['provider_specialization'] ?? '—');
        $rating = number_format((float)($prov['avg_rating'] ?? 4.5), 1);
        $bookings = (int)($prov['booking_count'] ?? 0);
        $initials = mb_strtoupper(mb_substr($prov['name'] ?? 'م', 0, 1));
        $price_show = $amount + ($i * 25);
    ?>
    <div class="provider-card" onclick="selectProvider(this,<?= $i ?>,<?= $price_show ?>,'<?= addslashes($name) ?>')" data-id="prov_<?= $i ?>">
      <div class="prov-avatar"><?= $initials ?></div>
      <div class="prov-body">
        <p class="prov-name"><?= $name ?></p>
        <p class="prov-spec"><?= $spec ?></p>
        <div class="prov-meta">
          <span class="prov-rating">⭐ <?= $rating ?></span>
          <span><?= $bookings > 0 ? $bookings.' '.($lang==='ar'?'حجز':'bookings') : ($lang==='ar'?'جديد':'New') ?></span>
          <span class="prov-price"><?= $price_show ?> SDG</span>
          <span style="color:var(--success)">🟢 <?= $lang==='ar'?'متاح':'Available' ?></span>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <div style="display:flex;gap:8px">
    <button class="btn btn-outline" onclick="prevStep(3,2)"><?= $lang==='ar'?'→ السابق':'← Back' ?></button>
    <button class="btn btn-primary" id="btn-3" onclick="nextStep(3,4)" disabled><?= $lang==='ar'?'التالي ←':'Next →' ?></button>
  </div>
</div>

<!-- STEP 4: Pay Decision + Confirm + Execute -->
<div class="flow-card" id="card-4" style="display:none">
  <h2>🚀 <?= $lang==='ar'?'التنفيذ':'Execution' ?></h2>

  <!-- SECTION A: What you get -->
  <div style="background:#F0FDF4;border:1px solid #6EE7B7;border-radius:var(--r2);padding:14px;margin-bottom:14px">
    <p style="font-weight:700;color:#065F46;margin-bottom:8px">✔ <?= $lang==='ar'?'ماذا ستحصل عليه؟':'What you get:' ?></p>
    <div style="font-size:.85rem;color:#065F46;display:flex;flex-direction:column;gap:5px">
      <span>✔ <?= $lang==='ar'?'استشارة مع':'Consultation with' ?> <strong id="sum-provider-v2">—</strong></span>
      <span>✔ <?= $lang==='ar'?'رد مضمون خلال 48 ساعة':'Guaranteed response within 48 hours' ?></span>
      <span>✔ <?= $lang==='ar'?'إيصال رسمي موثَّق':'Official documented receipt' ?></span>
      <span>✔ <?= $lang==='ar'?'تنفيذ مضمون أو استرجاع الرصيد':'Guaranteed execution or full refund' ?></span>
    </div>
  </div>

  <!-- SECTION B: Cost breakdown -->
  <div class="summary-card">
    <div class="sum-row"><span><?= $lang==='ar'?'الخدمة':'Service' ?></span><span><?= htmlspecialchars($svcName) ?></span></div>
    <div class="sum-row"><span><?= $lang==='ar'?'المزوّد':'Provider' ?></span><span id="sum-provider">—</span></div>
    <div class="sum-row"><span><?= $lang==='ar'?'SLA':'SLA' ?></span><span><?= $lang==='ar'?'حتى 48 ساعة':'up to 48 hours' ?></span></div>
    <div class="sum-row"><span><?= $lang==='ar'?'التكلفة':'Cost' ?></span><span id="sum-amount" style="font-weight:900;color:var(--g1)"><?= $amount ?> SDG</span></div>
    <div class="sum-row" id="balance-row" style="display:none">
      <span><?= $lang==='ar'?'رصيدك:':'Your balance:' ?></span>
      <span id="flow-balance" style="color:var(--g2)">—</span>
    </div>
    <div class="sum-row" id="after-row" style="display:none">
      <span><?= $lang==='ar'?'بعد التنفيذ:':'After execution:' ?></span>
      <span id="flow-after" style="color:var(--success);font-weight:700">—</span>
    </div>
  </div>

  <!-- SECTION C: Hold guarantee -->
  <div style="background:#D1FAE5;border:1px solid #6EE7B7;border-radius:var(--r2);padding:12px 14px;margin-bottom:14px">
    <p style="font-size:.82rem;font-weight:700;color:#065F46">🔒 <?= $lang==='ar'?'المبلغ محجوز فقط — لا يتم الخصم إلا بعد اكتمال الخدمة':'Amount reserved only — charged only after service completion' ?></p>
  </div>

  <div id="exec-id-display" style="font-size:.68rem;color:var(--text3);margin-bottom:8px;font-family:monospace;padding:4px 8px;background:var(--sand);border-radius:5px;display:none">
    🔍 <span id="exec-id-val"></span>
    <button onclick="navigator.clipboard.writeText(document.getElementById('exec-id-val').textContent)" style="border:none;background:none;font-size:.65rem;color:var(--g3);cursor:pointer;margin-right:6px">⎘ نسخ</button>
  </div>

  <div style="display:flex;gap:8px">
    <button class="btn btn-outline" onclick="prevStep(4,3)"><?= $lang==='ar'?'→ السابق':'← Back' ?></button>
    <button class="btn btn-primary" id="btn-pay" onclick="confirmAndPay()" style="flex:2">
      <span id="pay-text">🚀 <?= $lang==='ar'?'ابدأ التنفيذ الآن':'Start Execution Now' ?></span>
      <div id="pay-spin" style="display:none;width:16px;height:16px;border:2px solid rgba(255,255,255,.3);border-top-color:#fff;border-radius:50%;animation:spin .7s linear infinite"></div>
    </button>
  </div>
</div>

</div>

<style>@keyframes spin{to{transform:rotate(360deg)}}</style>
<script>
const SITE_URL = '<?= rtrim(SITE_URL,'/') ?>';

const FLOW_LANG = '<?= $lang ?>';
const EXEC_STATES = {
  INIT:    {cls:'exec-init',    icon:'⚙️', ar:'جاري التجهيز...',      en:'Initializing...'},
  RUNNING: {cls:'exec-running', icon:'⏳', ar:'جاري التنفيذ...',      en:'Processing...'},
  SUCCESS: {cls:'exec-success', icon:'✅', ar:'تم الحجز بنجاح',       en:'Booking confirmed'},
  FAILED:  {cls:'exec-failed',  icon:'❌', ar:'فشل التنفيذ — أعد المحاولة', en:'Failed — please retry'},
};
function showState(state, execId) {
  const banner = document.getElementById('exec-state-banner');
  const cfg = EXEC_STATES[state] || EXEC_STATES.INIT;
  banner.className = 'exec-banner ' + cfg.cls;
  banner.style.display = 'flex';
  document.getElementById('exec-state-icon').textContent = cfg.icon;
  document.getElementById('exec-state-text').textContent = FLOW_LANG==='ar' ? cfg.ar : cfg.en;
  if (execId) {
    document.getElementById('exec-id-mini').textContent = execId.substring(0,18)+'...';
    const dispEl = document.getElementById('exec-id-display');
    const valEl  = document.getElementById('exec-id-val');
    if (dispEl && valEl) { dispEl.style.display='block'; valEl.textContent=execId; }
  }
  banner.classList.add('show');
}

const LANG     = '<?= $lang ?>';
const CATEGORY = '<?= $category ?>';
let selectedAmount = <?= $amount ?>;
let selectedOption = null;
let selectedProviderName = '';

function selectOption(btn, idx) {
  document.querySelectorAll('.option-btn').forEach(b => b.classList.remove('selected'));
  btn.classList.add('selected');
  selectedOption = btn.dataset.val;
  document.getElementById('btn-1').disabled = false;
}

function selectProvider(card, idx, price, name) {
  document.querySelectorAll('.provider-card').forEach(c => c.classList.remove('selected'));
  card.classList.add('selected');
  selectedAmount = price;
  selectedProviderName = name;
  document.getElementById('btn-3').disabled = false;
}

function nextStep(from, to) {
  document.getElementById('card-' + from).style.display = 'none';
  document.getElementById('card-' + to).style.display = 'block';
  // Update progress
  document.getElementById('dot-' + from).classList.remove('active');
  document.getElementById('dot-' + from).classList.add('done');
  document.getElementById('dot-' + from).textContent = '✓';
  document.getElementById('step-nav-' + from).classList.add('done');
  document.getElementById('dot-' + to).classList.add('active');
  document.getElementById('step-nav-' + to).classList.add('active');
  if (to === 4) {
    document.getElementById('sum-provider').textContent = selectedProviderName;
    document.getElementById('sum-amount').textContent = selectedAmount + ' SDG';
    const pv2 = document.getElementById('sum-provider-v2');
    if (pv2) pv2.textContent = selectedProviderName;
    // Async wallet balance
    fetch(SITE_URL + '/api/wallet/summary.php?period=7d', {credentials:'include'})
      .then(r => r.json())
      .then(d => {
        const bal = parseFloat(d.cashflow?.balance_sdg || 0);
        const after = Math.max(0, bal - selectedAmount);
        const fmt = n => n.toLocaleString('en-US',{minimumFractionDigits:2,maximumFractionDigits:2}) + ' SDG';
        const br = document.getElementById('balance-row');
        const ar = document.getElementById('after-row');
        if (br) { document.getElementById('flow-balance').textContent = fmt(bal); br.style.display = ''; }
        if (ar) { document.getElementById('flow-after').textContent = fmt(after); ar.style.display = ''; }
      })
      .catch(() => {});
  }
}

function prevStep(from, to) {
  document.getElementById('card-' + from).style.display = 'none';
  document.getElementById('card-' + to).style.display = 'block';
}

function confirmAndPay() {
  const btn = document.getElementById('btn-pay');
  const txt = document.getElementById('pay-text');
  const spin = document.getElementById('pay-spin');
  const execId = 'exec_' + Date.now().toString(36) + Math.random().toString(36).substring(2,7);
  btn.disabled = true;
  txt.style.display = 'none';
  spin.style.display = 'block';
  showState('RUNNING', execId);

  // Create invoice then redirect to payment
  fetch(SITE_URL + '/api/payment/create_invoice.php', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    credentials: 'include',
    body: JSON.stringify({
      service: CATEGORY,
      amount: selectedAmount,
      method: 'offline',
      meta: {provider: selectedProviderName, option: selectedOption}
    })
  })
  .then(r => r.json())
  .then(data => {
    if (data.success && data.invoice_id) {
      showState('SUCCESS', data.execution_id||execId);
      setTimeout(()=>{ window.location.href = SITE_URL + '/payment.php?invoice_id=' + data.invoice_id; }, 600);
    } else {
      btn.disabled = false; txt.style.display = 'flex'; spin.style.display = 'none';
      showState('FAILED');
      alert(LANG==='ar' ? 'خطأ: ' + (data.error||'يجب تسجيل الدخول أولاً') : 'Error: ' + (data.error||'Login required'));
    }
  })
  .catch(() => {
    btn.disabled = false; txt.style.display = 'flex'; spin.style.display = 'none';
    alert(LANG==='ar' ? 'خطأ في الاتصال' : 'Connection error');
  });
}

document.addEventListener('DOMContentLoaded',()=>{ const execId='exec_'+Date.now().toString(36); showState('INIT',execId); });
</script>

<nav style="position:fixed;bottom:0;left:0;right:0;background:#fff;border-top:1px solid #e2e8f0;display:flex;padding:8px 0 calc(8px + env(safe-area-inset-bottom,0px));z-index:100">
  <a href="/app/hub.php" style="flex:1;display:flex;flex-direction:column;align-items:center;gap:2px;text-decoration:none;color:#64748b;font-size:.6rem;font-family:inherit;padding:4px 0"><span style="font-size:1.1rem">&#127968;</span><span>الهب</span></a>
  <a href="/app/pay.php" style="flex:1;display:flex;flex-direction:column;align-items:center;gap:2px;text-decoration:none;color:#64748b;font-size:.6rem;font-family:inherit;padding:4px 0"><span style="font-size:1.1rem">&#128179;</span><span>Pay</span></a>
  <a href="/app/invest/index.php" style="flex:1;display:flex;flex-direction:column;align-items:center;gap:2px;text-decoration:none;color:#64748b;font-size:.6rem;font-family:inherit;padding:4px 0"><span style="font-size:1.1rem">&#128185;</span><span>استثمار</span></a>
  <a href="/app/community.php" style="flex:1;display:flex;flex-direction:column;align-items:center;gap:2px;text-decoration:none;color:#64748b;font-size:.6rem;font-family:inherit;padding:4px 0"><span style="font-size:1.1rem">&#127968;</span><span>مجتمع</span></a>
  <a href="/app/profile.php" style="flex:1;display:flex;flex-direction:column;align-items:center;gap:2px;text-decoration:none;color:#64748b;font-size:.6rem;font-family:inherit;padding:4px 0"><span style="font-size:1.1rem">&#128100;</span><span>حسابي</span></a>
</nav>
</body>
</html>