<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if($_SERVER['REQUEST_METHOD']==='OPTIONS'){http_response_code(200);exit;}
require_once __DIR__.'/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
Kernel::handle(['auth' => false, 'public' => true]);
require_once __DIR__.'/../../engine/Logger.php';
require_once __DIR__.'/../../engine/SudannaPayEngine.php';
require_once __DIR__.'/../../engine/IntegrationEngine.php';
if($_SERVER['REQUEST_METHOD']!=='POST'){http_response_code(405);exit;}
$b = json_decode(file_get_contents('php://input'),true)??[];
$session = preg_replace('/[^a-f0-9]/','',$b['session']??'');
$phone   = trim($b['phone']??'');
$pin     = trim($b['pin']??'');
if(!$session||!$phone||!$pin){http_response_code(400);die(json_encode(['error'=>'missing_fields']));}

// ── P0 FIX: Rate limit برهان ثلاثي على PIN (brute-force protection) ──────
// 1. Per IP:   20 attempts / 60 seconds
// 2. Per phone: 5 attempts / 10 minutes
// 3. Per session: 3 attempts / 10 minutes (burns the session after 3 fails)
$_wp_ip   = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
$_wp_deny = function(string $msg) {
    http_response_code(429);
    die(json_encode(['ok'=>false,'error'=>'rate_limit','message'=>$msg]));
};

if (!check_rate_limit('wp_ip_' . md5($_wp_ip), 20, 60))
    $_wp_deny('طلبات كثيرة. انتظر دقيقة.');

if (!check_rate_limit('wp_phone_' . md5($phone), 5, 600))
    $_wp_deny('محاولات كثيرة. انتظر 10 دقائق.');

if (!check_rate_limit('wp_sess_' . md5($session), 3, 600)) {
    // After 3 fails on same session → expire it
    try {
        Logger::warn('widget_pay_failed', ['trace' => Logger::traceId()]);
        db()->prepare("UPDATE sdpay_partner_transactions SET status='failed' WHERE session_token=?")
            ->execute([$session]);
    } catch (\Throwable $ignored) {}
    $_wp_deny('تم تجاوز محاولات الدفع. أعد المحاولة من البداية.');
}
unset($_wp_ip, $_wp_deny);
// ── END P0 FIX ──────────────────────────────────────────────────────────
try {
    $st = db()->prepare(
        "SELECT spt.*,sp.webhook_url,sp.api_secret_hash 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){http_response_code(400);die(json_encode(['ok'=>false,'error'=>'session_expired']));}

    // الحصول على حساب المدفوع بالهاتف
    $custAcc = SudannaPayEngine::getAccountByPhone($phone);
    if(!$custAcc){http_response_code(404);die(json_encode(['ok'=>false,'error'=>'account_not_found','message'=>'رقم الجوال غير مسجل في Sudanna Pay']));}

    // التحقق من PIN
    if(!SudannaPayEngine::verifyPin($custAcc['user_id'], $pin)){
        http_response_code(401);die(json_encode(['ok'=>false,'error'=>'invalid_pin','message'=>'رقم PIN خاطئ']));
    }

    // تحقق من الرصيد
    if((float)$custAcc['balance_sdg'] < (float)$txn['amount_sdg']){
        http_response_code(402);die(json_encode(['ok'=>false,'error'=>'insufficient_balance','message'=>'رصيد غير كافٍ','available'=>$custAcc['balance_sdg'],'required'=>$txn['amount_sdg']]));
    }

    // خصم المبلغ
    db()->beginTransaction();
    try {
        db()->prepare("UPDATE sdpay_accounts SET balance_sdg=balance_sdg-? WHERE user_id=?")->execute([$txn['amount_sdg'],$custAcc['user_id']]);
        $txnRef='WGT'.date('YmdHis').substr(md5(uniqid()),0,6);
        db()->prepare("INSERT INTO sdpay_transactions (txn_ref,type,from_account,amount_sdg,fee_sdg,net_sdg,status,channel,narration,metadata) VALUES (?,'merchant',?,?,0,?,'completed','api',?,?)")
           ->execute([$txnRef,$custAcc['account_no'],$txn['amount_sdg'],$txn['amount_sdg'],'دفع: '.$txn['description'],json_encode(['payment_id'=>$txn['payment_id'],'partner_reference'=>$txn['partner_reference']])]);
        db()->prepare("UPDATE sdpay_partner_transactions SET status='completed',completed_at=NOW() WHERE id=?")->execute([$txn['id']]);
        db()->commit();
        Logger::info('widget_pay_completed', [
            'txn_ref'          => $txnRef,
            'amount_sdg'       => $txn['amount_sdg'],
            'payment_id'       => $txn['payment_id'] ?? null,
            'partner_reference'=> $txn['partner_reference'] ?? null,
        ]);
        // Webhook
        if($txn['webhook_url']){
            IntegrationEngine::sendWebhook($txn['webhook_url'],['event'=>'payment.completed','payment_id'=>$txn['payment_id'],'partner_reference'=>$txn['partner_reference'],'amount_sdg'=>$txn['amount_sdg'],'txn_ref'=>$txnRef,'completed_at'=>date('c')],$txn['api_secret_hash']);
        }
        echo json_encode(['ok'=>true,'txn_ref'=>$txnRef,'payment_id'=>$txn['payment_id'],'amount_sdg'=>$txn['amount_sdg'],'message'=>'تم الدفع بنجاح'], JSON_UNESCAPED_UNICODE);
    } catch(\Throwable $e){db()->rollBack();throw $e;}
} catch(\Throwable $e){
    http_response_code(500);echo json_encode(['error' => 'server_error', 'message' => 'خطأ مؤقت — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE);
}
