<?php
require_once dirname(__DIR__).'/config.php';
$u=current_user();if(!$u){header('Location: ' . url('?login=1'));exit;}
$cat=$_GET['cat']??'';
?><!DOCTYPE html><html lang="ar" dir="rtl"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>دفع الفواتير — سودانا</title>
<style>
:root{--g:#00d97e;--dark:#073328;--bg:#f0fdf4;--card:#fff;--muted:#64748b;--border:#e2e8f0;--safe-bottom:env(safe-area-inset-bottom,0px)}
*{box-sizing:border-box;margin:0;padding:0;-webkit-tap-highlight-color:transparent}
body{font-family:'Cairo',system-ui,sans-serif;background:var(--bg);min-height:100vh;padding-bottom:calc(70px + var(--safe-bottom))}
.hdr{background:var(--dark);height:56px;display:flex;align-items:center;justify-content:space-between;padding:0 16px;position:sticky;top:0;z-index:100}
.logo{color:#fff;font-weight:900}.back{color:rgba(255,255,255,.6);font-size:.82rem;text-decoration:none}
.cats{display:flex;gap:8px;padding:12px 16px;overflow-x:auto;background:var(--dark)}
.cat-btn{background:rgba(255,255,255,.1);border:none;border-radius:20px;padding:7px 16px;color:rgba(255,255,255,.7);font-family:inherit;font-size:.75rem;cursor:pointer;white-space:nowrap}
.cat-btn.active{background:var(--g);color:#000;font-weight:700}
.container{max-width:640px;margin:0 auto;padding:16px}
.provider-card{background:var(--card);border:1px solid var(--border);border-radius:14px;padding:14px;margin-bottom:10px;cursor:pointer;display:flex;align-items:center;gap:12px;transition:.15s}
.provider-card:active{transform:scale(.98)}
.prov-icon{width:44px;height:44px;border-radius:12px;background:#f0fdf4;display:flex;align-items:center;justify-content:center;font-size:1.4rem;flex-shrink:0}
.prov-info{flex:1}.prov-name{font-weight:700;font-size:.88rem;margin-bottom:3px}.prov-fee{font-size:.72rem;color:var(--muted)}
.arrow{color:var(--muted);font-size:.9rem}
.modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:200;align-items:flex-end}
.modal.open{display:flex}
.modal-body{background:#fff;border-radius:20px 20px 0 0;padding:24px 16px calc(20px + var(--safe-bottom));width:100%}
.modal-title{font-size:1rem;font-weight:900;margin-bottom:16px}
.field{margin-bottom:12px}
.field label{display:block;font-size:.75rem;font-weight:700;color:var(--muted);margin-bottom:4px}
.field input{width:100%;background:#f8fafc;border:1.5px solid var(--border);border-radius:10px;padding:11px 12px;font-family:inherit;font-size:15px}
.btn{background:linear-gradient(135deg,var(--g),#059669);color:#fff;border:none;border-radius:12px;padding:13px;width:100%;font-family:inherit;font-weight:800;font-size:.9rem;cursor:pointer;margin-top:4px}
.bottom-nav{position:fixed;bottom:0;left:0;right:0;background:#fff;border-top:1px solid var(--border);display:flex;padding:8px 0 calc(8px + var(--safe-bottom));z-index:100}
.nav-item{flex:1;display:flex;flex-direction:column;align-items:center;gap:3px;text-decoration:none;color:var(--muted);font-size:.62rem;padding:4px 0}
.nav-item.active{color:var(--g)}.nav-icon{font-size:1.2rem}
</style></head><body>
<header class="hdr"><div class="logo">📄 دفع الفواتير</div><a href="/app/pay.php" class="back">← Pay</a></header>
<div class="cats">
  <button class="cat-btn <?= !$cat?'active':'' ?>" onclick="loadCat('',this)">الكل</button>
  <button class="cat-btn <?= $cat==='electricity'?'active':'' ?>" onclick="loadCat('electricity',this)">⚡ كهرباء</button>
  <button class="cat-btn <?= $cat==='water'?'active':'' ?>" onclick="loadCat('water',this)">💧 مياه</button>
  <button class="cat-btn <?= $cat==='telecom'?'active':'' ?>" onclick="loadCat('telecom',this)">📱 اتصالات</button>
  <button class="cat-btn <?= $cat==='health'?'active':'' ?>" onclick="loadCat('health',this)">🏥 صحة</button>
</div>
<div class="container" id="providers-list"><p style="text-align:center;padding:24px;color:var(--muted)">جاري التحميل...</p></div>

<div class="modal" id="pay-modal">
  <div class="modal-body">
    <div class="modal-title" id="modal-provider-name">دفع الفاتورة</div>
    <input type="hidden" id="selected-provider">
    <div class="field"><label id="account-ref-label">رقم العداد / الحساب</label>
      <input type="text" id="account-ref" placeholder="أدخل رقم حسابك"></div>
    <div class="field"><label>المبلغ (SDG)</label>
      <input type="number" id="bill-amount" placeholder="أدخل المبلغ" min="100"></div>
    <div class="field"><label>رقم PIN</label>
      <input type="password" id="bill-pin" maxlength="6" placeholder="رقم PIN السري"></div>
    <button class="btn" onclick="payBill()">✅ ادفع الفاتورة</button>
    <button onclick="document.getElementById('pay-modal').classList.remove('open')" style="background:none;border:none;color:var(--muted);width:100%;padding:8px;font-family:inherit;cursor:pointer;margin-top:4px">إلغاء</button>
  </div>
</div>
<nav class="bottom-nav">
  <a href="/app/dashboard.php" class="nav-item"><span class="nav-icon">🏠</span><span>الرئيسية</span></a>
  <a href="/app/pay.php" class="nav-item active"><span class="nav-icon">💳</span><span>Pay</span></a>
  <a href="/app/invest/index.php" class="nav-item"><span class="nav-icon">💹</span><span>استثمار</span></a>
  <a href="/app/profile.php" class="nav-item"><span class="nav-icon">👤</span><span>حسابي</span></a>
</nav>
<script>
const icons={electricity:'⚡',water:'💧',telecom:'📱',health:'🏥',gov_fees:'🏛️',education:'📚',other:'📄'};
const catLabels={electricity:'رقم العداد',water:'رقم حساب المياه',telecom:'رقم الهاتف',health:'رقم البطاقة',default:'رقم الحساب'};
let currentCat='<?= $cat ?>';

async function loadCat(cat,btn){
  currentCat=cat;
  if(btn){document.querySelectorAll('.cat-btn').forEach(b=>b.classList.remove('active'));btn.classList.add('active');}
  const el=document.getElementById('providers-list');
  el.innerHTML='<p style="text-align:center;padding:24px;color:var(--muted)">جاري التحميل...</p>';
  try{
    const r=await fetch('/api/bills/providers.php'+(cat?'?category='+cat:''));
    const d=await r.json();
    const list=d.data||[];
    if(!list.length){el.innerHTML='<p style="text-align:center;padding:24px;color:var(--muted)">لا مزودين متاحين</p>';return;}
    el.innerHTML=list.map(p=>`<div class="provider-card" onclick="openPayModal(${p.id},'${p.name_ar}','${p.category}')">
      <div class="prov-icon">${icons[p.category]||'📄'}</div>
      <div class="prov-info"><div class="prov-name">${p.name_ar}</div>
      <div class="prov-fee">${p.fixed_fee_sdg>0?'رسوم: '+Number(p.fixed_fee_sdg).toLocaleString('ar-SA')+' SDG':'بدون رسوم إضافية'}</div></div>
      <div class="arrow">←</div></div>`).join('');
  }catch(e){el.innerHTML='<p style="text-align:center;padding:24px;color:var(--muted)">تعذّر التحميل</p>';}
}

function openPayModal(id,name,cat){
  document.getElementById('selected-provider').value=id;
  document.getElementById('modal-provider-name').textContent='دفع فاتورة: '+name;
  document.getElementById('account-ref-label').textContent=catLabels[cat]||catLabels.default;
  document.getElementById('pay-modal').classList.add('open');
}

async function payBill(){
  const providerId=parseInt(document.getElementById('selected-provider').value);
  const accountRef=document.getElementById('account-ref').value.trim();
  const amount=parseFloat(document.getElementById('bill-amount').value)||0;
  const pin=document.getElementById('bill-pin').value.trim();
  if(!accountRef||amount<100||!pin){alert('أكمل جميع البيانات');return;}
  const btn=document.querySelector('.modal .btn');btn.disabled=true;btn.textContent='جاري الدفع...';
  try{
    const r=await fetch('/api/bills/pay.php',{method:'POST',headers:{'Content-Type':'application/json'},
      body:JSON.stringify({provider_id:providerId,account_ref:accountRef,amount_sdg:amount,pin})});
    const d=await r.json();
    document.getElementById('pay-modal').classList.remove('open');
    if(d.ok)alert('✅ تم دفع الفاتورة بنجاح!
مرجع: '+d.bill_ref+(d.token_received?'
رمز الشحن: '+d.token_received:''));
    else alert('❌ '+(d.message||d.error||'حدث خطأ'));
  }catch(e){alert('❌ تعذّر الاتصال');}
  btn.disabled=false;btn.textContent='✅ ادفع الفاتورة';
}

loadCat(currentCat);
</script></body></html>
