<?php
/**
 * GET /api/subscription/plans.php
 * WAVE E — Full Kernel Replace
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';

$ctx = Kernel::handle(['auth' => false, 'public' => true]);

try {
    $plans = db()->query(
        "SELECT plan_key, name_ar, name_en, price_sdg, price_usd,
                ai_calls_day, storage_mb, features_json, is_active
         FROM subscription_plans WHERE is_active=1 ORDER BY price_sdg ASC"
    )->fetchAll(PDO::FETCH_ASSOC);

    foreach ($plans as &$p) {
        $p['features'] = json_decode($p['features_json'] ?? '[]', true) ?: [];
        unset($p['features_json']);
    }

    Kernel::respond(['plans' => $plans]);
} catch (Throwable $e) {
    Logger::error('plans_failed', ['error' => $e->getMessage()]);
    Kernel::fail('fetch_failed', 'تعذّر تحميل الخطط', 500);
}
