<?php
// modules/store/store.php
require_once '../../includes/auth.php';
checkLogin();
require_once '../../config/db.php';

// ==========================================
// دروازه امن (Proxy) برای دریافت اطلاعات زنده سرور
// ==========================================
if (isset($_GET['store_ajax'])) {
    require_once '../pasarguard/pasarguard_api.php';
    header('Content-Type: application/json');
    
    $action = $_GET['store_ajax'];
    
    if ($action === 'get_user') {
        $username = trim($_GET['username'] ?? '');
        $serverId = $_GET['server_id'] ?? 1;
        
        $tokenRes = getPsgApiToken($serverId);
        if (!$tokenRes['success']) { 
            echo json_encode(['error' => 'ارتباط با سرور برقرار نشد']); 
            exit; 
        }
        
        $res = executePsgApiCall($tokenRes['server_url'], "/api/user/" . urlencode($username), "GET", null, $tokenRes['token']);
        echo json_encode($res); 
        exit;
    }
    
    if ($action === 'get_sub_links') {
        $subUrl = $_GET['sub_url'] ?? '';
        if (!empty($subUrl)) {
            $ch = curl_init($subUrl);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ["User-Agent: VPNet-Panel"]);
            $res = curl_exec($ch);
            curl_close($ch);
            
            if ($res) {
                $decoded = base64_decode(trim($res), true);
                $content = $decoded ? $decoded : $res;
                $links = array_filter(explode("\n", str_replace("\r", "", $content)));
                echo json_encode(array_values($links)); 
                exit;
            }
        }
        echo json_encode([]); 
        exit;
    }
    exit;
}

$userId = $_SESSION['user_id'];
$isAdmin = isAdmin();
$msg = '';
$error = '';
$purchasedConfigs = []; 

// ==========================================
// ارتقای اتوماتیک دیتابیس
// ==========================================
try {
    $pdo->exec("ALTER TABLE plans ADD COLUMN IF NOT EXISTS has_timer TINYINT(1) DEFAULT 0");
    $pdo->exec("ALTER TABLE plans ADD COLUMN IF NOT EXISTS timer_end DATETIME NULL");
} catch (PDOException $e) {}

