<?php
/**
 * List Available Subscription Plans
 * GET /api/v1/subscriptions/plans
 */

use App\Core\Database;

// No auth required — public endpoint for pricing page

$db = Database::getInstance();

try {
    $stmt = $db->query("
        SELECT id, name_ar, name_en, max_companies, max_invoices_month, max_users,
               price_jod, ai_features, jofotara_enabled, sort_order
        FROM subscription_plans
        WHERE is_active = 1
        ORDER BY sort_order ASC
    ");
    $plans = $stmt->fetchAll();

    // Merge with config features (for richer display)
    $configPlans = require APP_PATH . '/config/plans.php';

    foreach ($plans as &$plan) {
        $configPlan = $configPlans[$plan['id']] ?? null;
        if ($configPlan) {
            $plan['description_ar'] = $configPlan['description_ar'] ?? '';
            $plan['features']       = $configPlan['features'] ?? [];
            $plan['badge_color']    = $configPlan['badge_color'] ?? 'gray';
            $plan['is_popular']     = $configPlan['is_popular'] ?? false;
        }
        // Cast numeric fields
        $plan['max_companies']      = (int)$plan['max_companies'];
        $plan['max_invoices_month'] = (int)$plan['max_invoices_month'];
        $plan['max_users']          = (int)$plan['max_users'];
        $plan['price_jod']          = (float)$plan['price_jod'];
        $plan['ai_features']        = (bool)$plan['ai_features'];
        $plan['jofotara_enabled']   = (bool)$plan['jofotara_enabled'];
    }

    json_success($plans, 'الباقات المتاحة');

} catch (\Exception $e) {
    error_log("Subscription Plans Error: " . $e->getMessage());

    // Fallback to config file
    $configPlans = require APP_PATH . '/config/plans.php';
    $fallback = array_values($configPlans);
    json_success($fallback, 'الباقات المتاحة (من الإعدادات)');
}
