<?php
// plans.php
// خروجی JSON برای لیست پلن‌ها

header('Content-Type: application/json; charset=utf-8');

require __DIR__ . '/db.php';

try {
    // فقط پلن‌های فعال
    $sql = "
        SELECT
            code,
            panel_key,
            title,
            amount_rial,
            amount_old_rial,
            imgurl,
            imgurlmob,
            plan_desc,
            is_recommended,
            duration_days,
            duration_months
        FROM plans
        WHERE is_active = 1
        ORDER BY amount_rial ASC, id ASC
    ";

    $stmt = $pdo->query($sql);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $plans = [];

    foreach ($rows as $r) {
        $plans[] = [
            'code'             => $r['code'],
            'panel_key'        => $r['panel_key'] ?? '',
            'title'            => $r['title'],
            'amount_rial'      => is_null($r['amount_rial'])      ? 0 : (int)$r['amount_rial'],
            'amount_old_rial'  => is_null($r['amount_old_rial'])  ? 0 : (int)$r['amount_old_rial'],
            'imgurl'           => $r['imgurl']        ?? '',
            'imgurlmob'        => $r['imgurlmob']     ?? '',
            'plan_desc'        => $r['plan_desc']     ?? '',
            'is_recommended'   => !empty($r['is_recommended']) ? 1 : 0,

            // 🔹 برای محاسبه مدت در فرانت
            'duration_days'    => isset($r['duration_days'])   ? (int)$r['duration_days']   : 0,
            'duration_months'  => isset($r['duration_months']) ? (int)$r['duration_months'] : 0,
        ];
    }

    echo json_encode([
        'ok'    => true,
        'plans' => $plans,
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

} catch (Throwable $e) {
    http_response_code(500);

    echo json_encode([
        'ok'    => false,
        'error' => 'DB_ERROR',
        // 'detail'=> $e->getMessage(),
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}
