<?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'];
$b = json_decode(file_get_contents('php://input'),true)??[];
$pin    = trim($b['pin']??'');
$oldPin = trim($b['old_pin']??'');
$uid = (int)$u['id'];
// إذا عنده PIN قديم — تحقق منه
$acc = SudannaPayEngine::getAccount($uid);
if($acc && !empty($acc['pin_hash']) && $oldPin){
  if(!SudannaPayEngine::verifyPin($uid,$oldPin)){http_response_code(401);die(json_encode(['error'=>'wrong_old_pin']));}
}
$result = SudannaPayEngine::setPin($uid, $pin);
echo json_encode($result, JSON_UNESCAPED_UNICODE);
