<?php
/**
 * POST /api/subscription/activate.php  (Admin only)
 * Activates a subscription for a user
 * Body: {user_id, plan_key, months, payment_ref, payment_id}
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';

// Session must start AFTER config to use secure cookie params
$ctx = Kernel::handle(['auth' => 'admin']);
Logger::setContext('admin_id', (int)($_SESSION['admin']['id'] ?? 0));
if ($_SERVER['REQUEST_METHOD'] !== 'POST') Kernel::fail('method_not_allowed', '', 405);

$b        = json_decode(file_get_contents('php://input'), true) ?? [];
$userId   = (int)($b['user_id']   ?? 0);
$planKey  = trim($b['plan_key']   ?? '');
$months   = max(1, (int)($b['months'] ?? 1));
$payRef   = trim($b['payment_ref'] ?? '');
$payId    = (int)($b['payment_id'] ?? 0);

if (!$userId || !in_array($planKey, ['free','plus','pro']))
    Kernel::fail('invalid_params', '', 400);

$expires = date('Y-m-d H:i:s', strtotime("+{$months} months"));

try {
    db()->beginTransaction();

    // Deactivate old subscriptions
    db()->prepare("UPDATE user_subscriptions SET status='cancelled' WHERE user_id=? AND status='active'")
       ->execute([$userId]);

    // Get plan
    $plan = db()->prepare("SELECT id FROM subscription_plans WHERE plan_key=? LIMIT 1");
    $plan->execute([$planKey]);
    $planRow = $plan->fetch();

    // Insert new subscription
    db()->prepare(
        "INSERT INTO user_subscriptions (user_id, plan_id, plan_key, status, expires_at, payment_ref, created_by)
         VALUES (?,?,?,'active',?,?,?)"
    )->execute([$userId, $planRow['id'] ?? 0, $planKey, $expires, $payRef,
        $_SESSION['admin']['id'] ?? $_SESSION['staff_id'] ?? 0]);  // use admin.id

    // Update user record
    db()->prepare(
        "UPDATE users SET plan_key=?, subscription_tier=?,
         plan_expires_at=?, subscription_expires_at=? WHERE id=?"
    )->execute([$planKey, $planKey === 'free' ? 'free' : 'paid', $expires, $expires, $userId]);

    // Verify payment record
    if ($payId) {
        db()->prepare(
            "UPDATE payments SET status='verified', verified_by=?, verified_at=NOW() WHERE id=?"
        )->execute([$_SESSION['staff_id'] ?? 0, $payId]);
    }

    // Provision monthly AI + booking credits based on plan
    try {
        require_once __DIR__ . '/../../engine/PricingEngine.php';
        $creditSdg = match($planKey) {
            'plus' => (int)PricingEngine::getSetting('sub_plus_credit_sdg', 5000),
            'pro'  => (int)PricingEngine::getSetting('sub_pro_credit_sdg', 15000),
            default => 0,
        };
        if ($creditSdg > 0) {
            db()->prepare(
                "INSERT INTO subscription_credits
                 (user_id, plan_key, remaining_sdg, total_sdg, period_month, period_year)
                 VALUES (?,?,?,?,MONTH(NOW()),YEAR(NOW()))
                 ON DUPLICATE KEY UPDATE remaining_sdg=VALUES(remaining_sdg), total_sdg=VALUES(total_sdg)"
            )->execute([$userId, $planKey, $creditSdg, $creditSdg]);
        }
    } catch (Throwable $credErr) {
        Logger::warn('subscription_credit_provision_failed', ['user_id' => $userId, 'error' => $credErr->getMessage()]);
    }

    db()->commit();

    // Notify user
    $token = get_user_token($userId);
    if ($token) send_push($token, '✅ تم تفعيل اشتراكك!',
        "باقة {$planKey} نشطة حتى " . date('d/m/Y', strtotime($expires)));
    save_notification($userId, 'subscription_activated', 'اشتراكك نشط!',
        "باقة {$planKey} مفعّلة حتى " . date('d/m/Y', strtotime($expires)));

    Logger::info('subscription_activated', [
        'user_id'  => $userId,
        'plan_key' => $planKey,
        'months'   => $months,
        'expires'  => $expires,
    ]);
    json_response(['success'=>true,'expires_at'=>$expires,'plan_key'=>$planKey,
                   'trace_id'=>Logger::traceId()]);
} catch (Throwable $e) {
    db()->rollBack();
    Logger::error('subscription_activate_failed', [
        'user_id' => $userId,
        'plan'    => $planKey,
        'error'   => $e->getMessage(),
    ]);
    Kernel::fail('activation_failed', 'فشل التفعيل — راجع الفريق الفني', 500);
}
