<?php
session_start();
require_once '../../vippanneladmin56329803/config.php';

if (!isset($_SESSION['agent_id'])) {
    header("Location: ../agent.php");
    exit;
}

$agent_id = $_SESSION['agent_id'];
$stmt = $pdo->prepare("SELECT * FROM agents WHERE id = ?");
$stmt->execute([$agent_id]);
$agent = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$agent) {
    session_destroy();
    header("Location: ../agent.php");
    exit;
}

$message = '';
$error = '';

// ==================== تابع محاسبه قیمت نهایی با احتساب تخفیف نماینده ====================
function calculateFinalPrice($plan_price, $plan_discount_price, $agent_discount) {
    // اول قیمت پایه رو مشخص کن (با تخفیف پلن یا بدون تخفیف)
    $base_price = $plan_discount_price ? $plan_discount_price : $plan_price;
    // سپس تخفیف نماینده اعمال میشه
    $final_price = $base_price * (1 - $agent_discount / 100);
    return round($final_price);
}

// ==================== دریافت دسته‌بندی‌های فعال ====================
$categories = $pdo->query("SELECT * FROM other_categories WHERE status = 1 ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);

// دریافت پلن‌های یک دسته‌بندی خاص
$selected_category = isset($_GET['category']) ? intval($_GET['category']) : 0;
$plans = [];
if ($selected_category) {
    $stmt = $pdo->prepare("
        SELECT p.*, 
               (SELECT COUNT(*) FROM other_stocks WHERE plan_id = p.id AND status = 1) as stock_count
        FROM other_plans p 
        WHERE p.category_id = ? AND p.status = 1 
        ORDER BY p.id DESC
    ");
    $stmt->execute([$selected_category]);
    $plans = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// ==================== دریافت تاریخچه خرید نماینده ====================
$my_purchases = $pdo->prepare("
    SELECT p.*, pl.name as plan_name, c.name as category_name
    FROM other_purchases p 
    JOIN other_stocks s ON p.stock_id = s.id
    JOIN other_plans pl ON s.plan_id = pl.id
    JOIN other_categories c ON pl.category_id = c.id
    WHERE p.agent_id = ?
    ORDER BY p.purchased_at DESC
");
$my_purchases->execute([$agent_id]);
$my_purchases = $my_purchases->fetchAll(PDO::FETCH_ASSOC);

// ==================== پردازش خرید ====================
if (isset($_POST['buy_plan'])) {
    $plan_id = intval($_POST['plan_id']);
    
    // دریافت اطلاعات پلن
    $stmt = $pdo->prepare("
        SELECT p.*, c.fields_config, c.name as category_name 
        FROM other_plans p 
        JOIN other_categories c ON p.category_id = c.id 
        WHERE p.id = ? AND p.status = 1
    ");
    $stmt->execute([$plan_id]);
    $plan = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$plan) {
        $error = "پلن مورد نظر یافت نشد";
    } else {
        // بررسی موجودی
        $stmt = $pdo->prepare("SELECT * FROM other_stocks WHERE plan_id = ? AND status = 1 LIMIT 1");
        $stmt->execute([$plan_id]);
        $stock = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$stock) {
            $error = "متاسفانه این محصول در حال حاضر موجود نمی‌باشد";
        } else {
            // محاسبه قیمت نهایی
            $final_price = calculateFinalPrice($plan['price'], $plan['discount_price'], $agent['discount']);
            
            // بررسی موجودی نماینده
            if ($agent['balance'] < $final_price) {
                $error = "موجودی شما کافی نیست. موجودی فعلی: " . number_format($agent['balance']) . " تومان - نیاز: " . number_format($final_price) . " تومان";
            } else {
                // انجام خرید
                try {
                    $pdo->beginTransaction();
                    
                    // کاهش موجودی نماینده
                    $new_balance = $agent['balance'] - $final_price;
                    $stmt = $pdo->prepare("UPDATE agents SET balance = ? WHERE id = ?");
                    $stmt->execute([$new_balance, $agent_id]);
                    
                    // ثبت خرید
                    $fields_data = json_decode($stock['fields_data'], true);
                    $stmt = $pdo->prepare("
                        INSERT INTO other_purchases (agent_id, stock_id, plan_name, price, fields_data) 
                        VALUES (?, ?, ?, ?, ?)
                    ");
                    $stmt->execute([$agent_id, $stock['id'], $plan['name'], $final_price, json_encode($fields_data)]);
                    
                    // حذف موجودی (غیرفعال کردن)
                    $stmt = $pdo->prepare("UPDATE other_stocks SET status = 0, sold_at = NOW(), sold_to_agent_id = ? WHERE id = ?");
                    $stmt->execute([$agent_id, $stock['id']]);
                    
                    $pdo->commit();
                    
                    $message = "خرید با موفقیت انجام شد! اطلاعات محصول برای شما ارسال گردید.";
                    
                    // رفرش صفحه برای بروزرسانی
                    header("Location: other_products_agent.php?category=" . $selected_category . "&success=1");
                    exit;
                    
                } catch (Exception $e) {
                    $pdo->rollBack();
                    $error = "خطا در انجام خرید: " . $e->getMessage();
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html dir="rtl" lang="fa">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>محصولات دیگر | نمایندگی</title>
    <link rel="stylesheet" href="../style.css">
    <style>
        :root {
            --accent: #8b5cf6;
            --accent-2: #6366f1;
            --emerald: #10b981;
            --rose: #ef4444;
            --amber: #f59e0b;
            --glass-bg: rgba(255,255,255,0.28);
            --glass-inset: rgba(255,255,255,0.18);
            --glass-border: rgba(255,255,255,0.35);
            --glass-border-mid: rgba(255,255,255,0.45);
            --glass-border-hi: rgba(255,255,255,0.65);
            --glass-top-shine: rgba(255,255,255,0.45);
            --text-1: #1f2937;
            --text-2: #4b5563;
            --text-3: #6b7280;
            --shadow-sm: 0 2px 8px rgba(0,0,0,0.04), 0 1px 2px rgba(0,0,0,0.06);
            --shadow-md: 0 8px 24px rgba(0,0,0,0.08), 0 2px 4px rgba(0,0,0,0.04);
            --blur: blur(12px);
            --blur-sm: blur(6px);
            --t-smooth: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
            --r-sm: 8px;
            --r-md: 12px;
            --r-lg: 16px;
            --r-xl: 24px;
            --r-pill: 999px;
        }
        
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { background: linear-gradient(145deg, #eef2ff 0%, #e0e7ff 100%); min-height: 100vh; font-family: 'Vazir', system-ui, sans-serif; }
        .page-wrap { max-width: 1440px; margin: 0 auto; padding: 24px; position: relative; z-index: 1; }
        
        .admin-header { display: flex; align-items: center; justify-content: space-between; background: var(--glass-bg); backdrop-filter: var(--blur); border: 1px solid var(--glass-border-mid); border-radius: var(--r-xl); padding: 16px 28px; margin-bottom: 28px; box-shadow: inset 0 1.5px 0 var(--glass-top-shine), var(--shadow-sm); flex-wrap: wrap; gap: 12px; }
        .brand { display: flex; align-items: center; gap: 12px; }
        .brand-logo { width: 44px; height: 44px; border-radius: 14px; object-fit: cover; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
        .brand-name { font-size: 20px; font-weight: 800; background: linear-gradient(135deg, #4f46e5, #7c3aed); -webkit-background-clip: text; background-clip: text; color: transparent; }
        .admin-info { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
        .admin-welcome { font-size: 13px; color: var(--text-2); background: var(--glass-inset); padding: 8px 16px; border-radius: var(--r-pill); border: 1px solid var(--glass-border); }
        .balance-badge { background: linear-gradient(135deg, var(--emerald), #059669); color: white; padding: 8px 20px; border-radius: var(--r-pill); font-weight: 700; font-size: 14px; }
        .discount-badge { background: linear-gradient(135deg, var(--accent), var(--accent-2)); color: white; padding: 8px 20px; border-radius: var(--r-pill); font-weight: 700; font-size: 14px; }
        .logout-btn { display: inline-flex; align-items: center; gap: 6px; padding: 8px 16px; background: rgba(239,68,68,0.12); border: 1px solid rgba(239,68,68,0.25); border-radius: var(--r-pill); color: #dc2626; text-decoration: none; font-size: 12px; font-weight: 600; transition: var(--t-smooth); }
        .logout-btn:hover { background: rgba(239,68,68,0.22); transform: translateY(-1px); }
        .back-btn { background: rgba(59,130,246,0.12); color: #2563eb; border-color: rgba(59,130,246,0.25); }
        
        .tabs { display: flex; gap: 12px; margin-bottom: 28px; background: var(--glass-bg); backdrop-filter: var(--blur); padding: 8px; border-radius: var(--r-pill); border: 1px solid var(--glass-border-mid); flex-wrap: wrap; }
        .tab-btn { padding: 10px 28px; border: none; background: transparent; border-radius: var(--r-pill); font-size: 14px; font-weight: 600; cursor: pointer; transition: var(--t-smooth); color: var(--text-2); text-decoration: none; display: inline-block; }
        .tab-btn.active { background: linear-gradient(135deg, var(--accent), var(--accent-2)); color: white; box-shadow: 0 2px 8px rgba(139,92,246,0.3); }
        
        .categories-strip { display: flex; gap: 12px; margin-bottom: 28px; background: var(--glass-bg); backdrop-filter: var(--blur); padding: 12px 20px; border-radius: var(--r-pill); border: 1px solid var(--glass-border-mid); flex-wrap: wrap; justify-content: center; }
        .category-btn { padding: 10px 24px; border-radius: var(--r-pill); text-decoration: none; font-size: 14px; font-weight: 600; transition: var(--t-smooth); background: var(--glass-inset); color: var(--text-2); border: 1px solid var(--glass-border); }
        .category-btn.active { background: linear-gradient(135deg, var(--accent), var(--accent-2)); color: white; border-color: transparent; box-shadow: 0 2px 8px rgba(139,92,246,0.3); }
        .category-btn:hover:not(.active) { transform: translateY(-2px); background: rgba(255,255,255,0.25); }
        
        .products-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(360px, 1fr)); gap: 24px; margin-bottom: 32px; }
        .product-card { background: var(--glass-bg); backdrop-filter: var(--blur); border: 1px solid var(--glass-border-mid); border-radius: var(--r-xl); overflow: hidden; transition: var(--t-smooth); box-shadow: inset 0 1.5px 0 var(--glass-top-shine), var(--shadow-sm); }
        .product-card:hover { transform: translateY(-6px); border-color: var(--glass-border-hi); box-shadow: var(--shadow-md); }
        .product-header { padding: 20px 24px; background: linear-gradient(135deg, rgba(139,92,246,0.15), rgba(99,102,241,0.08)); border-bottom: 1px solid var(--glass-border); }
        .product-name { font-size: 20px; font-weight: 800; color: var(--text-1); margin-bottom: 8px; }
        .product-desc { font-size: 12px; color: var(--text-3); line-height: 1.6; }
        .product-desc span { display: inline-block; background: rgba(139,92,246,0.12); padding: 2px 8px; border-radius: var(--r-pill); margin: 2px 4px; font-size: 11px; }
        .product-body { padding: 20px 24px; }
        .price-section { margin-bottom: 16px; padding-bottom: 16px; border-bottom: 1px solid var(--glass-border); }
        .original-price { font-size: 14px; color: var(--text-3); text-decoration: line-through; }
        .final-price { font-size: 28px; font-weight: 800; color: var(--accent); }
        .final-price small { font-size: 12px; font-weight: 400; color: var(--text-3); }
        .discount-tag { display: inline-block; background: linear-gradient(135deg, var(--emerald), #059669); color: white; padding: 2px 10px; border-radius: var(--r-pill); font-size: 11px; font-weight: 600; margin-right: 10px; }
        .agent-discount-tag { display: inline-block; background: linear-gradient(135deg, var(--accent), var(--accent-2)); color: white; padding: 2px 10px; border-radius: var(--r-pill); font-size: 11px; font-weight: 600; margin-right: 10px; }
        .price-breakdown { font-size: 11px; color: var(--text-3); margin-top: 8px; padding-top: 8px; border-top: 1px dashed var(--glass-border); }
        .stock-info { font-size: 12px; color: var(--text-3); margin-bottom: 16px; display: flex; align-items: center; gap: 8px; }
        .stock-badge { display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: var(--emerald); }
        .stock-badge.low { background: var(--amber); }
        .stock-badge.out { background: var(--rose); }
        .buy-btn { width: 100%; padding: 14px; background: linear-gradient(135deg, var(--accent), var(--accent-2)); border: none; border-radius: var(--r-pill); color: white; font-size: 15px; font-weight: 700; cursor: pointer; transition: var(--t-smooth); box-shadow: 0 4px 14px rgba(139,92,246,0.3); display: flex; align-items: center; justify-content: center; gap: 8px; }
        .buy-btn:hover:not(:disabled) { transform: translateY(-2px); box-shadow: 0 8px 24px rgba(139,92,246,0.4); }
        .buy-btn:disabled { opacity: 0.5; cursor: not-allowed; background: var(--text-3); box-shadow: none; }
        
        .alert { display: flex; align-items: center; gap: 12px; padding: 14px 20px; border-radius: var(--r-md); margin-bottom: 20px; font-size: 13px; font-weight: 500; }
        .alert-success { background: rgba(16,185,129,0.12); border: 1px solid rgba(16,185,129,0.3); color: #065f46; }
        .alert-error { background: rgba(239,68,68,0.12); border: 1px solid rgba(239,68,68,0.3); color: #7f1d1d; }
        .alert-info { background: rgba(59,130,246,0.12); border: 1px solid rgba(59,130,246,0.25); color: #1e40af; }
        
        .data-table { width: 100%; background: var(--glass-bg); backdrop-filter: var(--blur); border: 1px solid var(--glass-border-mid); border-radius: var(--r-xl); overflow-x: auto; margin-bottom: 20px; }
        .data-table table { width: 100%; border-collapse: collapse; min-width: 600px; }
        .data-table th, .data-table td { padding: 14px 12px; text-align: center; border-bottom: 1px solid var(--glass-border); font-size: 13px; }
        .data-table th { background: rgba(255,255,255,0.08); color: var(--text-2); font-weight: 600; }
        .data-table tr:hover { background: rgba(255,255,255,0.08); }
        
        .view-btn { display: inline-flex; align-items: center; gap: 4px; padding: 6px 12px; background: rgba(59,130,246,0.15); border: 1px solid rgba(59,130,246,0.3); border-radius: var(--r-pill); color: #2563eb; text-decoration: none; font-size: 11px; font-weight: 600; transition: var(--t-smooth); cursor: pointer; }
        .view-btn:hover { transform: translateY(-1px); }
        
        .badge { display: inline-block; padding: 4px 12px; border-radius: var(--r-pill); font-size: 11px; font-weight: 600; }
        .badge-success { background: rgba(16,185,129,0.12); color: #059669; border: 1px solid rgba(16,185,129,0.3); }
        
        .empty-state { text-align: center; padding: 60px 20px; background: var(--glass-bg); backdrop-filter: var(--blur); border-radius: var(--r-xl); border: 1px solid var(--glass-border-mid); }
        .empty-state svg { margin-bottom: 16px; opacity: 0.5; }
        .empty-state h3 { color: var(--text-2); margin-bottom: 8px; }
        .empty-state p { color: var(--text-3); font-size: 13px; }
        
        .tab-content { display: none; }
        .tab-content.active { display: block; }
        
        .modal { display: none; position: fixed; inset: 0; background: rgba(80,60,160,0.22); backdrop-filter: blur(22px); z-index: 1000; justify-content: center; align-items: center; padding: 20px; }
        .modal.active { display: flex; }
        .modal-card { background: rgba(255,255,255,0.92); backdrop-filter: blur(20px); border: 1px solid var(--glass-border-hi); border-radius: var(--r-xl); padding: 28px; max-width: 520px; width: 100%; max-height: 85vh; overflow-y: auto; }
        .info-row { display: flex; padding: 10px 0; border-bottom: 1px solid var(--glass-border); }
        .info-label { width: 100px; font-weight: 600; color: var(--text-2); font-size: 12px; }
        .info-value { flex: 1; color: var(--text-1); font-size: 13px; word-break: break-word; }
        .close-modal-btn { width: 100%; padding: 12px; background: var(--glass-inset); border: 1px solid var(--glass-border); border-radius: var(--r-pill); cursor: pointer; margin-top: 20px; font-weight: 600; transition: var(--t-smooth); }
        .close-modal-btn:hover { background: rgba(239,68,68,0.12); border-color: rgba(239,68,68,0.3); color: #dc2626; }
        
        @media (max-width: 768px) { .page-wrap { padding: 14px; } .admin-header { flex-direction: column; text-align: center; } .products-grid { grid-template-columns: 1fr; } .categories-strip { border-radius: var(--r-lg); } .tabs { flex-direction: column; border-radius: var(--r-lg); } }
    </style>
</head>
<body>
<div class="page-wrap">
    
    <div class="admin-header">
        <div class="brand">
            <img src="../../vippanneladmin56329803/picture/rahgozar.png" alt="لوگو" class="brand-logo">
            <span class="brand-name">محصولات دیگر</span>
        </div>
        <div class="admin-info">
            <span class="admin-welcome">خوش آمدید، <strong><?= htmlspecialchars($agent['name']) ?></strong></span>
            <div class="balance-badge">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" style="display: inline; margin-left: 6px;"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>
                <?= number_format($agent['balance']) ?> تومان
            </div>
            <div class="discount-badge">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" style="display: inline; margin-left: 6px;"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>
                تخفیف دائمی <?= $agent['discount'] ?>%
            </div>
            <a href="../agent.php" class="logout-btn back-btn">بازگشت</a>
            <a href="../agent.php?logout=1" class="logout-btn">خروج</a>
        </div>
    </div>
    
    <div class="tabs">
        <a href="other_products_agent.php" class="tab-btn <?= !isset($_GET['tab']) || $_GET['tab'] == 'shop' ? 'active' : '' ?>">فروشگاه</a>
        <a href="?tab=purchases" class="tab-btn <?= isset($_GET['tab']) && $_GET['tab'] == 'purchases' ? 'active' : '' ?>">تاریخچه خرید من</a>
    </div>
    
    <?php if ($message): ?>
        <div class="alert alert-success"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="alert alert-error"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    <?php if (isset($_GET['success'])): ?>
        <div class="alert alert-success">خرید شما با موفقیت انجام شد! اطلاعات محصول برای شما ارسال گردید.</div>
    <?php endif; ?>
    
    <!-- ==================== تب فروشگاه ==================== -->
    <div id="shopTab" class="tab-content <?= !isset($_GET['tab']) || $_GET['tab'] == 'shop' ? 'active' : '' ?>">
        
        <!-- دسته‌بندی‌ها -->
        <div class="categories-strip">
            <?php foreach ($categories as $cat): ?>
                <a href="?category=<?= $cat['id'] ?>" class="category-btn <?= $selected_category == $cat['id'] ? 'active' : '' ?>">
                    <?= htmlspecialchars($cat['name']) ?>
                </a>
            <?php endforeach; ?>
        </div>
        
        <!-- نمایش محصولات -->
        <?php if ($selected_category && count($plans) > 0): ?>
            <div class="products-grid">
                <?php foreach ($plans as $plan): 
                    $stock_count = $plan['stock_count'];
                    $has_stock = $stock_count > 0;
                    
                    // محاسبات قیمت
                    $base_price = $plan['price'];
                    $has_plan_discount = $plan['discount_price'] && $plan['discount_price'] > 0;
                    $price_after_plan_discount = $has_plan_discount ? $plan['discount_price'] : $plan['price'];
                    $final_price = calculateFinalPrice($plan['price'], $plan['discount_price'], $agent['discount']);
                    
                    $plan_discount_percent = $has_plan_discount ? round((1 - $plan['discount_price'] / $plan['price']) * 100) : 0;
                    $agent_discount_amount = $price_after_plan_discount * ($agent['discount'] / 100);
                    $total_discount_percent = $has_plan_discount ? $plan_discount_percent + $agent['discount'] - ($plan_discount_percent * $agent['discount'] / 100) : $agent['discount'];
                    
                    // استخراج توضیحات از پرانتزها
                    $desc_items = [];
                    if ($plan['descriptions']) {
                        preg_match_all('/\(([^)]+)\)/', $plan['descriptions'], $matches);
                        $desc_items = $matches[1];
                    }
                ?>
                    <div class="product-card">
                        <div class="product-header">
                            <div class="product-name"><?= htmlspecialchars($plan['name']) ?></div>
                            <?php if (count($desc_items) > 0): ?>
                                <div class="product-desc">
                                    <?php foreach ($desc_items as $item): ?>
                                        <span><?= htmlspecialchars($item) ?></span>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="product-body">
                            <div class="price-section">
                                <?php if ($has_plan_discount): ?>
                                    <div class="original-price"><?= number_format($plan['price']) ?> تومان</div>
                                <?php endif; ?>
                                <span class="final-price"><?= number_format($final_price) ?> <small>تومان</small></span>
                                
                                <?php if ($has_plan_discount): ?>
                                    <span class="discount-tag"><?= $plan_discount_percent ?>% تخفیف پلن</span>
                                <?php endif; ?>
                                <?php if ($agent['discount'] > 0): ?>
                                    <span class="agent-discount-tag">+<?= $agent['discount'] ?>% تخفیف نماینده</span>
                                <?php endif; ?>
                                
                                <?php if ($has_plan_discount || $agent['discount'] > 0): ?>
                                    <div class="price-breakdown">
                                        <?php if ($has_plan_discount): ?>
                                            قیمت اصلی: <?= number_format($plan['price']) ?> تومان<br>
                                            قیمت با تخفیف پلن: <?= number_format($price_after_plan_discount) ?> تومان (<?= $plan_discount_percent ?>% تخفیف)<br>
                                        <?php endif; ?>
                                        <?php if ($agent['discount'] > 0): ?>
                                            اعمال تخفیف نماینده (<?= $agent['discount'] ?>%): 
                                            کاهش <?= number_format(round($agent_discount_amount)) ?> تومان<br>
                                        <?php endif; ?>
                                        <strong>شما پرداخت می‌کنید: <?= number_format($final_price) ?> تومان</strong>
                                        <br><small style="color: var(--emerald);">جمع تخفیف: <?= round($total_discount_percent) ?>%</small>
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <div class="stock-info">
                                <?php if ($has_stock): ?>
                                    <span class="stock-badge <?= $stock_count <= 3 ? 'low' : '' ?>"></span>
                                    <span>موجودی: <?= $stock_count ?> عدد</span>
                                    <?php if ($stock_count <= 3): ?>
                                        <span style="color: var(--amber); font-size: 11px;">(فقط <?= $stock_count ?> عدد باقی مانده)</span>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span class="stock-badge out"></span>
                                    <span style="color: var(--rose);">ناموجود</span>
                                <?php endif; ?>
                            </div>
                            
                            <form method="POST">
                                <input type="hidden" name="plan_id" value="<?= $plan['id'] ?>">
                                <button type="submit" name="buy_plan" class="buy-btn" <?= !$has_stock ? 'disabled' : '' ?>>
                                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"/><line x1="3" y1="6" x2="21" y2="6"/></svg>
                                    <?= $has_stock ? 'خرید محصول' : 'ناموجود' ?>
                                </button>
                            </form>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php elseif ($selected_category && count($plans) == 0): ?>
            <div class="empty-state">
                <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="var(--text-3)" stroke-width="1.5"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
                <h3>هیچ محصولی یافت نشد</h3>
                <p>در حال حاظر محصولی برای این دسته‌بندی وجود ندارد.</p>
            </div>
        <?php elseif (!$selected_category && count($categories) > 0): ?>
            <div class="empty-state">
                <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="var(--text-3)" stroke-width="1.5"><path d="M20 7h-4.18A3 3 0 0 0 16 5.18V4a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2z"/><circle cx="10" cy="14" r="2"/></svg>
                <h3>یک دسته‌بندی انتخاب کنید</h3>
                <p>از نوار بالا یکی از دسته‌بندی‌های محصولات را انتخاب کنید.</p>
            </div>
        <?php elseif (count($categories) == 0): ?>
            <div class="empty-state">
                <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="var(--text-3)" stroke-width="1.5"><path d="M20 7h-4.18A3 3 0 0 0 16 5.18V4a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2z"/><circle cx="10" cy="14" r="2"/></svg>
                <h3>هیچ دسته‌بندی وجود ندارد</h3>
                <p>هنوز دسته‌بندی محصولی توسط مدیریت تعریف نشده است.</p>
            </div>
        <?php endif; ?>
    </div>
    
    <!-- ==================== تب تاریخچه خرید من ==================== -->
    <div id="purchasesTab" class="tab-content <?= isset($_GET['tab']) && $_GET['tab'] == 'purchases' ? 'active' : '' ?>">
        
        <div class="data-table">
            <table>
                <thead>
                    <tr>
                        <th>شناسه</th>
                        <th>نام محصول</th>
                        <th>دسته‌بندی</th>
                        <th>مبلغ پرداختی</th>
                        <th>زمان خرید</th>
                        <th>جزئیات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($my_purchases) > 0): ?>
                        <?php foreach ($my_purchases as $purchase): 
                            $fields_data = json_decode($purchase['fields_data'], true);
                        ?>
                            <tr>
                                <td><?= $purchase['id'] ?></td>
                                <td><strong><?= htmlspecialchars($purchase['plan_name']) ?></strong></td>
                                <td><?= htmlspecialchars($purchase['category_name']) ?></td>
                                <td><span class="badge badge-success"><?= number_format($purchase['price']) ?> تومان</span></td>
                                <td><?= date('Y/m/d H:i', strtotime($purchase['purchased_at'])) ?></td>
                                <td>
                                    <button class="view-btn" onclick='showPurchaseDetails(<?= json_encode($purchase) ?>)'>مشاهده</button>
                                 </br><small>اطلاعات محصول</small>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="6" style="text-align: center; padding: 40px;">شما هنوز هیچ خریدی انجام نداده اید</td><td style="display:none;"></td><td style="display:none;"></td><td style="display:none;"></td><td style="display:none;"></td><td style="display:none;"></td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
</div>

<script>
function showPurchaseDetails(purchase) {
    let fieldsData = [];
    try {
        fieldsData = JSON.parse(purchase.fields_data);
    } catch(e) {
        fieldsData = [];
    }
    
    let html = '<div class="modal-header"><h3>جزئیات خرید</h3></div>';
    html += '<div class="info-row"><div class="info-label">شناسه خرید:</div><div class="info-value">#' + purchase.id + '</div></div>';
    html += '<div class="info-row"><div class="info-label">نام محصول:</div><div class="info-value">' + escapeHtml(purchase.plan_name) + '</div></div>';
    html += '<div class="info-row"><div class="info-label">دسته‌بندی:</div><div class="info-value">' + escapeHtml(purchase.category_name) + '</div></div>';
    html += '<div class="info-row"><div class="info-label">مبلغ پرداختی:</div><div class="info-value">' + numberFormat(purchase.price) + ' تومان</div></div>';
    html += '<div class="info-row"><div class="info-label">زمان خرید:</div><div class="info-value">' + escapeHtml(purchase.purchased_at) + '</div></div>';
    
    if (fieldsData.length > 0) {
        html += '<div class="info-row" style="background: rgba(139,92,246,0.08); margin-top: 10px;"><div class="info-label">اطلاعات محصول:</div><div class="info-value"></div></div>';
        for (let i = 0; i < fieldsData.length; i++) {
            html += '<div class="info-row"><div class="info-label">' + escapeHtml(fieldsData[i].name) + ':</div><div class="info-value">' + escapeHtml(fieldsData[i].value) + '</div></div>';
        }
    }
    
    document.getElementById('modalContent').innerHTML = html;
    document.getElementById('productModal').classList.add('active');
}

function closeModal(event) {
    if (!event || event.target === document.getElementById('productModal')) {
        document.getElementById('productModal').classList.remove('active');
    }
}

function numberFormat(num) {
    return new Intl.NumberFormat('fa-IR').format(num);
}

function escapeHtml(str) {
    if (!str) return '';
    return str.replace(/[&<>]/g, function(m) {
        if (m === '&') return '&amp;';
        if (m === '<') return '&lt;';
        if (m === '>') return '&gt;';
        return m;
    });
}

// برای حفظ تب در هنگام رفرش
if (window.location.hash === '#purchases') {
    document.querySelector('a[href="?tab=purchases"]').click();
}
</script>

<div id="productModal" class="modal" onclick="closeModal(event)">
    <div class="modal-card" onclick="event.stopPropagation()">
        <div id="modalContent"></div>
        <button class="close-modal-btn" onclick="closeModal()">بستن</button>
    </div>
</div>

</body>
</html>