<?php
require_once 'config.php';
require_once 'plan_price_helper.php';
header('Content-Type: application/json; charset=utf-8');
function plans_add_column_if_missing(PDO $pdo, string $table, string $column, string $definition): void {
    try {
        if (function_exists('gemacc_column_exists') && gemacc_column_exists($pdo, $table, $column)) return;
        $pdo->exec("ALTER TABLE `{$table}` ADD COLUMN `{$column}` {$definition}");
    } catch (Throwable $e) {}
}
plans_add_column_if_missing($pdo, 'plan_categories', 'service_type', "VARCHAR(30) NOT NULL DEFAULT 'openvpn_l2tp' AFTER `code`");
plans_add_column_if_missing($pdo, 'plan_categories', 'service_name', "VARCHAR(100) NULL AFTER `service_type`");
plans_add_column_if_missing($pdo, 'plan_categories', 'traffic_type', "VARCHAR(20) NOT NULL DEFAULT 'unlimited' AFTER `months`");
plans_add_column_if_missing($pdo, 'plan_categories', 'traffic_limit_gb', "INT UNSIGNED NULL AFTER `traffic_type`");
plans_add_column_if_missing($pdo, 'plans', 'service_name', "VARCHAR(100) NULL AFTER `protocol`");
plans_add_column_if_missing($pdo, 'plans', 'traffic_type', "VARCHAR(20) NOT NULL DEFAULT 'unlimited' AFTER `protocol`");
plans_add_column_if_missing($pdo, 'plans', 'traffic_limit_gb', "INT UNSIGNED NULL AFTER `traffic_type`");

