<?php
/**
 * سودانا — Wallet Dashboard
 * Route: /wallet.php
 */
require_once __DIR__ . '/config.php';
session_start();
$u      = require_auth();
$userId = (int)$u['id'];
$lang   = $_SESSION['lang'] ?? 'ar';
$dir    = $lang === 'ar' ? 'rtl' : 'ltr';
if (!$userId) { header('Location: ' . SITE_URL . '/'); exit; }
?>
<!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'?'المحفظة':'Wallet' ?> — سودانا</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;--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:640px;margin:0 auto;padding:24px 16px}
.wallet-hero{background:linear-gradient(150deg,var(--g1),var(--g3));border-radius:var(--r);padding:28px;color:#fff;margin-bottom:20px;position:relative;overflow:hidden}
.wallet-hero::before{content:'';position:absolute;top:-40px;right:-40px;width:180px;height:180px;background:rgba(212,175,55,.08);border-radius:50%}
.balance-label{font-size:.82rem;color:rgba(255,255,255,.7);margin-bottom:6px}
.balance-amount{font-size:2.8rem;font-weight:900;color:#fff;line-height:1}
.balance-sdg{font-size:1rem;color:rgba(255,255,255,.8)}
.wallet-actions{display:flex;gap:10px;margin-top:20px;flex-wrap:wrap}
.wal-btn{padding:8px 18px;border-radius:var(--r2);font-weight:700;font-size:.85rem;border:none;cursor:pointer;display:flex;align-items:center;gap:6px;transition:all .2s}
.wal-btn-gold{background:var(--gold);color:var(--g1)}
.wal-btn-outline{background:rgba(255,255,255,.12);color:#fff;border:1.5px solid rgba(255,255,255,.3)}
.kpi-row{display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px;margin-bottom:20px}
.kpi-card{background:#fff;border:1px solid var(--border);border-radius:var(--r2);padding:14px;text-align:center}
.kpi-card .knum{font-size:1.2rem;font-weight:900;color:var(--g1)}
.kpi-card .klbl{font-size:.72rem;color:var(--text2);margin-top:3px}
.filters{display:flex;gap:8px;margin-bottom:16px;flex-wrap:wrap}
.filter-btn{padding:6px 14px;border-radius:20px;font-size:.8rem;font-weight:600;border:1px solid var(--border);background:#fff;color:var(--text2);cursor:pointer;transition:all .2s}
.filter-btn.active{background:var(--g1);color:#fff;border-color:var(--g1)}
.transactions{background:#fff;border:1px solid var(--border);border-radius:var(--r);overflow:hidden}
.txn-header{padding:14px 18px;border-bottom:1px solid var(--border);font-weight:700;font-size:.92rem}
.date-group{padding:10px 18px 4px;font-size:.72rem;font-weight:700;color:var(--text3);background:var(--sand);text-transform:uppercase;letter-spacing:.05em}
.txn-item{display:flex;align-items:center;gap:12px;padding:12px 18px;border-bottom:1px solid var(--sand2);cursor:pointer;transition:background .15s}
.txn-item:hover{background:var(--sand)}
.txn-item:last-child{border:none}
.txn-icon{width:36px;height:36px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:1rem;flex-shrink:0}
.txn-icon.credit{background:#D1FAE5}
.txn-icon.debit{background:#FEE2E2}
.txn-body{flex:1}
.txn-desc{font-size:.88rem;font-weight:600}
.txn-date{font-size:.75rem;color:var(--text2)}
.txn-amount{font-size:.92rem;font-weight:700}
.txn-amount.credit{color:var(--success)}
.txn-amount.debit{color:var(--danger)}
.skeleton{background:linear-gradient(90deg,#eee 25%,#f5f5f5 50%,#eee 75%);background-size:200%;animation:shimmer 1.5s infinite;border-radius:6px}
@keyframes shimmer{0%{background-position:200% 0}100%{background-position:-200% 0}}
.limits-card{background:#fff;border:1px solid var(--border);border-radius:var(--r);padding:16px;margin-bottom:16px}
.limits-card h4{font-size:.88rem;font-weight:700;margin-bottom:12px}
.limit-row{display:flex;justify-content:space-between;align-items:center;margin-bottom:10px}
.limit-bar-wrap{flex:1;height:6px;background:var(--sand2);border-radius:3px;margin:0 12px}
.limit-bar{height:6px;border-radius:3px;background:var(--g3);transition:width .5s}
.limit-pct{font-size:.75rem;font-weight:600;color:var(--g2);min-width:32px;text-align:left}
.empty-state{text-align:center;padding:40px 20px;color:var(--text2)}
.empty-state .empty-icon{font-size:2.5rem;margin-bottom:12px}

@media(max-width:640px){
  .wal-stats{grid-template-columns:repeat(2,1fr)!important}
  .container{padding:14px!important}
  .wal-hero{padding:20px 16px!important}
}
.wal-hero{background:linear-gradient(135deg,#073328,#0a2a1a)}
.stat-box{transition:.2s}
.stat-box:hover{transform:translateY(-2px);box-shadow:0 4px 16px rgba(0,217,126,.15)}
.tx-row:hover{background:#f8fafc!important}
.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}}
.fade-in{animation:fi .35s ease}@keyframes fi{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}}
</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'?'المحفظة':'Wallet' ?></span>
</div>

<div class="wrap">
  <!-- Wallet hero — loaded via JS -->
  <div class="wallet-hero" id="wallet-hero">
    <div class="balance-label" id="balance-label"><?= $lang==='ar'?'الرصيد الحالي':'Current Balance' ?></div>
    <div class="balance-amount" id="balance-amount">
      <div class="skeleton" style="width:180px;height:40px"></div>
    </div>
    <div class="wallet-actions">
      <button class="wal-btn wal-btn-gold" onclick="location.href='<?= SITE_URL ?>/payment.php'">
        + <?= $lang==='ar'?'شحن المحفظة':'Top Up' ?>
      </button>
      <button class="wal-btn wal-btn-outline" onclick="showSpending()">
        📊 <?= $lang==='ar'?'تحليل الإنفاق':'Spending' ?>
      </button>
    </div>
  </div>

  <!-- KPI row -->
  <div class="kpi-row" id="kpi-row">
    <div class="kpi-card"><div class="skeleton" style="height:20px;margin:0 auto 6px;width:60%"></div><div class="klbl">...</div></div>
    <div class="kpi-card"><div class="skeleton" style="height:20px;margin:0 auto 6px;width:60%"></div><div class="klbl">...</div></div>
    <div class="kpi-card"><div class="skeleton" style="height:20px;margin:0 auto 6px;width:60%"></div><div class="klbl">...</div></div>
  </div>

  <!-- Limits -->
  <div class="limits-card" id="limits-card" style="display:none">
    <h4>🔐 <?= $lang==='ar'?'حدود المعاملات (KYC)':'Transaction Limits (KYC)' ?></h4>
    <div id="limits-body"></div>
  </div>

  <!-- Filters -->
  <div class="filters">
    <button class="filter-btn active" data-filter="all"><?= $lang==='ar'?'الكل':'All' ?></button>
    <button class="filter-btn" data-filter="credit">+ <?= $lang==='ar'?'إيداع':'Deposit' ?></button>
    <button class="filter-btn" data-filter="debit">- <?= $lang==='ar'?'سحب':'Withdrawal' ?></button>
    <select id="period-select" style="padding:5px 10px;border-radius:20px;border:1px solid var(--border);font-size:.8rem;background:#fff">
      <option value="30d"><?= $lang==='ar'?'آخر 30 يوم':'Last 30 days' ?></option>
      <option value="7d"><?= $lang==='ar'?'آخر 7 أيام':'Last 7 days' ?></option>
      <option value="90d"><?= $lang==='ar'?'آخر 90 يوم':'Last 90 days' ?></option>
    </select>
  </div>

  <!-- Transactions -->
  <div class="transactions" id="transactions-container">
    <div class="txn-header"><?= $lang==='ar'?'المعاملات':'Transactions' ?></div>
    <div id="txn-list">
      <?php for($i=0;$i<4;$i++): ?>
      <div class="txn-item">
        <div class="skeleton txn-icon" style="width:36px;height:36px"></div>
        <div class="txn-body"><div class="skeleton" style="height:14px;width:60%;margin-bottom:6px"></div><div class="skeleton" style="height:10px;width:40%"></div></div>
        <div class="skeleton" style="width:60px;height:18px"></div>
      </div>
      <?php endfor; ?>
    </div>
  </div>
</div>

<script>
const SITE_URL = '<?= rtrim(SITE_URL,'/') ?>';
const LANG     = '<?= $lang ?>';
let allTxns = [];

async function loadWallet(period='30d') {
  const data = await fetch(SITE_URL + '/api/wallet/summary.php?period='+period, {credentials:'include'})
    .then(r => r.json()).catch(() => null);
  if (!data) return;

  const cf = data.cashflow || {};
  const bal      = parseFloat(cf.balance_sdg  || 0);
  const held     = parseFloat(data.reserved_sdg || 0);
  const available = Math.max(0, bal - held);
  const heldPct   = bal > 0 ? Math.min(100, Math.round(held / bal * 100)) : 0;
  const availPct  = 100 - heldPct;
  const fmt = n => n.toLocaleString('en-US', {minimumFractionDigits:2, maximumFractionDigits:2});

  // ── Balance hero ─────────────────────────────────────────────
  document.getElementById('balance-amount').innerHTML =
    `<span style="font-size:2.8rem;font-weight:900">${fmt(bal)}</span>
     <span class="balance-sdg"> SDG</span>`;

  // ── Visual breakdown bar ──────────────────────────────────────
  const hero = document.getElementById('wallet-hero');
  // Remove any existing breakdown
  const existing = hero.querySelector('.balance-breakdown-bar');
  if (existing) existing.remove();

  const breakdownHTML = `<div class="balance-breakdown-bar" style="margin-top:14px">
    <div style="display:flex;justify-content:space-between;font-size:.75rem;color:rgba(255,255,255,.8);margin-bottom:5px">
      <span>${LANG==='ar'?'الرصيد الكلي':'Total'}: ${fmt(bal)} SDG</span>
      <span style="color:rgba(255,255,255,.7)">${LANG==='ar'?'متاح':'Available'}: ${fmt(available)} SDG</span>
    </div>
    <div style="height:8px;background:rgba(255,255,255,.2);border-radius:4px;overflow:hidden">
      <div style="height:100%;width:${availPct}%;background:#6EE7B7;border-radius:4px;transition:width .6s"></div>
    </div>
    <div style="display:flex;justify-content:space-between;font-size:.72rem;margin-top:5px">
      ${held > 0 ? `<span style="color:rgba(255,212,55,.9)">🔒 ${LANG==='ar'?'محجوز':'Reserved'}: ${fmt(held)} SDG</span>` : '<span></span>'}
      <span style="color:rgba(255,255,255,.8)">${LANG==='ar'?'متاح للصرف':'Available'}: <strong style="color:#6EE7B7">${fmt(available)} SDG</strong></span>
    </div>
    ${held > 0 ? `<div id="pending-exec-list" style="margin-top:10px;padding-top:10px;border-top:1px solid rgba(255,255,255,.15)">
      <div style="font-size:.72rem;color:rgba(255,255,255,.7);margin-bottom:6px">⏳ ${LANG==='ar'?'تنفيذات معلقة:':'Pending executions:'}</div>
      <a href="${SITE_URL}/payment.php" style="display:block;background:rgba(255,255,255,.1);border-radius:6px;padding:6px 10px;font-size:.75rem;color:#fff;text-decoration:none;margin-bottom:4px">
        🔒 ${LANG==='ar'?'محجوز للتنفيذ':'Reserved for execution'}: ${fmt(held)} SDG →
      </a>
    </div>` : ''}
  </div>`;

  hero.insertAdjacentHTML('beforeend', breakdownHTML);

  // KPIs
  document.getElementById('kpi-row').innerHTML = `
    <div class="kpi-card"><div class="knum">${parseFloat(cf.deposited_sdg||0).toLocaleString()}</div><div class="klbl">${LANG==='ar'?'إجمالي الإيداع':'Total Deposited'}</div></div>
    <div class="kpi-card"><div class="knum">${parseFloat(cf.spent_sdg||0).toLocaleString()}</div><div class="klbl">${LANG==='ar'?'إجمالي الإنفاق':'Total Spent'}</div></div>
    <div class="kpi-card"><div class="knum">${cf.runway_days||0}</div><div class="klbl">${LANG==='ar'?'أيام متبقية':'Days Runway'}</div></div>
  `;

  // Limits
  const lim = data.limits || {};
  if (lim.limits) {
    document.getElementById('limits-card').style.display = 'block';
    const daily_remaining = lim.daily_remaining || lim.limits.daily || 0;
    const pct = Math.min(100, Math.round((lim.amount||0) / (lim.limits.daily||1) * 100));
    document.getElementById('limits-body').innerHTML = `
      <div class="limit-row">
        <span style="font-size:.78rem;color:var(--text2)">${LANG==='ar'?'الحد اليومي':'Daily Limit'}</span>
        <div class="limit-bar-wrap"><div class="limit-bar" style="width:${pct}%"></div></div>
        <span class="limit-pct">${parseFloat(daily_remaining).toLocaleString()} SDG</span>
      </div>
      <p style="font-size:.72rem;color:var(--text2)">KYC ${LANG==='ar'?'المستوى':'Level'} ${lim.kyc_level||0} — ${LANG==='ar'?'وثّق هويتك لرفع الحد':'Verify ID to increase limits'}</p>
    `;
  }

  // Transactions
  allTxns = data.transactions || [];
  renderTxns(allTxns);
}

function renderTxns(txns) {
  const list = document.getElementById('txn-list');
  if (!txns.length) {
    list.innerHTML = `<div class="empty-state"><div class="empty-icon">💡</div>
      <p>${LANG==='ar'?'لا معاملات بعد. عند حجز أول خدمة ستظهر هنا.':'No transactions yet. Book a service to get started.'}</p></div>`;
    return;
  }
  const byDate = {};
  txns.forEach(t => {
    const d = t.created_at?.split(' ')[0] || 'N/A';
    (byDate[d] = byDate[d] || []).push(t);
  });
  list.innerHTML = Object.entries(byDate).map(([date, items]) => {
    const dLabel = new Date(date).toLocaleDateString(LANG==='ar'?'ar-SD':'en-US', {weekday:'long',year:'numeric',month:'long',day:'numeric'});
    return `<div class="date-group">${dLabel}</div>` + items.map(t => {
      const isCredit = t.type === 'credit';
      const icon = isCredit ? '⬆️' : '⬇️';
      const amtStr = `${isCredit?'+':'-'}${parseFloat(t.amount_sdg||0).toFixed(2)} SDG`;
      const time = t.created_at?.split(' ')[1]?.substring(0,5) || '';
      return `<div class="txn-item" onclick="viewReceipt('${t.ref_type}','${t.ref_id}')">
        <div class="txn-icon ${isCredit?'credit':'debit'}">${icon}</div>
        <div class="txn-body">
          <p class="txn-desc">${t.description||''}</p>
          <p class="txn-date">${time}</p>
        </div>
        <span class="txn-amount ${isCredit?'credit':'debit'}">${amtStr}</span>
      </div>`;
    }).join('');
  }).join('');
}

// Filters
document.querySelectorAll('.filter-btn').forEach(btn => {
  btn.addEventListener('click', function() {
    document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
    this.classList.add('active');
    const f = this.dataset.filter;
    renderTxns(f === 'all' ? allTxns : allTxns.filter(t => t.type === f));
  });
});
document.getElementById('period-select').addEventListener('change', e => loadWallet(e.target.value));

function viewReceipt(type, id) {
  if (type === 'invoice') window.open(SITE_URL + '/receipt.php?invoice_id=' + id, '_blank');
}
function showSpending() {
  alert(LANG==='ar' ? 'تحليل الإنفاق قيد التطوير' : 'Spending analysis coming soon');
}

loadWallet();
</script>
</body>
</html>
