<?php
require_once __DIR__.'/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__.'/../../engine/Logger.php';
require_once __DIR__.'/../../engine/ServicePaymentEngine.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)??[];
$providerId  = (int)($b['provider_user_id']??0);
$amount      = (float)($b['amount_sdg']??0);
$serviceType = preg_replace('/[^a-z_]/','',strtolower($b['service_type']??'other'));
$pin         = trim($b['pin']??'');
$bookingId   = (int)($b['booking_id']??0);
$desc        = mb_substr(trim($b['description']??''),0,100);
if(!$providerId||$amount<100||!$pin){http_response_code(400);die(json_encode(['error'=>'invalid_input']));}
$result = ServicePaymentEngine::payForService((int)$u['id'],$providerId,$amount,$serviceType,$pin,$bookingId,$desc);
http_response_code(($result['ok']??false)?200:400);
echo json_encode($result, JSON_UNESCAPED_UNICODE);
