<?php
require_once dirname(__DIR__).'/config.php';
$u = current_user(); if(!$u){header('Location: ' . url('?login=1'));exit;}
?>
/**
 * سودانا — Services Marketplace v3 (Conversion Engine)
 * Route: /app/services.php
 */
require_once __DIR__ . '/../config.php';
session_start();
$lang = $_SESSION['lang'] ?? 'ar';
$dir  = $lang === 'ar' ? 'rtl' : 'ltr';

// ── Fetch real provider counts ────────────────────────────────
$provider_counts = [];
try {
    $pq = db()->query("
        SELECT CASE user_type
            WHEN 'doctor'     THEN 'medical'
            WHEN 'lawyer'     THEN 'legal'
            WHEN 'teacher'    THEN 'education'
            WHEN 'engineer'   THEN 'engineering'
            WHEN 'agronomist' THEN 'agriculture'
            ELSE 'business'
        END AS sector, COUNT(*) AS cnt
        FROM users WHERE provider_verified=1
          AND user_type IN ('doctor','lawyer','teacher','engineer','agronomist','service_provider')
        GROUP BY user_type
    ");
    foreach ($pq->fetchAll(PDO::FETCH_ASSOC) as $r) {
        $sector = $r['sector'];
        $provider_counts[$sector] = ($provider_counts[$sector] ?? 0) + (int)$r['cnt'];
    }
} catch (Throwable $e) {}

// ── 10 Categories (ALL connected to flow.php) ─────────────────
$categories = [
    ['id'=>'medical',     'icon'=>'🏥','ar'=>'طب وصحة',           'en'=>'Medical',     'price'=>250,'sla'=>24, 'rating'=>4.8,'desc_ar'=>'استشارة أطباء متخصصين في جميع التخصصات','desc_en'=>'Specialist doctor consultations in all fields'],
    ['id'=>'legal',       'icon'=>'⚖️','ar'=>'قانون واستشارات',   'en'=>'Legal',       'price'=>350,'sla'=>48, 'rating'=>4.7,'desc_ar'=>'محامون معتمدون لحل النزاعات القانونية','desc_en'=>'Certified lawyers for legal disputes'],
    ['id'=>'business',    'icon'=>'💼','ar'=>'أعمال وتجارة',      'en'=>'Business',    'price'=>300,'sla'=>24, 'rating'=>4.6,'desc_ar'=>'خبراء أعمال لتطوير مشاريعك وخططك','desc_en'=>'Business experts for your projects and plans'],
    ['id'=>'education',   'icon'=>'📚','ar'=>'تعليم وأكاديمي',   'en'=>'Education',   'price'=>150,'sla'=>12, 'rating'=>4.9,'desc_ar'=>'معلمون متخصصون في جميع المواد والمراحل','desc_en'=>'Specialist tutors for all subjects and levels'],
    ['id'=>'engineering', 'icon'=>'⚙️','ar'=>'هندسة وتقنية',     'en'=>'Engineering', 'price'=>400,'sla'=>48, 'rating'=>4.6,'desc_ar'=>'مهندسون معتمدون لمشاريع البناء والتقنية','desc_en'=>'Certified engineers for construction and tech'],
    ['id'=>'agriculture', 'icon'=>'🌾','ar'=>'زراعة وبيئة',      'en'=>'Agriculture', 'price'=>200,'sla'=>48, 'rating'=>4.5,'desc_ar'=>'خبراء زراعيون لتحسين الإنتاج والجودة','desc_en'=>'Agricultural experts to improve production'],
    ['id'=>'community',   'icon'=>'🏘️','ar'=>'مجتمع وأحياء',     'en'=>'Community',   'price'=>0,  'sla'=>24, 'rating'=>4.5,'desc_ar'=>'خدمات مجتمعية وتواصل بين الأحياء','desc_en'=>'Community services and neighborhood connectivity'],
    ['id'=>'local',       'icon'=>'📍','ar'=>'خدمات محلية',       'en'=>'Local',       'price'=>50, 'sla'=>6,  'rating'=>4.5,'desc_ar'=>'خدمات قريبة منك — متاجر، مطاعم، صيانة','desc_en'=>'Services near you — shops, restaurants, repairs'],
    ['id'=>'family',      'icon'=>'👨‍👩‍👧','ar'=>'أسرة ومنزل',      'en'=>'Family',      'price'=>100,'sla'=>24, 'rating'=>4.6,'desc_ar'=>'دعم الأسرة، التربية، والاستشارات المنزلية','desc_en'=>'Family support, parenting, home consultations'],
    ['id'=>'enterprise',  'icon'=>'🏢','ar'=>'حلول مؤسسية',       'en'=>'Enterprise',  'price'=>500,'sla'=>48, 'rating'=>4.7,'desc_ar'=>'حلول متكاملة للشركات والمؤسسات الكبرى','desc_en'=>'Integrated solutions for companies and institutions'],
    ['id'=>'pharmacy',    'icon'=>'💊','ar'=>'الصيدلية الذكية',    'en'=>'Pharmacy',     'price'=>50,'sla'=>2,   'rating'=>4.7,'desc_ar'=>'بدائل أدوية وجرعات','desc_en'=>'Drug alternatives and dosages'],
    ['id'=>'jobs',        'icon'=>'💼','ar'=>'سوق العمل',          'en'=>'Jobs',         'price'=>0,'sla'=>24,  'rating'=>4.6,'desc_ar'=>'وظائف وCV','desc_en'=>'Jobs and CV'],
    ['id'=>'market',      'icon'=>'🛒','ar'=>'سوق الجيران',        'en'=>'Market',       'price'=>0,'sla'=>6,   'rating'=>4.5,'desc_ar'=>'بيع وشراء في حيك','desc_en'=>'Neighborhood marketplace'],
    ['id'=>'suggestions', 'icon'=>'💡','ar'=>'اقتراحاتك',         'en'=>'Suggestions',  'price'=>0,'sla'=>0,   'rating'=>5.0,'desc_ar'=>'أفكارك لتطوير سودانا','desc_en'=>'Ideas to improve Sudanna'],
];

// Inject real counts + compute social proof
$maxCount = 0; $hotIdx = 0;
foreach ($categories as $i => &$cat) {
    $cat['count']    = $provider_counts[$cat['id']] ?? 0;
    $cat['executed'] = max($cat['count'] * 15, 0);
    if ($cat['count'] > $maxCount) { $maxCount = $cat['count']; $hotIdx = $i; }
}
unset($cat);
if ($maxCount > 0) $categories[$hotIdx]['hot'] = true;
else $categories[0]['hot'] = true; // default
?>
<!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'?'الخدمات':'Services' ?> — سودانا</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;--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}
.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}
.topbar a:hover{color:#fff}
.hero{background:linear-gradient(135deg,var(--g1),var(--g3));color:#fff;padding:32px 20px;text-align:center}
.hero h1{font-size:clamp(1.4rem,4vw,2rem);font-weight:900;margin-bottom:8px}
.hero p{font-size:.9rem;color:rgba(255,255,255,.8)}
.search-bar{display:flex;gap:8px;max-width:480px;margin:16px auto 0;background:#fff;border-radius:var(--r2);padding:4px 4px 4px 12px}
.search-bar input{flex:1;border:none;outline:none;font-family:'Cairo',sans-serif;font-size:.9rem;background:transparent}
.search-bar button{background:var(--gold);color:var(--g1);border:none;padding:8px 18px;border-radius:8px;font-weight:700;cursor:pointer}
.wrap{max-width:960px;margin:0 auto;padding:24px 16px}
.filters{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:16px}
.filter-pill{padding:5px 14px;border-radius:20px;font-size:.78rem;font-weight:600;border:1px solid var(--border);background:#fff;color:var(--text2);cursor:pointer;transition:all .2s}
.filter-pill.active{background:var(--g1);color:#fff;border-color:var(--g1)}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:16px}
.cat-card{background:#fff;border:1px solid var(--border);border-radius:var(--r);padding:20px;cursor:pointer;transition:transform .2s,box-shadow .2s,border-color .2s;position:relative;overflow:hidden}
.cat-card::before{content:'';position:absolute;top:0;right:0;width:4px;height:100%;background:var(--g3)}
.cat-card:hover{transform:translateY(-4px);box-shadow:0 10px 28px rgba(7,51,40,.14);border-color:var(--g3)}
.cat-card.hot{border-color:var(--amber)}
.cat-card.cat-free::before{background:var(--success)}
.hot-badge{position:absolute;top:10px;left:10px;background:var(--amber);color:#fff;font-size:.68rem;font-weight:700;padding:2px 8px;border-radius:20px}
.cat-icon{font-size:2rem;margin-bottom:10px}
.cat-name{font-size:1rem;font-weight:700;margin-bottom:4px}
.cat-meta{display:flex;justify-content:space-between;font-size:.78rem;color:var(--text2);margin-top:8px}
.cat-price{color:var(--g2);font-weight:700}
.prov-count{font-weight:600}
.prov-count.avail{color:var(--success)}
.prov-count.soon{color:var(--text3)}
.cta-btn{display:block;width:100%;margin-top:12px;padding:9px;background:var(--g1);color:#fff;border:none;border-radius:var(--r2);font-weight:700;font-size:.85rem;cursor:pointer;font-family:'Cairo',sans-serif;transition:background .2s}
.cta-btn:hover{background:var(--g2)}
.cat-card{animation:fadeUpCard .35s ease both}
@keyframes fadeUpCard{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:none}}
.cat-card:nth-child(2){animation-delay:.04s}.cat-card:nth-child(3){animation-delay:.08s}
.cat-card:nth-child(4){animation-delay:.12s}.cat-card:nth-child(5){animation-delay:.16s}
.cat-card:nth-child(6){animation-delay:.20s}.cat-card:nth-child(7){animation-delay:.24s}
.cat-card:nth-child(8){animation-delay:.28s}.cat-card:nth-child(9){animation-delay:.32s}
.cat-card:nth-child(10){animation-delay:.36s}
/* ── SERVICE MODAL ── */
.modal-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:500;align-items:center;justify-content:center;padding:20px}
.modal-overlay.open{display:flex;animation:fadeIn .2s ease}
@keyframes fadeIn{from{opacity:0}to{opacity:1}}
.modal-box{background:#fff;border-radius:var(--r);max-width:480px;width:100%;max-height:90vh;overflow-y:auto;box-shadow:0 20px 60px rgba(0,0,0,.2)}
.modal-header{background:var(--g1);color:#fff;padding:18px 20px;display:flex;align-items:center;justify-content:space-between;border-radius:var(--r) var(--r) 0 0}
.modal-header .m-title{font-weight:900;font-size:1.05rem;color:#fff}
.modal-close{background:none;border:none;color:rgba(255,255,255,.7);font-size:1.4rem;cursor:pointer;padding:0 4px;line-height:1}
.modal-close:hover{color:#fff}
.modal-body{padding:20px}
.m-row{display:flex;align-items:center;gap:10px;padding:8px 0;border-bottom:1px solid var(--sand2);font-size:.88rem}
.m-row:last-child{border:none}
.m-label{color:var(--text2);min-width:100px}
.m-val{font-weight:600}
.m-desc{font-size:.88rem;color:var(--text2);line-height:1.6;margin-bottom:14px}
.social-proof{background:var(--sand);border-radius:var(--r2);padding:10px 14px;margin:12px 0;font-size:.82rem;color:var(--text2);display:flex;align-items:center;gap:8px}
.trust-line{color:var(--success);font-weight:700;font-size:.82rem;margin-bottom:14px;display:flex;align-items:center;gap:6px}
.modal-cta{display:block;width:100%;padding:13px;background:var(--g1);color:#fff;border:none;border-radius:var(--r);font-weight:900;font-size:.95rem;cursor:pointer;font-family:'Cairo',sans-serif;transition:all .2s;text-align:center}
.modal-cta:hover{background:var(--g2);transform:translateY(-1px)}
@media(max-width:640px){.services-grid{grid-template-columns:1fr 1fr!important}.container{padding:14px!important}.svc-hero{padding:20px 16px!important}}
</style>
</head>
<body>
<div class="topbar">
  <span class="logo">🇸🇩 سودانا</span>
  <a href="<?= SITE_URL ?>/"><?= $lang==='ar'?'الرئيسية':'Home' ?></a>
  <span style="margin-right:auto;font-size:.82rem;color:rgba(255,255,255,.7)"><?= $lang==='ar'?'سوق الخدمات':'Marketplace' ?></span>
  <a href="<?= SITE_URL ?>/wallet.php">💳</a>
  <a href="<?= SITE_URL ?>/app/notifications.php">🔔</a>
</div>

<div class="hero">
  <h1><?= $lang==='ar'?'🚀 منصة التنفيذ الذكي':'🚀 Smart Execution Platform' ?></h1>
  <p><?= $lang==='ar'?'خبراء متخصصون — تنفيذ مضمون — إيصال رسمي':'Specialist experts — Guaranteed execution — Official receipt' ?></p>
  <div class="search-bar">
    <input type="text" placeholder="<?= $lang==='ar'?'ابحث عن خدمة...':'Search for a service...' ?>" id="search-input">
    <button onclick="searchServices()"><?= $lang==='ar'?'بحث':'Search' ?></button>
  </div>
</div>

<div class="wrap">
  <div class="filters" id="sort-filters">
    <button class="filter-pill active" data-sort="default"><?= $lang==='ar'?'الكل':'All' ?></button>
    <button class="filter-pill" data-sort="popular"><?= $lang==='ar'?'الأكثر طلباً':'Most Popular' ?></button>
    <button class="filter-pill" data-sort="price"><?= $lang==='ar'?'الأقل سعراً':'Lowest Price' ?></button>
    <button class="filter-pill" data-sort="free"><?= $lang==='ar'?'مجاني':'Free' ?></button>
  </div>

  <div class="grid" id="services-grid">
    <?php foreach($categories as $cat):
      $executed = (int)$cat['executed'];
      $count    = (int)$cat['count'];
    ?>
    <div class="cat-card <?= !empty($cat['hot'])?'hot':'' ?> <?= $cat['price']===0?'cat-free':'' ?>"
         onclick="openModal('<?= $cat['id'] ?>')"
         data-id="<?= $cat['id'] ?>"
         data-price="<?= $cat['price'] ?>"
         data-count="<?= $count ?>">
      <?php if(!empty($cat['hot'])): ?>
      <div class="hot-badge">🔥 <?= $lang==='ar'?'الأكثر طلباً':'Most Popular' ?></div>
      <?php endif; ?>
      <div class="cat-icon"><?= $cat['icon'] ?></div>
      <div class="cat-name"><?= $lang==='ar'?$cat['ar']:$cat['en'] ?></div>
      <div class="cat-meta">
        <span class="cat-price">
          <?= $cat['price'] > 0 ? ($lang==='ar'?'من ':'from ').$cat['price'].' SDG' : ($lang==='ar'?'🆓 مجاني':'🆓 Free') ?>
        </span>
        <span class="prov-count <?= $count > 0 ? 'avail' : 'soon' ?>">
          <?= $count > 0 ? $count.' '.($lang==='ar'?'مزوّد':'prov.') : ($lang==='ar'?'قريباً':'Soon') ?>
        </span>
      </div>
      <button class="cta-btn" onclick="event.stopPropagation();openModal('<?= $cat['id'] ?>')">
        🚀 <?= $lang==='ar'?'ابدأ التنفيذ الآن':'Start Execution Now' ?>
      </button>
    </div>
    <?php endforeach; ?>
  </div>

  <!-- Trust footer -->
  <div style="text-align:center;padding:24px 0;font-size:.82rem;color:var(--text2)">
    ✔ <?= $lang==='ar'?'تنفيذ مضمون أو استرجاع الرصيد':'Guaranteed execution or full refund' ?>
    &nbsp;•&nbsp; 🔒 <?= $lang==='ar'?'المبلغ محجوز فقط حتى الاكتمال':'Amount reserved until completion' ?>
    &nbsp;•&nbsp; 🏦 NO_CUSTODY
  </div>
</div>

<!-- ══ SERVICE MODAL ══ -->
<div class="modal-overlay" id="service-modal" onclick="if(event.target===this)closeModal()">
  <div class="modal-box">
    <div class="modal-header">
      <span class="m-title" id="m-title">—</span>
      <button class="modal-close" onclick="closeModal()">×</button>
    </div>
    <div class="modal-body">
      <p class="m-desc" id="m-desc"></p>
      <div class="m-row"><span class="m-label">⏱️ <?= $lang==='ar'?'وقت التنفيذ:':'Response time:' ?></span><span class="m-val" id="m-sla"></span></div>
      <div class="m-row"><span class="m-label">⭐ <?= $lang==='ar'?'التقييم:':'Rating:' ?></span><span class="m-val" id="m-rating"></span></div>
      <div class="m-row"><span class="m-label">👥 <?= $lang==='ar'?'المزودون:':'Providers:' ?></span><span class="m-val" id="m-count"></span></div>
      <div class="m-row"><span class="m-label">💰 <?= $lang==='ar'?'السعر:':'Price:' ?></span><span class="m-val" id="m-price"></span></div>
      <div class="social-proof" id="m-social">📊 <span id="m-social-text"></span></div>
      <div class="trust-line">✔ <?= $lang==='ar'?'تنفيذ مضمون أو استرجاع الرصيد':'Guaranteed execution or full refund' ?></div>
      <button class="modal-cta" id="m-cta" onclick="startExecution()">
        🚀 <?= $lang==='ar'?'ابدأ التنفيذ الآن':'Start Execution Now' ?>
      </button>
    </div>
  </div>
</div>

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

// ── Category data for modal ─────────────────────────────────
const CATS = {
<?php foreach($categories as $cat): ?>
  '<?= $cat['id'] ?>': {
    id:'<?= $cat['id'] ?>', icon:'<?= $cat['icon'] ?>',
    name: LANG==='ar' ? '<?= $lang==='ar'?addslashes($cat['ar']):addslashes($cat['en']) ?>' : '<?= addslashes($cat['en']) ?>',
    desc: LANG==='ar' ? '<?= addslashes($cat['desc_ar']) ?>' : '<?= addslashes($cat['desc_en']) ?>',
    price: <?= $cat['price'] ?>, sla: <?= $cat['sla'] ?>, rating: <?= $cat['rating'] ?>,
    count: <?= (int)$cat['count'] ?>, executed: <?= (int)$cat['executed'] ?>,
  },
<?php endforeach; ?>
};

let currentCat = null;

function openModal(id) {
  const cat = CATS[id]; if (!cat) return;
  currentCat = cat;
  document.getElementById('m-title').textContent = cat.icon + ' ' + cat.name;
  document.getElementById('m-desc').textContent = cat.desc;
  document.getElementById('m-sla').textContent = LANG==='ar' ? 'حتى '+cat.sla+' ساعة' : 'Up to '+cat.sla+'h';
  document.getElementById('m-rating').textContent = '⭐ ' + cat.rating.toFixed(1) + ' / 5.0';
  document.getElementById('m-count').textContent = cat.count > 0 ? cat.count + (LANG==='ar'?' مزوّد متاح':' providers available') : (LANG==='ar'?'قريباً':'Coming soon');
  document.getElementById('m-price').textContent = cat.price > 0 ? (LANG==='ar'?'من ':'from ')+cat.price+' SDG' : (LANG==='ar'?'🆓 مجاني':'🆓 Free');
  const spText = cat.executed > 0
    ? (LANG==='ar' ? 'تم تنفيذ '+cat.executed+' طلب' : cat.executed+' requests executed')
    : (LANG==='ar' ? 'جديد — كن أول المستخدمين 🎯' : 'New — be the first 🎯');
  document.getElementById('m-social-text').textContent = spText;
  document.getElementById('service-modal').classList.add('open');
  document.body.style.overflow = 'hidden';
}

function closeModal() {
  document.getElementById('service-modal').classList.remove('open');
  document.body.style.overflow = '';
}

function startExecution() {
  if (!currentCat) return;
  window.location.href = SITE_URL + '/app/flow.php?category=' + currentCat.id + '&amount=' + currentCat.price;
}

// ── Search ─────────────────────────────────────────────────
function searchServices() {
  const q = document.getElementById('search-input').value.toLowerCase().trim();
  document.querySelectorAll('.cat-card').forEach(card => {
    const text = card.textContent.toLowerCase();
    card.style.display = (!q || text.includes(q)) ? '' : 'none';
  });
}
document.getElementById('search-input').addEventListener('keyup', e => { if(e.key==='Enter') searchServices(); });

// ── Sort ───────────────────────────────────────────────────
document.querySelectorAll('.filter-pill').forEach(btn => {
  btn.addEventListener('click', function() {
    document.querySelectorAll('.filter-pill').forEach(b => b.classList.remove('active'));
    this.classList.add('active');
    const sort = this.dataset.sort;
    const grid = document.getElementById('services-grid');
    const cards = [...grid.querySelectorAll('.cat-card')];
    if (sort === 'popular') cards.sort((a,b) => +(b.dataset.count||0) - +(a.dataset.count||0));
    else if (sort === 'price') cards.sort((a,b) => +(a.dataset.price||999) - +(b.dataset.price||999));
    else if (sort === 'free') { cards.forEach(c => { c.style.display = +(c.dataset.price||1) === 0 ? '' : 'none'; }); return; }
    else cards.sort((a,b) => a.dataset.id.localeCompare(b.dataset.id));
    cards.forEach(c => { c.style.display = ''; grid.appendChild(c); });
  });
});

document.addEventListener('keydown', e => { if(e.key === 'Escape') closeModal(); });
</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>

<script>
// ══ Service Payment Integration ══════════════════════════════
async function payForService(providerId, amount, serviceType, description) {
  const pin = prompt('أدخل رقم PIN الخاص بك لإتمام الدفع:');
  if (!pin) return;
  
  const btn = event.target;
  btn.disabled = true;
  btn.textContent = 'جاري الدفع...';
  
  try {
    // bookAndPay wrapper
async function bookAndPay(pid,amt,type,desc){const pin=prompt("PIN:");if(!pin)return;const r2=await fetch('/api/services/pay.php',{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider_user_id:pid,amount_sdg:amt,service_type:type,description:desc,pin})});const d=await r2.json();alert(d.ok?"✅ "+d.message:"❌ "+(d.message||d.error));if(d.ok)location.reload();}
        const r = await fetch('/api/services/pay.php', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({
        provider_user_id: providerId,
        amount_sdg:       amount,
        service_type:     serviceType,
        pin:              pin,
        description:      description
      })
    });
    const d = await r.json();
    if (d.ok) {
      alert(`✅ تم الدفع!
المرجع: ${d.txn_ref}
المبلغ: ${d.amount_sdg} SDG
عمولة المنصة: ${d.platform_fee} SDG`);
      location.reload();
    } else {
      const msgs = {
        invalid_pin: 'PIN خاطئ — تحقق وأعد المحاولة',
        insufficient_balance: 'رصيد غير كافٍ — اشحن محفظتك أولاً',
        min_amount: 'الحد الأدنى للدفع 100 SDG'
      };
      alert('❌ ' + (msgs[d.error] || d.message || d.error || 'حدث خطأ'));
    }
  } catch(e) {
    alert('❌ تعذّر الاتصال — حاول مجدداً');
  }
  btn.disabled = false;
  btn.textContent = 'ادفع الآن';
}

// تحميل خدمات المزودين
async function loadProviderServices() {
  try {
    const r = await fetch('/api/services/history.php?limit=10');
    const d = await r.json();
    const container = document.getElementById('my-services-history');
    if (!container || !d.data?.length) return;
    container.innerHTML = d.data.map(s => `
      <div style="display:flex;justify-content:space-between;padding:10px 0;border-bottom:1px solid var(--border,#e2e8f0)">
        <div>
          <div style="font-weight:600;font-size:.85rem">${s.service_type}</div>
          <div style="font-size:.72rem;color:var(--muted,#64748b)">${(s.created_at||'').substring(0,16)}</div>
        </div>
        <div style="text-align:right">
          <div style="font-weight:800">${Number(s.amount_sdg||0).toLocaleString('ar-SA')} SDG</div>
          <div style="font-size:.68rem;color:${s.status==='completed'?'#059669':'#d97706'}">${s.status==='completed'?'مكتملة':'جارية'}</div>
        </div>
      </div>`).join('');
  } catch(e) {}
}

document.addEventListener('DOMContentLoaded', loadProviderServices);
</script>

<script src="/assets/pricing-loader.js" defer></script>
</body>
</html>
