<?php
/**
 * POST /api/subscription/request.php
 * User requests a subscription upgrade
 * Body: {plan_key, payment_method, receipt_base64}
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../../engine/PricingEngine.php';

$ctx = Kernel::handle(['auth' => true, 'rate' => 'api']);
$u   = $ctx['user'];

// BRIDGE: rate limiting
$_rl_uid = (int)($u['id'] ?? 0);
if (!check_rate_limit('sub_req_' . $_rl_uid, 3, 3600)) {
    http_response_code(429);
    die(json_encode(['error'=>'rate_limit','message'=>'طلبات كثيرة. انتظر قليلاً.']));
}
unset($_rl_uid);
if ($_SERVER['REQUEST_METHOD'] !== 'POST') Kernel::fail('method_not_allowed', '', 405);

$b = json_decode(file_get_contents('php://input'), true) ?? [];
$plan_key = trim($b['plan_key'] ?? '');
$method   = trim($b['payment_method'] ?? 'bank_transfer');
$receipt  = $b['receipt_base64'] ?? null;

$allowed = ['plus','pro'];
if (!in_array($plan_key, $allowed))
    Kernel::fail('invalid_plan', 'الخطة غير متاحة', 400);

// Fetch plan price
$plan = null;
try {
    $st = db()->prepare("SELECT * FROM subscription_plans WHERE plan_key=? AND is_active=1 LIMIT 1");
    $st->execute([$plan_key]);
    $plan = $st->fetch();
} catch (Throwable $e) {}
if (!$plan) Kernel::fail('plan_not_found', '', 404);

// Save receipt image
$receipt_url = null;
if ($receipt) {
    if (strlen($receipt) > 3500000) Kernel::fail('file_too_large', '', 400);
    $receipt_url = save_uploaded_image($receipt);
}

// Create payment record
try {
    db()->prepare(
        "INSERT INTO payments (user_id, plan_id, amount_sdg, payment_method, receipt_url, status)
         VALUES (?,?,?,?,?,'pending')"
    )->execute([$u['id'], $plan['id'], $plan['price_sdg'], $method, $receipt_url]);

    $paymentId = (int)db()->lastInsertId();

    // Also create subscription_requests for admin panel
    try {
        db()->prepare(
            "INSERT INTO subscription_requests (user_id, plan_key, amount, payment_method, receipt_url, status)
             VALUES (?,?,?,?,?,'pending')"
        )->execute([$u['id'], $plan_key, $plan['price_sdg'], $method, $receipt_url]);
    } catch (Throwable $ignored) {}

    // Notify admins
    save_notification(1, 'new_payment', 'طلب اشتراك جديد',
        "{$u['name']} يطلب {$plan['name_ar']}", ['payment_id'=>(string)$paymentId]);

    Logger::info('subscription_requested', [
        'user_id'    => (int)$u['id'],
        'plan'       => $plan_key,
        'plan_name'  => $plan['name_ar'] ?? $plan_key,
        'amount_sdg' => $plan['price_sdg'],
        'method'     => $method,
        'payment_id' => $paymentId,
    ]);
    json_response([
        'success'    => true,
        'payment_id' => $paymentId,
        'receipt_submitted' => !empty($receipt_url),  // bool only — don't expose path
        'message'    => 'تم إرسال طلبك. سيُفعَّل الاشتراك خلال 24 ساعة بعد التحقق.',
        'trace_id'   => Logger::traceId(),
        'bank_details' => [
            'bank'    => PricingEngine::getSetting('pay_bank_name',    'بنك الخرطوم'),
            'account' => PricingEngine::getSetting('pay_bank_account', '1821425'),
            'name'    => PricingEngine::getSetting('pay_account_holder','سودانا للتقنية'),
            'amount'  => $plan['price_sdg'] . ' SDG',
        ],
    ]);
} catch (Throwable $e) {
    Logger::error('subscription_request_failed', ['user_id' => (int)$u['id'], 'error' => $e->getMessage()]);
    Kernel::fail('request_failed', 'خطأ مؤقت — حاول مجدداً', 500);
}
