<?php
/**
 * GET /api/subscription/status.php
 * WAVE E — Full Kernel Replace
 * Returns current user's subscription status + usage limits
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../../engine/PricingEngine.php';

$ctx     = Kernel::handle(['auth' => true]);
$u       = $ctx['user'];
$uid     = (int)$u['id'];
$planKey = $u['plan_key'] ?? $u['subscription_tier'] ?? 'free';

try {
    // Active subscription
    $sub = null;
    $s   = db()->prepare("SELECT * FROM user_subscriptions WHERE user_id=? AND status='active' LIMIT 1");
    $s->execute([$uid]);
    $sub = $s->fetch() ?: null;

    // AI usage today
    $aiQ = db()->prepare(
        "SELECT COUNT(*) FROM ai_usage WHERE user_id=? AND DATE(created_at)=CURDATE()"
    );
    $aiQ->execute([$uid]);
    $aiUsed = (int)$aiQ->fetchColumn();

    $limits = [
        'ai'      => PricingEngine::getAILimit($planKey),
        'booking' => PricingEngine::getBookingLimit($planKey),
    ];

    Kernel::respond([
        'success'      => true,
        'plan_key'     => $planKey,
        'is_premium'   => in_array($planKey, ['plus','pro','paid']),
        'subscription' => $sub,
        'usage'        => ['ai_today' => $aiUsed],
        'limits'       => $limits,
        'ai_remaining' => max(0, $limits['ai'] - $aiUsed),
    ]);

} catch (Throwable $e) {
    Logger::error('subscription_status_failed', ['user_id' => $uid, 'error' => $e->getMessage()]);
    Kernel::fail('fetch_failed', 'تعذّر تحميل حالة الاشتراك', 500);
}
