<?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)??[];
$bookingId = (int)($b['booking_id']??0);
$pin       = trim($b['pin']??'');
if(!$bookingId||!$pin){http_response_code(400);die(json_encode(['error'=>'booking_id and pin required']));}
try {
    $booking = db()->prepare("SELECT * FROM bookings WHERE id=? AND user_id=? LIMIT 1");
    $booking->execute([$bookingId,(int)$u['id']]);
    $bk = $booking->fetch();
    if(!$bk){http_response_code(404);die(json_encode(['error'=>'booking_not_found']));}
    if($bk['payment_status']==='paid'){die(json_encode(['ok'=>true,'message'=>'already_paid','txn_ref'=>$bk['payment_ref']]));}
    $result = ServicePaymentEngine::payForService(
        (int)$u['id'],(int)$bk['provider_id'],
        (float)$bk['price_sdg'],$bk['service_type']??'other',
        $pin,$bookingId,'دفع حجز #'.$bookingId
    );
    http_response_code(($result['ok']??false)?200:400);
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
} catch(\Throwable $e){http_response_code(500);echo json_encode(['error' => 'server_error', 'message' => 'خطأ مؤقت — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE);}
