<?php
// miniapp/api/plans.php
error_reporting(0); // برای جلوگیری از به‌هم‌ریختن JSON با Warning
header('Content-Type: application/json; charset=utf-8');

require __DIR__ . '/config.php';

$userId = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;

if ($userId <= 0) {
    echo json_encode(['ok' => false, 'error' => 'User ID required'], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    // دسته‌بندی‌ها از جدول plan_categories
    $stmtCat = $pdo->query("
        SELECT code, name, display_order
        FROM plan_categories
        WHERE is_active = 1
        ORDER BY display_order ASC, id ASC
    ");
    $categories = $stmtCat->fetchAll(PDO::FETCH_ASSOC);

    // پلن‌های فعال از جدول اصلی plans
    $stmtPlans = $pdo->query("
        SELECT id,
               category,
               duration_label,
               users,
               price,
               plan_code,
               title
        FROM plans
        WHERE is_active = 1
        ORDER BY category, price ASC, id ASC
    ");
    $plans = $stmtPlans->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'ok'   => true,
        'data' => [
            'categories' => $categories ?: [],
            'plans'      => $plans ?: [],
        ],
    ], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    echo json_encode([
        'ok'   => false,
        'error'=> 'Database Error: ' . $e->getMessage(),
        'data' => ['categories' => [], 'plans' => []]
    ], JSON_UNESCAPED_UNICODE);
}
