<?php
require_once '../config.php';
start_secure_session();
$u=current_user();if(!$u){header('Location: ' . url('?login=1'));exit;}
$userId=(int)$u['id'];
$plan=$u['plan_key']??'free';

// Fetch billing data
$invoices=[];$wallet=[];$sub=null;
try{
  $stmt=db()->prepare("SELECT * FROM invoices WHERE user_id=? ORDER BY created_at DESC LIMIT 10");
  $stmt->execute([$userId]);$invoices=$stmt->fetchAll() ?: [];
  $wstmt=db()->prepare("SELECT *, balance_sdg AS balance FROM wallet WHERE user_id=?");
  $wstmt->execute([$userId]);$wallet=$wstmt->fetch()?:[];
}catch(Throwable $e){}
?><!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
  <title>الفوترة — سودانا</title>
  <style>
    :root{--green:#00d97e;--bg:#f8fafc;--card:#fff;--border:#e2e8f0;--text:#1e293b;--muted:#64748b}
    *{box-sizing:border-box;margin:0;padding:0}
    body{font-family:'Cairo',system-ui,sans-serif;background:var(--bg);color:var(--text)}
    .header{background:#fff;border-bottom:1px solid var(--border);padding:0 20px;height:54px;display:flex;align-items:center;justify-content:space-between;position:sticky;top:0;z-index:100;box-shadow:0 1px 4px rgba(0,0,0,.05)}
    .logo{font-weight:900;font-size:1rem}
    .back{color:var(--muted);font-size:.8rem;text-decoration:none;border:1px solid var(--border);padding:5px 12px;border-radius:7px}
    .container{max-width:900px;margin:0 auto;padding:20px}
    .hero{background:linear-gradient(135deg,#00d97e18,#0ea5e905);border:1px solid var(--border);border-radius:16px;padding:20px;margin-bottom:16px;display:flex;justify-content:space-between;align-items:center}
    .plan-badge{background:var(--green);color:#fff;padding:6px 16px;border-radius:20px;font-weight:900;font-size:.85rem}
    .card{background:var(--card);border:1px solid var(--border);border-radius:16px;padding:20px;margin-bottom:14px;box-shadow:0 1px 4px rgba(0,0,0,.04)}
    .card h2{font-size:.9rem;font-weight:800;margin-bottom:14px;display:flex;align-items:center;gap:8px}
    .plans-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}
    .plan-card{border:1px solid var(--border);border-radius:12px;padding:16px;text-align:center;position:relative}
    .plan-card.current{border-color:var(--green);background:#00d97e08}
    .plan-name{font-weight:900;font-size:1rem;margin-bottom:4px}
    .plan-price{font-size:1.4rem;font-weight:900;color:var(--green);margin-bottom:8px}
    .plan-feat{list-style:none;font-size:.72rem;color:var(--muted);line-height:2}
    .invoice-row{display:flex;justify-content:space-between;align-items:center;padding:10px 0;border-bottom:1px solid var(--border);font-size:.8rem}
    .badge{font-size:.68rem;padding:3px 8px;border-radius:10px;font-weight:700}
    .badge.paid{background:#d1fae5;color:#065f46}
    .badge.pending{background:#fef3c7;color:#92400e}
    .badge.failed{background:#fee2e2;color:#991b1b}
    .wallet-bal{font-size:2rem;font-weight:900;color:var(--green)}
    @media(max-width:600px){.plans-grid{grid-template-columns:1fr}.hero{flex-direction:column;gap:10px}}
  </style>
</head>
<body>
<header class="header">
  <div class="logo">💳 الفوترة والاشتراك</div>
  <a href="/dashboard/" class="back">← Dashboard</a>
</header>
<div class="container">

  <!-- Current plan hero -->
  <div class="hero">
    <div>
      <div style="font-size:.75rem;color:var(--muted);margin-bottom:4px">خطتك الحالية</div>
      <div style="font-size:1.5rem;font-weight:900"><?= match($plan){'pro'=>'Pro 🔥','plus'=>'Plus ⭐',default=>'Free 🆓'} ?></div>
      <div style="font-size:.8rem;color:var(--muted);margin-top:4px">
        <?= match($plan){'pro'=>'200 AI/يوم · 20 حجز · API Access','plus'=>'60 AI/يوم · 5 حجوزات · أولوية','free'=>'20 AI/يوم · 2 حجوزات · مجتمع'} ?>
      </div>
    </div>
    <span class="plan-badge"><?= strtoupper($plan) ?></span>
  </div>

  <!-- Wallet -->
  <div class="card">
    <h2>💰 محفظتي</h2>
    <div style="text-align:center;padding:10px 0">
      <div class="wallet-bal"><?= number_format($wallet['balance']??0) ?> <span style="font-size:.9rem;color:var(--muted)">SDG</span></div>
      <div style="font-size:.78rem;color:var(--muted);margin-top:4px">محجوز: <?= number_format($wallet['hold_balance']??0) ?> SDG</div>
    </div>
    <div style="display:flex;gap:10px;margin-top:14px;justify-content:center">
      <a href="/wallet.php" style="background:var(--green);color:#fff;padding:8px 20px;border-radius:9px;text-decoration:none;font-weight:700;font-size:.82rem">إدارة المحفظة ←</a>
    </div>
  </div>

  <!-- Plans -->
  <div class="card">
    <h2>📋 الخطط المتاحة</h2>
    <div class="plans-grid">
      <div class="plan-card <?= $plan==='free'?'current':'' ?>">
        <?php if($plan==='free'): ?><div style="position:absolute;top:-8px;right:10px;background:var(--green);color:#fff;font-size:.6rem;font-weight:800;padding:2px 8px;border-radius:8px">خطتك</div><?php endif;?>
        <div class="plan-name">Free 🆓</div>
        <div class="plan-price">0 SDG</div>
        <ul class="plan-feat"><li>20 AI/يوم</li><li>2 حجوزات/شهر</li><li>مجتمع كامل</li></ul>
      </div>
      <div class="plan-card <?= $plan==='plus'?'current':'' ?>" style="border-color:<?= $plan==='plus'?'var(--green)':'var(--border)' ?>">
        <?php if($plan==='plus'): ?><div style="position:absolute;top:-8px;right:10px;background:var(--green);color:#fff;font-size:.6rem;font-weight:800;padding:2px 8px;border-radius:8px">خطتك</div><?php endif;?>
        <div class="plan-name">Plus ⭐</div>
        <div class="plan-price">5,000 SDG</div>
        <ul class="plan-feat"><li>60 AI/يوم</li><li>5 حجوزات/شهر</li><li>أولوية المطابقة</li></ul>
      </div>
      <div class="plan-card <?= $plan==='pro'?'current':'' ?>">
        <?php if($plan==='pro'): ?><div style="position:absolute;top:-8px;right:10px;background:var(--green);color:#fff;font-size:.6rem;font-weight:800;padding:2px 8px;border-radius:8px">خطتك</div><?php endif;?>
        <div class="plan-name">Pro 🔥</div>
        <div class="plan-price">10,000 SDG</div>
        <ul class="plan-feat"><li>200 AI/يوم</li><li>20 حجوزات/شهر</li><li>API Access</li></ul>
      </div>
    </div>
  </div>

  <!-- Invoices -->
  <div class="card">
    <h2>🧾 سجل الفواتير</h2>
    <?php if($invoices): ?>
    <?php foreach($invoices as $inv): ?>
    <div class="invoice-row">
      <div>
        <div style="font-weight:600"><?= htmlspecialchars($inv['reference_code']??'') ?></div>
        <div style="color:var(--muted);font-size:.72rem"><?= htmlspecialchars($inv['service_type']??'') ?> · <?= substr($inv['created_at']??'',0,10) ?></div>
      </div>
      <div style="display:flex;align-items:center;gap:10px">
        <span style="font-weight:700"><?= number_format($inv['amount_sdg']??0) ?> SDG</span>
        <span class="badge <?= $inv['status']??'pending' ?>"><?= match($inv['status']??'pending'){'paid'=>'مدفوع','pending'=>'معلق','failed'=>'فشل',default=>$inv['status']} ?></span>
      </div>
    </div>
    <?php endforeach;?>
    <?php else: ?>
    <p style="color:var(--muted);font-size:.82rem;text-align:center;padding:16px">لا توجد فواتير بعد</p>
    <?php endif; ?>
  </div>
</div>
</body>
</html>