<?php
/**
 * Sudanna Pay — Inline Payment Widget
 * <script src="https://sudanna.ai/api/partners/widget.php?session=xxx"></script>
 */
header('Content-Type: application/javascript; charset=utf-8');
header('Access-Control-Allow-Origin: *');
require_once __DIR__.'/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
Kernel::handle(['auth' => false, 'public' => true]);
require_once __DIR__.'/../../engine/Logger.php';

$session = preg_replace('/[^a-f0-9]/', '', $_GET['session'] ?? '');
if(!$session){die('// invalid session');}

try {
    $st = db()->prepare(
        "SELECT spt.*, sp.partner_name FROM sdpay_partner_transactions spt
         JOIN sdpay_partners sp ON sp.id=spt.partner_id
         WHERE spt.session_token=? AND spt.status='pending' AND expires_at>NOW() LIMIT 1"
    );
    $st->execute([$session]);
    $txn = $st->fetch();
    if(!$txn){die("// session expired or not found");}
} catch(\Throwable $e){die("// db error");}

$amount    = number_format((float)$txn['amount_sdg'],0,'.',',');
$desc      = htmlspecialchars($txn['description']??'');
$paymentId = $txn['payment_id'];
$checkUrl  = '/api/partners/widget_pay.php';
?>
(function(){
  var SudannaPay = {
    session: '<?= $session ?>',
    paymentId: '<?= $paymentId ?>',
    amount: '<?= $amount ?>',
    description: '<?= $desc ?>',
    mount: function(containerId) {
      var el = document.getElementById(containerId);
      if(!el) return console.error('SudannaPay: container not found');
      el.innerHTML = `
        <div style="font-family:Cairo,system-ui,sans-serif;direction:rtl;background:#f0fdf4;border:1px solid #bbf7d0;border-radius:16px;padding:20px;max-width:360px">
          <div style="text-align:center;margin-bottom:16px">
            <div style="font-size:1.5rem;margin-bottom:4px">💳</div>
            <div style="font-weight:900;color:#073328;font-size:1rem">Sudanna Pay</div>
            <div style="font-size:.8rem;color:#64748b">${this.description}</div>
          </div>
          <div style="background:#fff;border-radius:10px;padding:14px;text-align:center;margin-bottom:14px">
            <div style="font-size:.75rem;color:#64748b;margin-bottom:4px">المبلغ المطلوب</div>
            <div style="font-size:1.8rem;font-weight:900;color:#073328">${this.amount} SDG</div>
          </div>
          <input type="tel" id="sdp_phone" placeholder="رقم جوالك" style="width:100%;background:#f8fafc;border:1.5px solid #e2e8f0;border-radius:10px;padding:10px 12px;font-family:inherit;font-size:15px;text-align:right;margin-bottom:8px;box-sizing:border-box">
          <input type="password" id="sdp_pin" placeholder="رقم PIN السري (4-6 أرقام)" maxlength="6" style="width:100%;background:#f8fafc;border:1.5px solid #e2e8f0;border-radius:10px;padding:10px 12px;font-family:inherit;font-size:15px;text-align:right;margin-bottom:12px;box-sizing:border-box">
          <button id="sdp_btn" onclick="SudannaPay._pay()" style="width:100%;background:linear-gradient(135deg,#00d97e,#059669);color:#fff;border:none;border-radius:12px;padding:13px;font-family:inherit;font-weight:800;font-size:.9rem;cursor:pointer">💳 ادفع الآن</button>
          <div id="sdp_msg" style="text-align:center;margin-top:10px;font-size:.82rem"></div>
          <div style="text-align:center;margin-top:8px;font-size:.68rem;color:#94a3b8">مدعوم بـ Sudanna Pay | آمن ومشفر</div>
        </div>`;
    },
    _pay: async function() {
      var phone = document.getElementById('sdp_phone').value.trim();
      var pin   = document.getElementById('sdp_pin').value.trim();
      var msg   = document.getElementById('sdp_msg');
      var btn   = document.getElementById('sdp_btn');
      if(!phone||!pin){msg.innerHTML='<span style="color:#dc2626">أدخل رقم الجوال والـ PIN</span>';return;}
      btn.disabled=true;btn.textContent='جاري الدفع...';
      try{
        var r = await fetch('<?= $checkUrl ?>', {
          method:'POST',
          headers:{'Content-Type':'application/json'},
          body: JSON.stringify({session:this.session, phone:phone, pin:pin})
        });
        var d = await r.json();
        if(d.ok){
          msg.innerHTML='<span style="color:#059669;font-size:1rem">✅ تم الدفع بنجاح!</span>';
          btn.style.display='none';
          if(typeof SudannaPayCallback==='function') SudannaPayCallback(d);
          if(d.redirect_url) setTimeout(()=>{window.location=d.redirect_url;},1500);
        }else{
          msg.innerHTML='<span style="color:#dc2626">❌ '+(d.message||d.error||'حدث خطأ')+'</span>';
          btn.disabled=false;btn.textContent='💳 ادفع الآن';
        }
      }catch(e){
        msg.innerHTML='<span style="color:#dc2626">تعذّر الاتصال</span>';
        btn.disabled=false;btn.textContent='💳 ادفع الآن';
      }
    }
  };
  window.SudannaPay = SudannaPay;
  document.dispatchEvent(new Event('SudannaPayReady'));
})();