try {
    $pdo->query("SELECT plan_name_en FROM plans LIMIT 1");
} catch (PDOException $e) {
    $pdo->exec("ALTER TABLE plans ADD COLUMN plan_name_en VARCHAR(255) DEFAULT '' AFTER plan_name");
}

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `plan_discounts` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `plan_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
        `volume` int(11) NOT NULL,
        `discount_percent` int(11) NOT NULL DEFAULT 0,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;");
} catch(PDOException $e) {}

// ارتقای دیتابیس تراکنش‌ها برای ثبت واحد حجم
try {
    $pdo->query("SELECT volume_unit FROM transactions LIMIT 1");
} catch (PDOException $e) {
    $pdo->exec("ALTER TABLE transactions ADD COLUMN volume_unit VARCHAR(5) DEFAULT 'GB' AFTER volume");
}

// ==========================================
// دریافت اطلاعات مشتریان، بانک‌ها و آمار کاربر
// ==========================================
$stmtBanks = $pdo->prepare("SELECT id, bank_name FROM banks WHERE user_id = ?");
$stmtBanks->execute([$userId]);
$myBanks = $stmtBanks->fetchAll();

$stmtCustomers = $pdo->prepare("SELECT DISTINCT customer_name FROM transactions WHERE user_id = ? AND customer_name != '' AND customer_name != '-'");
$stmtCustomers->execute([$userId]);
$myCustomers = $stmtCustomers->fetchAll(PDO::FETCH_COLUMN);

$stmtTotalPurchased = $pdo->prepare("SELECT COUNT(*) FROM inventory WHERE operator_id = ? AND status = 'sold'");
$stmtTotalPurchased->execute([$userId]);
$totalActiveSubs = $stmtTotalPurchased->fetchColumn() ?: 0;

// ==========================================
// پردازش عملیات خرید
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'buy_config') {
    $planName = trim($_POST['plan_name']);
    $volume = (float)$_POST['volume'];
    $volumeUnit = $_POST['volume_unit'] ?? 'GB';
    $quantity = isset($_POST['quantity']) ? max(1, (int)$_POST['quantity']) : 1;
    
    $customerName = !empty($_POST['customer_name']) ? trim($_POST['customer_name']) : '-';
    $customPricePerItem = !empty($_POST['custom_sale_price']) ? (int)str_replace(',', '', $_POST['custom_sale_price']) : 0;
    $bankId = !empty($_POST['bank_id']) ? (int)$_POST['bank_id'] : null;

    if (!$planName || $volume <= 0 || $quantity <= 0) {
        $error = "درخواست نامعتبر است.";
    } else {
        $pdo->beginTransaction();
        try {
            $stmtUser = $pdo->prepare("SELECT wallet_balance FROM users WHERE id = ? FOR UPDATE");
            $stmtUser->execute([$userId]);
            $currentBalance = (int)$stmtUser->fetch()['wallet_balance'];

            $stmtPlan = $pdo->prepare("
                SELECT p.*, up.custom_cost_price, up.custom_retail_price, 
                COALESCE(up.allow_discount, 0) as allow_discount,
                COALESCE(up.allow_festival, 0) as allow_festival,
                COALESCE(pd.discount_percent, 0) as active_discount_percent
                FROM plans p 
                LEFT JOIN user_prices up ON p.plan_name COLLATE utf8mb4_general_ci = up.plan_name COLLATE utf8mb4_general_ci AND up.user_id = ? 
                LEFT JOIN plan_discounts pd ON p.plan_name COLLATE utf8mb4_general_ci = pd.plan_name COLLATE utf8mb4_general_ci AND pd.volume = ?
                WHERE p.plan_name COLLATE utf8mb4_general_ci = ? LIMIT 1
            ");
            $stmtPlan->execute([$userId, (int)$volume, $planName]);
            $planDetails = $stmtPlan->fetch();

            if (!$planDetails) throw new Exception("اطلاعات قیمت‌گذاری این طرح یافت نشد.");

            if (!empty($planDetails['custom_cost_price'])) {
                if (!$planDetails['allow_discount']) $planDetails['active_discount_percent'] = 0;
                if (!$planDetails['allow_festival']) {
                    $planDetails['has_timer'] = 0;
                    $planDetails['timer_end'] = null;
                }
            }

            if ($planDetails['has_timer'] && !empty($planDetails['timer_end'])) {
                if (time() > strtotime($planDetails['timer_end'])) {
                    throw new Exception("زمان فروش این طرح جشنواره‌ای به پایان رسیده است.");
                }
            }

            $stmtInv = $pdo->prepare("SELECT id, config_link, account_username FROM inventory WHERE plan_name COLLATE utf8mb4_general_ci = ? AND volume = ? AND COALESCE(volume_unit, 'GB') = ? AND status = 'available' ORDER BY id ASC LIMIT " . $quantity . " FOR UPDATE");
            $stmtInv->execute([$planName, $volume, $volumeUnit]);
            $configItems = $stmtInv->fetchAll();

            if (count($configItems) < $quantity) {
                throw new Exception("موجودی این محصول در انبار کافی نیست! (موجود: " . count($configItems) . " عدد)");
            }

            $activeCostPrice = !empty($planDetails['custom_cost_price']) ? $planDetails['custom_cost_price'] : $planDetails['cost_price'];
            $activeRetailPrice = !empty($planDetails['custom_retail_price']) ? $planDetails['custom_retail_price'] : $planDetails['retail_price'];

            $volumeForPrice = ($volumeUnit === 'MB') ? ($volume / 1024) : $volume;

            $baseCostPricePerItem = $volumeForPrice * (int)$activeCostPrice; 
            $adminCostTotalPerItem = $volumeForPrice * (int)$planDetails['admin_cost_price']; 
            
            $discountPerItem = ($baseCostPricePerItem * (int)$planDetails['active_discount_percent']) / 100;
            $finalPriceToDeductPerItem = $baseCostPricePerItem - $discountPerItem; 
            
            $defaultRetailTotalPerItem = $volumeForPrice * (int)$activeRetailPrice;
            $actualSalePricePerItem = ($customPricePerItem > 0) ? $customPricePerItem : $defaultRetailTotalPerItem; 
            
            $totalPriceToDeduct = $finalPriceToDeductPerItem * $quantity;
            $adminProfitPerItem = $finalPriceToDeductPerItem - $adminCostTotalPerItem; 
            $operatorProfitPerItem = $actualSalePricePerItem - $finalPriceToDeductPerItem; 

            if ($currentBalance < $totalPriceToDeduct) {
                throw new Exception("موجودی کیف پول شما برای خرید $quantity عدد کافی نیست.");
            }

            $pdo->prepare("UPDATE users SET wallet_balance = wallet_balance - ? WHERE id = ?")->execute([$totalPriceToDeduct, $userId]);
            
            require_once '../../includes/functions.php';
            $todayShamsi = getTodayShamsi(); 
            $stmtUpdateInv = $pdo->prepare("UPDATE inventory SET status = 'sold', operator_id = ?, sold_at = NOW() WHERE id = ?");
            $stmtTx = $pdo->prepare("INSERT INTO transactions (user_id, plan, volume, volume_unit, customer_name, paid_amount, profit, admin_profit, date_shamsi, account_username, type, bank_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'new', ?)");

            foreach ($configItems as $item) {
                $stmtUpdateInv->execute([$userId, $item['id']]);
                $stmtTx->execute([$userId, $planName, $volume, $volumeUnit, $customerName, $actualSalePricePerItem, $operatorProfitPerItem, $adminProfitPerItem, $todayShamsi, $item['account_username'], $bankId]);
                $purchasedConfigs[] = $item;
            }

            $pdo->commit();
            $msg = "خرید $quantity عدد اکانت با موفقیت انجام شد. " . number_format($totalPriceToDeduct) . " تومان از حساب شما کسر گردید.";
        } catch (Exception $e) {
            $pdo->rollBack();
            $error = $e->getMessage();
        }
    }
}

// ==========================================
// دریافت اطلاعات برای نمایش فروشگاه
// ==========================================
$stmtBalance = $pdo->prepare("SELECT wallet_balance FROM users WHERE id = ?");
$stmtBalance->execute([$userId]);
$walletBalance = $stmtBalance->fetchColumn() ?: 0;

$productsSql = "
    SELECT 
        inv.plan_name, 
        inv.volume, 
        inv.volume_unit,
        inv.available_count,
        up.custom_cost_price as has_custom_price,
        COALESCE(up.custom_cost_price, p.cost_price) as cost_price,
        COALESCE(up.custom_retail_price, p.retail_price) as retail_price,
        COALESCE(pd.discount_percent, 0) as discount_percent, 
        p.color_code,
        p.has_timer,
        p.timer_end,
        p.plan_name_en,
        COALESCE(up.allow_discount, 0) as allow_discount,
        COALESCE(up.allow_festival, 0) as allow_festival
    FROM (
        SELECT plan_name, volume, COALESCE(volume_unit, 'GB') as volume_unit, SUM(CASE WHEN status = 'available' THEN 1 ELSE 0 END) as available_count
        FROM inventory
        GROUP BY plan_name, volume, COALESCE(volume_unit, 'GB')
    ) inv
    JOIN plans p ON inv.plan_name COLLATE utf8mb4_general_ci = p.plan_name COLLATE utf8mb4_general_ci
    LEFT JOIN user_prices up ON inv.plan_name COLLATE utf8mb4_general_ci = up.plan_name COLLATE utf8mb4_general_ci AND up.user_id = :user_id
    LEFT JOIN plan_discounts pd ON inv.plan_name COLLATE utf8mb4_general_ci = pd.plan_name COLLATE utf8mb4_general_ci AND inv.volume = pd.volume
    WHERE p.is_active = 1 OR p.is_active IS NULL
    ORDER BY cost_price ASC, inv.volume ASC
";

$rawProducts = [];
try {
    $stmtProd = $pdo->prepare($productsSql);
    $stmtProd->execute([':user_id' => $userId]);
    $rawProducts = $stmtProd->fetchAll();
} catch (PDOException $e) {
    die("<div style='text-align:center; padding:20px;'><b>خطای دیتابیس در بارگذاری فروشگاه</b></div>");
}

$stmtVip = $pdo->prepare("SELECT allow_discount, allow_festival FROM user_prices WHERE user_id = ?");
$stmtVip->execute([$userId]);
$vipRows = $stmtVip->fetchAll(PDO::FETCH_ASSOC);
$isVipAgent = count($vipRows) > 0;
$vipAllowDiscount = false;
$vipAllowFestival = false;

if ($isVipAgent) {
    foreach($vipRows as $r) {
        if ($r['allow_discount'] == 1) $vipAllowDiscount = true;
        if ($r['allow_festival'] == 1) $vipAllowFestival = true;
    }
}

$groupedProducts = [];
foreach($rawProducts as $p) {
    if ($isVipAgent) {
        if (!$vipAllowDiscount) $p['discount_percent'] = 0;
        if (!$vipAllowFestival && !empty($p['has_timer'])) continue; 
    }

    if (!empty($p['has_timer']) && !empty($p['timer_end']) && time() > strtotime($p['timer_end'])) {
        continue; 
    }

    if (!isset($groupedProducts[$p['plan_name']]['has_timer'])) {
        $groupedProducts[$p['plan_name']]['has_timer'] = empty($p['has_timer']) ? 0 : 1;
        $groupedProducts[$p['plan_name']]['timer_end'] = $p['timer_end'];
    } elseif (!empty($p['has_timer'])) {
        $groupedProducts[$p['plan_name']]['has_timer'] = 1;
        $groupedProducts[$p['plan_name']]['timer_end'] = $p['timer_end'];
    }

    $groupedProducts[$p['plan_name']]['color'] = $p['color_code'];
    $groupedProducts[$p['plan_name']]['items'][] = $p;
}

require_once '../../includes/header.php';
?>

<datalist id="customerNamesList">
    <?php foreach($myCustomers as $cName): ?>
        <option value="<?php echo htmlspecialchars($cName); ?>">
    <?php endforeach; ?>
</datalist>

<div class="px-2 md:px-0">
    <?php if($msg): ?><div class="bg-emerald-50 border border-emerald-200 text-emerald-800 px-5 py-4 rounded-2xl mb-6 font-bold shadow-sm flex items-center gap-3"><span class="text-xl">✅</span> <?php echo $msg; ?></div><?php endif; ?>
    <?php if($error): ?><div class="bg-rose-50 border border-rose-200 text-rose-700 px-5 py-4 rounded-2xl mb-6 font-bold shadow-sm flex items-center gap-3"><span class="text-xl">❌</span> <?php echo $error; ?></div><?php endif; ?>

    <?php 
    // 1. نمایش باکس موفقیت (در صورت وجود خرید)
    if (!empty($purchasedConfigs)) {
        require_once 'widgets/success_box.php';
    }

    // 2. نمایش هدر و گرید محصولات
    if (empty($purchasedConfigs)) {
        require_once 'widgets/product_grid.php';
    }

    // 3. اسکریپت‌ها و مودال‌ها
    require_once 'widgets/scripts.php';
    ?>
</div>

<?php require_once '../../includes/footer.php'; ?>