<?php
/**
 * POST /api/bills/pay.php
 * Bill payment — bridges to BillPayEngine
 * WAVE A: Logger + trace_id + error masking added
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../../engine/BillPayEngine.php';


if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') Kernel::fail('method_not_allowed','',405);
$ctx = Kernel::handle(['auth' => true, 'rate' => 'api']);
$u   = $ctx['user'];
$uid = (int)$u['id'];

$uid = (int)$u['id'];

$b          = json_decode(file_get_contents('php://input'), true) ?? [];
$providerId = (int)($b['provider_id'] ?? 0);
$accountRef = mb_substr(trim($b['account_ref'] ?? ''), 0, 50);
$amount     = (float)($b['amount_sdg'] ?? 0);
$pin        = trim($b['pin'] ?? '');

if (!$providerId || !$accountRef || $amount < 100 || !$pin) {
    http_response_code(400);
    die(json_encode(['error' => 'invalid_input', 'message' => 'بيانات الدفع غير مكتملة'], JSON_UNESCAPED_UNICODE));
}

try {
    $result = BillPayEngine::pay($uid, $providerId, $accountRef, $amount, $pin);

    if ($result['ok'] ?? false) {
        Logger::info('bill_payment', [
            'user_id'     => $uid,
            'provider_id' => $providerId,
            'amount_sdg'  => $amount,
        ]);
    } else {
        Logger::warn('bill_payment_failed', [
            'user_id'     => $uid,
            'provider_id' => $providerId,
            'error'       => $result['error'] ?? 'unknown',
        ]);
    }

    http_response_code(($result['ok'] ?? false) ? 200 : 400);
    echo json_encode(array_merge($result, ['trace_id' => Logger::traceId()]), JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    Logger::error('bill_payment_exception', ['user_id' => $uid, 'error' => $e->getMessage()]);
    http_response_code(500);
    echo json_encode(['error' => 'payment_failed', 'message' => 'فشل الدفع — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE);
}