function planNormalizeServiceType(string $raw, string $hint=''): string {
    $s = function_exists('mb_strtolower') ? mb_strtolower(trim($raw), 'UTF-8') : strtolower(trim($raw));
    $h = function_exists('mb_strtolower') ? mb_strtolower(trim($hint), 'UTF-8') : strtolower(trim($hint));
    if (in_array($s, ['windscribe','ws','ویندسکرایب'], true) || str_contains($h, 'windscribe') || str_contains($h, 'ویندسکرایب')) return 'windscribe';
    if (in_array($s, ['expressvpn','express','اکسپرس','express vpn'], true) || str_contains($h, 'express') || str_contains($h, 'اکسپرس')) return 'expressvpn';
    if (in_array($s, ['v2ray','v2','vmess','vless','trojan','ویتوری','وی تو ری','وی‌تو‌ری'], true) || str_contains($h, 'v2ray') || str_contains($h, 'vmess') || str_contains($h, 'vless') || str_contains($h, 'trojan') || str_contains($h, 'ویتوری') || str_contains($h, 'وی تو ری') || str_contains($h, 'وی‌تو‌ری')) return 'v2ray';
    return 'openvpn_l2tp';
}
function planServiceLabel(string $type, string $custom=''): string {
    $custom = trim($custom);
    if ($custom !== '') return $custom;
    return $type === 'windscribe' ? 'Windscribe' : ($type === 'expressvpn' ? 'ExpressVPN' : ($type === 'v2ray' ? 'V2Ray' : 'OpenVPN | L2TP'));
}
$cats=$pdo->query("SELECT *, CASE WHEN service_type IN ('windscribe','expressvpn','v2ray') THEN CONCAT(name,' - ',COALESCE(NULLIF(service_name,''), CASE WHEN service_type='windscribe' THEN 'Windscribe' WHEN service_type='v2ray' THEN 'V2Ray' ELSE 'ExpressVPN' END)) WHEN traffic_type='limited' THEN CONCAT(name,' - حجمی ',COALESCE(traffic_limit_gb,0),' گیگ') ELSE CONCAT(name,' - ',COALESCE(NULLIF(service_name,''),'OpenVPN | L2TP')) END AS full_name FROM plan_categories WHERE is_active=1 AND deleted_at IS NULL ORDER BY service_type, months, traffic_type DESC, traffic_limit_gb, display_order, sort_order, id")->fetchAll(PDO::FETCH_ASSOC);
$stmt=$pdo->query("SELECT p.*, pc.name category_name, pc.code category_code, pc.service_type category_service_type, pc.service_name category_service_name, pc.months category_months, pc.traffic_type category_traffic_type, pc.traffic_limit_gb category_traffic_limit_gb FROM plans p INNER JOIN plan_categories pc ON pc.id=p.category_id WHERE p.is_active=1 AND p.deleted_at IS NULL AND pc.is_active=1 AND pc.deleted_at IS NULL ORDER BY pc.service_type, pc.months, pc.traffic_type DESC, pc.traffic_limit_gb, p.display_order, p.id LIMIT 500");
$plans=[];
foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $p){
    $serviceType = planNormalizeServiceType((string)($p['protocol'] ?: ($p['category_service_type'] ?? 'openvpn_l2tp')), (string)(($p['service_name'] ?? '').' '.($p['category_service_name'] ?? '').' '.($p['category_name'] ?? '').' '.($p['title'] ?? '')));
    $trafficType = $p['traffic_type'] ?: ($p['category_traffic_type'] ?? 'unlimited');
    $gb = $p['traffic_limit_gb'] ?? ($p['category_traffic_limit_gb'] ?? null);
    $serviceLabel = planServiceLabel($serviceType, (string)($p['service_name'] ?: ($p['category_service_name'] ?? '')));
    $planOut=['id'=>(int)$p['id'],'category_id'=>(int)($p['category_id']??0),'duration'=>$p['duration'],'duration_label'=>($p['category_name'] ?: getDurationLabel($p['duration'])) . ' - ' . $serviceLabel . ' - ' . ($trafficType==='limited' ? ('حجمی '.(int)$gb.' گیگ') : 'نامحدود'),'months'=>(int)($p['months']??1),'seats'=>(int)$p['seats'],'users'=>(int)$p['user_count'],'price'=>(int)$p['price'],'purchase_price'=>(int)($p['purchase_price'] ?? 0),'title'=>$p['title'],'is_active'=>(int)$p['is_active'],'tier_label'=>$p['title'],'service_type'=>$serviceType,'service_label'=>$serviceLabel,'category_service_type'=>$p['category_service_type'] ?? null,'traffic_type'=>$trafficType,'traffic_limit_gb'=>$gb,'traffic_label'=>$trafficType==='limited' ? ('حجمی '.(int)$gb.' گیگ') : 'نامحدود'];
    $plans[] = gemacc_plan_apply_unit_price_fields($planOut);
}
function gemacc_reseller_price(PDO $pdo, int $userId, int $price): array {
    try { $pdo->exec("CREATE TABLE IF NOT EXISTS resellers (user_id BIGINT NOT NULL PRIMARY KEY, discount_percent DECIMAL(5,2) NOT NULL DEFAULT 0, fixed_discount INT NOT NULL DEFAULT 0, is_active TINYINT(1) NOT NULL DEFAULT 1, notes TEXT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"); $st = $pdo->prepare("SELECT * FROM resellers WHERE user_id=? AND is_active=1 LIMIT 1"); $st->execute([$userId]); $r = $st->fetch(PDO::FETCH_ASSOC); if (!$r) return ['is_reseller'=>false, 'price'=>$price, 'discount'=>0]; $discount = (int)round($price * ((float)$r['discount_percent'] / 100)) + (int)$r['fixed_discount']; $final = max(0, $price - $discount); return ['is_reseller'=>true, 'price'=>$final, 'discount'=>$price-$final]; } catch (Throwable $e) { return ['is_reseller'=>false, 'price'=>$price, 'discount'=>0]; }
}
$userIdForPrice = (int)($_GET['user_id'] ?? $_POST['user_id'] ?? 0);
if ($userIdForPrice) { foreach ($plans as &$__p) { $base=(int)$__p['price']; $rp=gemacc_reseller_price($pdo,$userIdForPrice,$base); $__p['base_price']=$base; $__p['reseller_discount']=(int)$rp['discount']; $__p['is_reseller_price']=!empty($rp['is_reseller']); $__p['price']=(int)$rp['price']; } unset($__p); }
$groups=[];
foreach($cats as $c){ $gp=array_values(array_filter($plans, fn($p)=>(int)$p['category_id']===(int)$c['id'])); if($gp) $groups[]=['id'=>(int)$c['id'],'code'=>$c['code'],'name'=>$c['full_name'] ?: $c['name'],'base_name'=>$c['name'],'months'=>(int)$c['months'],'service_type'=>$c['service_type'] ?? 'openvpn_l2tp','service_label'=>planServiceLabel(planNormalizeServiceType((string)($c['service_type']??'openvpn_l2tp'), (string)(($c['service_name']??'').' '.($c['name']??''))), (string)($c['service_name'] ?? '')),'traffic_type'=>$c['traffic_type'],'traffic_limit_gb'=>$c['traffic_limit_gb'],'traffic_label'=>$c['traffic_type']==='limited'?('حجمی '.(int)$c['traffic_limit_gb'].' گیگ'):'نامحدود','plans'=>$gp]; }
echo json_encode(['ok'=>true,'data'=>['categories'=>$groups,'plans'=>$plans]], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
