<?php
require_once __DIR__.'/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__.'/../../engine/Logger.php';
require_once __DIR__.'/../../engine/SudannaPayEngine.php';
if ($_SERVER['REQUEST_METHOD']!=='POST'){http_response_code(405);exit;}
$ctx = Kernel::handle(['auth' => true]);
$u   = $ctx['user'];

// BRIDGE: rate limiting
$_rl_uid = (int)($u['id'] ?? 0);
if (!check_rate_limit('gov_pay_' . $_rl_uid, 5, 60)) {
    http_response_code(429);
    die(json_encode(['error'=>'rate_limit','message'=>'طلبات كثيرة. انتظر قليلاً.']));
}
unset($_rl_uid);
$b = json_decode(file_get_contents('php://input'),true)??[];
$serviceCode = preg_replace('/[^A-Z0-9_]/','',strtoupper($b['service_code']??''));
$pin         = trim($b['pin']??'');
$extraData   = $b['extra_data']??[];
if(!$serviceCode||!$pin){http_response_code(400);die(json_encode(['error'=>'missing_fields']));}
try {
  $st = db()->prepare("SELECT * FROM sdpay_gov_services WHERE service_code=? AND is_active=1 LIMIT 1");
  $st->execute([$serviceCode]);
  $svc = $st->fetch();
  if(!$svc){http_response_code(404);die(json_encode(['error'=>'service_not_found']));}
  if(!SudannaPayEngine::verifyPin((int)$u['id'],$pin)){http_response_code(401);die(json_encode(['error'=>'invalid_pin']));}
  $acc = SudannaPayEngine::getAccount((int)$u['id']);
  if(!$acc){http_response_code(402);die(json_encode(['error'=>'no_pay_account']));}
  if((float)$acc['balance_sdg']<(float)$svc['fee_sdg']){
    http_response_code(402);die(json_encode(['error'=>'insufficient_balance','required'=>$svc['fee_sdg'],'available'=>$acc['balance_sdg']]));
  }
  if($svc['fee_sdg']>0){
    db()->prepare("UPDATE sdpay_accounts SET balance_sdg=balance_sdg-? WHERE user_id=?")->execute([$svc['fee_sdg'],(int)$u['id']]);
  }
  $ref = 'GOV'.date('YmdHis').strtoupper(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 (?,'bill',?,?,0,?,'completed','app',?,?)")
     ->execute([$ref,$acc['account_no'],$svc['fee_sdg'],$svc['fee_sdg'],'رسوم حكومية: '.$svc['service_name_ar'],json_encode(['service_code'=>$serviceCode,'ministry'=>$svc['ministry'],'extra'=>$extraData])]);
  echo json_encode(['ok'=>true,'ref'=>$ref,'service'=>$svc['service_name_ar'],'fee'=>$svc['fee_sdg'],'processing_days'=>$svc['processing_days']], JSON_UNESCAPED_UNICODE);
} catch(Throwable $e){http_response_code(500);echo json_encode(['error' => 'server_error', 'message' => 'خطأ مؤقت — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE);}
