<?php
/**
 * POST /api/payment/create_invoice.php
 * Creates invoice + BillingEngine hold
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../../engine/InvoiceEngine.php';
require_once __DIR__ . '/../../engine/BillingEngine.php';
require_once __DIR__ . '/../../engine/Logger.php'; // BRIDGE
Logger::traceId();                                  // establish trace
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); die(json_encode(['error'=>'method_not_allowed']));
}

$ctx = Kernel::handle(['auth' => 'optional']);
$u = $ctx['user'];
$userId = $u ? (int)$u['id'] : (int)($_SESSION['user_id'] ?? 0);
if (!$userId) { http_response_code(401); die(json_encode(['error'=>'not_authenticated'])); }

$data    = json_decode(file_get_contents('php://input'), true) ?: [];
$service = preg_replace('/[^a-z_]/', '', $data['service'] ?? 'general');
$amount  = (float)($data['amount'] ?? 0);
$method  = in_array($data['method'] ?? '', ['offline','gateway']) ? $data['method'] : 'offline';

if ($amount <= 0) { http_response_code(422); die(json_encode(['error'=>'invalid_amount'])); }

try {
    // ── BillingEngine: reserve hold ──────────────────────────
    $planKey = $u['plan_key'] ?? $u['subscription_tier'] ?? 'free';
    $billing = BillingEngine::evaluate($userId, $service, []);
    if ($billing['decision'] === 'create_invoice') {
        // Hold the amount in wallet
        $holdResult = BillingEngine::holdFunds($userId, $amount, $service);
        if (!($holdResult['ok'] ?? true)) {
            http_response_code(402);
            die(json_encode(['error'=>'insufficient_balance',
                'message'=>'رصيد غير كافٍ. اشحن المحفظة أولاً.',
                'balance' => $holdResult['balance'] ?? 0,
                'required'=> $amount]));
        }
    }

    // ── Create invoice ────────────────────────────────────────
    $result = InvoiceEngine::create($userId, $service, $amount, [
        'payment_method' => $method,
        'meta'           => $data['meta'] ?? [],
    ]);

    if (!$result['success']) {
        // Rollback hold if invoice creation fails
        BillingEngine::rollbackFunds($userId, $amount, $service);
        http_response_code(500);
        die(json_encode($result));
    }

    if ($method === 'gateway') {
        $result['webhook_url'] = rtrim(SITE_URL, '/') . '/api/payment/webhook.php';
    }

    Logger::info('invoice_created', [
        'invoice_id' => $result['invoice_id'] ?? null,
        'service'    => $service,
        'amount_sdg' => $amount,
        'method'     => $method,
    ]);
    echo json_encode($result, JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    error_log("[create_invoice] " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'server_error', 'message' => 'خطأ مؤقت — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE);
}
