<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);



session_start();
require_once '../config.php';

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: ../admin_panel.php");
    exit;
}

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

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

// ==================== مدیریت دسته‌بندی ====================
if (isset($_POST['add_category'])) {
    $name = trim($_POST['name']);
    $description = trim($_POST['description']);
    $fields_count = intval($_POST['fields_count']);
    
    $fields_config = [];
    for ($i = 1; $i <= $fields_count; $i++) {
        $fields_config[] = [
            'name' => trim($_POST["field_name_$i"]),
            'placeholder' => trim($_POST["field_placeholder_$i"])
        ];
    }
    
    $stmt = $pdo->prepare("INSERT INTO other_categories (name, description, fields_count, fields_config, status) VALUES (?, ?, ?, ?, 1)");
    if ($stmt->execute([$name, $description, $fields_count, json_encode($fields_config)])) {
        $message = "دسته‌بندی با موفقیت اضافه شد";
    } else {
        $error = "خطا در افزودن دسته‌بندی";
    }
}

if (isset($_POST['edit_category'])) {
    $id = intval($_POST['category_id']);
    $name = trim($_POST['name']);
    $description = trim($_POST['description']);
    $fields_count = intval($_POST['fields_count']);
    $status = isset($_POST['status']) ? 1 : 0;
    
    $fields_config = [];
    for ($i = 1; $i <= $fields_count; $i++) {
        $fields_config[] = [
            'name' => trim($_POST["field_name_$i"]),
            'placeholder' => trim($_POST["field_placeholder_$i"])
        ];
    }
    
    $stmt = $pdo->prepare("UPDATE other_categories SET name = ?, description = ?, fields_count = ?, fields_config = ?, status = ? WHERE id = ?");
    if ($stmt->execute([$name, $description, $fields_count, json_encode($fields_config), $status, $id])) {
        $message = "دسته‌بندی با موفقیت ویرایش شد";
    } else {
        $error = "خطا در ویرایش دسته‌بندی";
    }
}

if (isset($_GET['delete_category'])) {
    $id = intval($_GET['delete_category']);
    $stmt = $pdo->prepare("DELETE FROM other_categories WHERE id = ?");
    if ($stmt->execute([$id])) {
        $message = "دسته‌بندی با موفقیت حذف شد";
    } else {
        $error = "خطا در حذف دسته‌بندی";
    }
}

// ==================== مدیریت پلن‌ها ====================
if (isset($_POST['add_plan'])) {
    $category_id = intval($_POST['category_id']);
    $name = trim($_POST['name']);
    $descriptions = trim($_POST['descriptions']);
    $price = floatval($_POST['price']);
    $discount_price = !empty($_POST['discount_price']) ? floatval($_POST['discount_price']) : null;
    
    $stmt = $pdo->prepare("INSERT INTO other_plans (category_id, name, descriptions, price, discount_price, status) VALUES (?, ?, ?, ?, ?, 1)");
    if ($stmt->execute([$category_id, $name, $descriptions, $price, $discount_price])) {
        $message = "پلن با موفقیت اضافه شد";
    } else {
        $error = "خطا در افزودن پلن";
    }
}

if (isset($_POST['edit_plan'])) {
    $id = intval($_POST['plan_id']);
    $category_id = intval($_POST['category_id']);
    $name = trim($_POST['name']);
    $descriptions = trim($_POST['descriptions']);
    $price = floatval($_POST['price']);
    $discount_price = !empty($_POST['discount_price']) ? floatval($_POST['discount_price']) : null;
    $status = isset($_POST['status']) ? 1 : 0;
    
    $stmt = $pdo->prepare("UPDATE other_plans SET category_id = ?, name = ?, descriptions = ?, price = ?, discount_price = ?, status = ? WHERE id = ?");
    if ($stmt->execute([$category_id, $name, $descriptions, $price, $discount_price, $status, $id])) {
        $message = "پلن با موفقیت ویرایش شد";
    } else {
        $error = "خطا در ویرایش پلن";
    }
}

if (isset($_GET['delete_plan'])) {
    $id = intval($_GET['delete_plan']);
    $stmt = $pdo->prepare("DELETE FROM other_plans WHERE id = ?");
    if ($stmt->execute([$id])) {
        $message = "پلن با موفقیت حذف شد";
    } else {
        $error = "خطا در حذف پلن";
    }
}

// ==================== مدیریت موجودی ====================
if (isset($_POST['add_stock'])) {
    $plan_id = intval($_POST['plan_id']);
    
    $stmt = $pdo->prepare("
        SELECT c.fields_config, c.fields_count, p.name as plan_name 
        FROM other_plans p 
        JOIN other_categories c ON p.category_id = c.id 
        WHERE p.id = ?
    ");
    $stmt->execute([$plan_id]);
    $plan_info = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($plan_info) {
        $fields_config = json_decode($plan_info['fields_config'], true);
        $fields_data = [];
        
        foreach ($fields_config as $index => $field) {
            $fields_data[] = [
                'name' => $field['name'],
                'value' => trim($_POST["field_$index"])
            ];
        }
        
        $stmt = $pdo->prepare("INSERT INTO other_stocks (plan_id, fields_data, status) VALUES (?, ?, 1)");
        if ($stmt->execute([$plan_id, json_encode($fields_data)])) {
            $message = "موجودی جدید با موفقیت اضافه شد";
            header("Location: other_products.php?tab=stocks&success=1");
            exit;
        } else {
            $error = "خطا در افزودن موجودی";
        }
    } else {
        $error = "پلن مورد نظر یافت نشد";
    }
}

if (isset($_GET['delete_stock'])) {
    $id = intval($_GET['delete_stock']);
    $stmt = $pdo->prepare("DELETE FROM other_stocks WHERE id = ?");
    if ($stmt->execute([$id])) {
        $message = "موجودی با موفقیت حذف شد";
    } else {
        $error = "خطا در حذف موجودی";
    }
}

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

// دریافت همه پلن‌ها
$plans = $pdo->query("
    SELECT p.*, c.name as category_name, c.fields_config
    FROM other_plans p 
    LEFT JOIN other_categories c ON p.category_id = c.id 
    ORDER BY p.id DESC
")->fetchAll(PDO::FETCH_ASSOC);

// دریافت همه موجودی‌ها
$stocks = $pdo->query("
    SELECT s.*, p.name as plan_name, p.price, p.discount_price, c.name as category_name
    FROM other_stocks s 
    JOIN other_plans p ON s.plan_id = p.id
    JOIN other_categories c ON p.category_id = c.id
    WHERE s.status = 1
    ORDER BY s.id DESC
")->fetchAll(PDO::FETCH_ASSOC);

// دریافت همه خریدهای انجام شده
$purchases = $pdo->query("
    SELECT p.*, a.name as agent_name, a.token as agent_token,
           pl.name as plan_name, c.name as category_name
    FROM other_purchases p 
    JOIN agents a ON p.agent_id = a.id
    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
    ORDER BY p.purchased_at DESC
    LIMIT 100
")->fetchAll(PDO::FETCH_ASSOC);

// متغیر برای ویرایش
$edit_category = null;
$edit_plan = null;
if (isset($_GET['edit_category_id'])) {
    $stmt = $pdo->prepare("SELECT * FROM other_categories WHERE id = ?");
    $stmt->execute([$_GET['edit_category_id']]);
    $edit_category = $stmt->fetch(PDO::FETCH_ASSOC);
}
if (isset($_GET['edit_plan_id'])) {
    $stmt = $pdo->prepare("SELECT * FROM other_plans WHERE id = ?");
    $stmt->execute([$_GET['edit_plan_id']]);
    $edit_plan = $stmt->fetch(PDO::FETCH_ASSOC);
}

// متغیر برای نمایش فرم افزودن موجودی
$show_stock_form = isset($_GET['add_stock_to']) ? intval($_GET['add_stock_to']) : 0;
$selected_plan = null;
if ($show_stock_form) {
    $stmt = $pdo->prepare("
        SELECT p.*, c.fields_config, c.fields_count, c.name as category_name 
        FROM other_plans p 
        JOIN other_categories c ON p.category_id = c.id 
        WHERE p.id = ?
    ");
    $stmt->execute([$show_stock_form]);
    $selected_plan = $stmt->fetch(PDO::FETCH_ASSOC);
}

// تعیین تب فعال
$active_tab = isset($_GET['tab']) ? $_GET['tab'] : 'categories';
if (isset($_GET['add_stock_to'])) {
    $active_tab = 'stocks';
}
?>
<!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;
            --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; }
        .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); }
        .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); }
        
        .form-card { background: var(--glass-bg); backdrop-filter: var(--blur); border: 1px solid var(--glass-border-mid); border-radius: var(--r-xl); margin-bottom: 32px; overflow: hidden; box-shadow: inset 0 1.5px 0 var(--glass-top-shine), var(--shadow-md); }
        .card-header { display: flex; align-items: center; gap: 10px; padding: 18px 24px; border-bottom: 1px solid var(--glass-border); background: rgba(255,255,255,0.12); }
        .card-header-icon { width: 36px; height: 36px; background: linear-gradient(135deg, var(--accent), var(--accent-2)); border-radius: 12px; display: flex; align-items: center; justify-content: center; color: white; }
        .card-title { font-size: 18px; font-weight: 700; color: var(--text-1); }
        .card-body { padding: 24px; }
        .form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 20px; margin-bottom: 20px; }
        .form-field { display: flex; flex-direction: column; gap: 8px; }
        .form-field label { font-size: 12px; font-weight: 600; color: var(--text-2); }
        .form-field input, .form-field select, .form-field textarea { padding: 12px 14px; background: rgba(255,255,255,0.35); backdrop-filter: var(--blur-sm); border: 1px solid var(--glass-border); border-radius: var(--r-md); color: var(--text-1); font-size: 14px; transition: var(--t-smooth); }
        .form-field input:focus, .form-field select:focus, .form-field textarea:focus { outline: none; border-color: rgba(139,92,246,0.45); background: rgba(255,255,255,0.55); box-shadow: 0 0 0 3px rgba(139,92,246,0.15); }
        
        .fields-builder { background: rgba(255,255,255,0.18); border-radius: var(--r-lg); padding: 20px; margin-top: 16px; }
        .field-item { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 16px; padding-bottom: 16px; border-bottom: 1px solid var(--glass-border); }
        
        .submit-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; margin-top: 20px; transition: var(--t-smooth); box-shadow: 0 4px 14px rgba(139,92,246,0.3); }
        .submit-btn:hover { transform: translateY(-2px); box-shadow: 0 8px 24px rgba(139,92,246,0.4); }
        .submit-btn-secondary { background: linear-gradient(135deg, var(--emerald), #059669); }
        
        .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; }
        
        .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); }
        
        .edit-btn, .stock-btn, .view-btn { display: inline-flex; align-items: center; gap: 4px; padding: 6px 12px; background: rgba(139,92,246,0.15); border: 1px solid rgba(139,92,246,0.3); border-radius: var(--r-pill); color: #7c3aed; text-decoration: none; font-size: 11px; font-weight: 600; margin: 0 4px; transition: var(--t-smooth); }
        .delete-btn { display: inline-flex; align-items: center; gap: 4px; padding: 6px 12px; 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: 11px; font-weight: 600; transition: var(--t-smooth); }
        .stock-btn { background: rgba(16,185,129,0.15); border-color: rgba(16,185,129,0.3); color: #059669; }
        .view-btn { background: rgba(59,130,246,0.15); border-color: rgba(59,130,246,0.3); color: #2563eb; }
        .edit-btn:hover, .delete-btn:hover, .stock-btn:hover, .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-active { background: rgba(16,185,129,0.12); color: #059669; border: 1px solid rgba(16,185,129,0.3); }
        .badge-inactive { background: rgba(239,68,68,0.12); color: #dc2626; border: 1px solid rgba(239,68,68,0.25); }
        .badge-success { background: rgba(16,185,129,0.12); color: #059669; border: 1px solid rgba(16,185,129,0.3); }
        
        .tab-content { display: none; }
        .tab-content.active { display: block; }
        
        .fields-preview { font-size: 11px; color: var(--text-3); max-width: 250px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        .agent-info { font-size: 11px; color: var(--text-3); }
        
        .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; } .tabs { flex-direction: column; border-radius: var(--r-lg); } .field-item { grid-template-columns: 1fr; } }
    </style>
</head>
<body>
<div class="page-wrap">
    
    <div class="admin-header">
        <div class="brand">
            <img src="../picture/rahgozar.png" alt="لوگو" class="brand-logo">
            <span class="brand-name">مدیریت محصولات دیگر</span>
        </div>
        <div class="admin-info">
            <span class="admin-welcome">خوش آمدید، <strong><?= htmlspecialchars($admin['full_name'] ?? $admin['username']) ?></strong></span>
            <a href="../admin_panel.php" class="logout-btn back-btn">بازگشت به داشبورد</a>
            <a href="../admin_panel.php?logout=1" class="logout-btn">خروج</a>
        </div>
    </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; ?>
    
    <div class="tabs">
        <a href="?tab=categories" class="tab-btn <?= $active_tab == 'categories' ? 'active' : '' ?>">دسته‌بندی‌ها</a>
        <a href="?tab=plans" class="tab-btn <?= $active_tab == 'plans' ? 'active' : '' ?>">پلن‌ها</a>
        <a href="?tab=stocks" class="tab-btn <?= $active_tab == 'stocks' ? 'active' : '' ?>">موجودی‌ها</a>
        <a href="?tab=purchases" class="tab-btn <?= $active_tab == 'purchases' ? 'active' : '' ?>">خریدهای انجام شده</a>
    </div>
    
    <!-- ==================== تب دسته‌بندی‌ها ==================== -->
    <div id="categoriesTab" class="tab-content <?= $active_tab == 'categories' ? 'active' : '' ?>">
        <div class="form-card">
            <div class="card-header">
                <div class="card-header-icon">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><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>
                </div>
                <div class="card-title"><?= $edit_category ? 'ویرایش دسته‌بندی' : 'افزودن دسته‌بندی جدید' ?></div>
            </div>
            <div class="card-body">
                <form method="POST">
                    <?php if ($edit_category): ?>
                        <input type="hidden" name="category_id" value="<?= $edit_category['id'] ?>">
                    <?php endif; ?>
                    <div class="form-grid">
                        <div class="form-field">
                            <label>نام دسته‌بندی *</label>
                            <input type="text" name="name" required value="<?= $edit_category ? htmlspecialchars($edit_category['name']) : '' ?>" placeholder="مثال: پنل فروش">
                        </div>
                        <div class="form-field">
                            <label>تعداد فیلدها *</label>
                            <input type="number" name="fields_count" id="fields_count" min="1" max="10" required value="<?= $edit_category ? $edit_category['fields_count'] : 3 ?>" onchange="buildFields()">
                        </div>
                        <div class="form-field" style="grid-column: span 2;">
                            <label>توضیحات دسته‌بندی</label>
                            <textarea name="description" rows="2" placeholder="توضیحات مربوط به این دسته‌بندی..."><?= $edit_category ? htmlspecialchars($edit_category['description']) : '' ?></textarea>
                        </div>
                    </div>
                    
                    <div id="fieldsContainer" class="fields-builder">
                        <label style="font-weight: 600; margin-bottom: 12px; display: block;">تنظیمات فیلدهای محصول</label>
                        <div id="fieldsList"></div>
                        <small style="color: var(--text-3);">مثال: فیلد اول: آدرس پنل، فیلد دوم: یوزرنیم، فیلد سوم: پسورد</small>
                    </div>
                    
                    <?php if ($edit_category): ?>
                        <div class="form-field" style="margin-top: 16px;">
                            <label style="display: flex; align-items: center; gap: 8px;">
                                <input type="checkbox" name="status" value="1" <?= $edit_category['status'] ? 'checked' : '' ?>>
                                فعال بودن دسته‌بندی
                            </label>
                        </div>
                        <button type="submit" name="edit_category" class="submit-btn">بروزرسانی دسته‌بندی</button>
                        <a href="?tab=categories" class="submit-btn" style="display: inline-block; text-align: center; background: var(--glass-inset); color: var(--text-2); margin-top: 10px;">انصراف</a>
                    <?php else: ?>
                        <button type="submit" name="add_category" class="submit-btn">ایجاد دسته‌بندی</button>
                    <?php endif; ?>
                </form>
            </div>
        </div>
        
        <div class="data-table">
            <table>
                <thead>
                    <tr><th>شناسه</th><th>نام دسته‌بندی</th><th>تعداد فیلد</th><th>وضعیت</th><th>عملیات</th></tr>
                </thead>
                <tbody>
                    <?php if (count($categories) > 0): ?>
                        <?php foreach ($categories as $cat): ?>
                            <tr>
                                <td><?= $cat['id'] ?></td>
                                <td><strong><?= htmlspecialchars($cat['name']) ?></strong><br><small><?= htmlspecialchars($cat['description']) ?></small></td>
                                <td><?= $cat['fields_count'] ?> فیلد</td>
                                <td><span class="badge <?= $cat['status'] ? 'badge-active' : 'badge-inactive' ?>"><?= $cat['status'] ? 'فعال' : 'غیرفعال' ?></span></td>
                                <td>
                                    <a href="?edit_category_id=<?= $cat['id'] ?>&tab=categories" class="edit-btn">ویرایش</a>
                                    <a href="?delete_category=<?= $cat['id'] ?>&tab=categories" class="delete-btn" onclick="return confirm('آیا از حذف این دسته‌بندی اطمینان دارید؟')">حذف</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="5" style="text-align: center; padding: 40px;">هیچ دسته‌بندی وجود ندارد</td><td style="display:none;"></td><td style="display:none;"></td><td style="display:none;"></td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- ==================== تب پلن‌ها ==================== -->
    <div id="plansTab" class="tab-content <?= $active_tab == 'plans' ? 'active' : '' ?>">
        <div class="form-card">
            <div class="card-header">
                <div class="card-header-icon">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
                </div>
                <div class="card-title"><?= $edit_plan ? 'ویرایش پلن' : 'افزودن پلن جدید' ?></div>
            </div>
            <div class="card-body">
                <form method="POST">
                    <?php if ($edit_plan): ?>
                        <input type="hidden" name="plan_id" value="<?= $edit_plan['id'] ?>">
                    <?php endif; ?>
                    <div class="form-grid">
                        <div class="form-field">
                            <label>دسته‌بندی *</label>
                            <select name="category_id" required>
                                <option value="">انتخاب کنید...</option>
                                <?php foreach ($categories as $cat): ?>
                                    <?php if ($cat['status']): ?>
                                        <option value="<?= $cat['id'] ?>" <?= ($edit_plan && $edit_plan['category_id'] == $cat['id']) ? 'selected' : '' ?>><?= htmlspecialchars($cat['name']) ?></option>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-field">
                            <label>نام پلن *</label>
                            <input type="text" name="name" required value="<?= $edit_plan ? htmlspecialchars($edit_plan['name']) : '' ?>" placeholder="مثال: پنل 100 کاربر">
                        </div>
                        <div class="form-field">
                            <label>قیمت (تومان) *</label>
                            <input type="number" name="price" required value="<?= $edit_plan ? $edit_plan['price'] : '' ?>" placeholder="مثال: 150000">
                        </div>
                        <div class="form-field">
                            <label>قیمت با تخفیف (تومان)</label>
                            <input type="number" name="discount_price" value="<?= $edit_plan && $edit_plan['discount_price'] ? $edit_plan['discount_price'] : '' ?>" placeholder="اختیاری">
                        </div>
                        <div class="form-field" style="grid-column: span 2;">
                            <label>توضیحات پلن (اختیاری)</label>
                            <input type="text" name="descriptions" placeholder="مثال: (100 کاربر)(ترافیک نامحدود)(پشتیبانی 24/7)" value="<?= $edit_plan ? htmlspecialchars($edit_plan['descriptions']) : '' ?>">
                            <small>هر توضیح را داخل پرانتز () قرار دهید</small>
                        </div>
                    </div>
                    
                    <?php if ($edit_plan): ?>
                        <div class="form-field" style="margin-top: 16px;">
                            <label style="display: flex; align-items: center; gap: 8px;">
                                <input type="checkbox" name="status" value="1" <?= $edit_plan['status'] ? 'checked' : '' ?>>
                                فعال بودن پلن
                            </label>
                        </div>
                        <button type="submit" name="edit_plan" class="submit-btn">بروزرسانی پلن</button>
                        <a href="?tab=plans" class="submit-btn" style="display: inline-block; text-align: center; background: var(--glass-inset); color: var(--text-2); margin-top: 10px;">انصراف</a>
                    <?php else: ?>
                        <button type="submit" name="add_plan" class="submit-btn">ایجاد پلن</button>
                    <?php endif; ?>
                </form>
            </div>
        </div>
        
        <div class="data-table">
            <table>
                <thead>
                    <tr><th>شناسه</th><th>نام پلن</th><th>دسته‌بندی</th><th>قیمت</th><th>تعداد موجودی</th><th>وضعیت</th><th>عملیات</th></tr>
                </thead>
                <tbody>
                    <?php if (count($plans) > 0): ?>
                        <?php foreach ($plans as $plan): 
                            $stmt_count = $pdo->prepare("SELECT COUNT(*) as count FROM other_stocks WHERE plan_id = ? AND status = 1");
                            $stmt_count->execute([$plan['id']]);
                            $stock_count = $stmt_count->fetch(PDO::FETCH_ASSOC)['count'];
                        ?>
                            <tr>
                                <td><?= $plan['id'] ?></td>
                                <td><strong><?= htmlspecialchars($plan['name']) ?></strong></td>
                                <td><?= htmlspecialchars($plan['category_name']) ?></td>
                                <td><?= number_format($plan['discount_price'] ?: $plan['price']) ?> تومان<br><small>تخفیف: <?= $plan['discount_price'] ? number_format($plan['discount_price']) : 'ندارد' ?></small></td>
                                <td><?= $stock_count ?> عدد<br><small>موجود</small></td>
                                <td><span class="badge <?= $plan['status'] ? 'badge-active' : 'badge-inactive' ?>"><?= $plan['status'] ? 'فعال' : 'غیرفعال' ?></span></td>
                                <td>
                                    <a href="?add_stock_to=<?= $plan['id'] ?>" class="stock-btn">افزودن موجودی</a>
                                    <a href="?edit_plan_id=<?= $plan['id'] ?>&tab=plans" class="edit-btn">ویرایش</a>
                                    <a href="?delete_plan=<?= $plan['id'] ?>&tab=plans" class="delete-btn" onclick="return confirm('آیا از حذف این پلن اطمینان دارید؟')">حذف</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="7" 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><td style="display:none;"></td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- ==================== تب موجودی‌ها ==================== -->
    <div id="stocksTab" class="tab-content <?= $active_tab == 'stocks' ? 'active' : '' ?>">
        
        <?php if ($show_stock_form && $selected_plan): ?>
        <div class="form-card">
            <div class="card-header">
                <div class="card-header-icon">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                </div>
                <div class="card-title">افزودن موجودی جدید برای پلن: <?= htmlspecialchars($selected_plan['name']) ?></div>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="plan_id" value="<?= $selected_plan['id'] ?>">
                    
                    <?php 
                    $fields_config = json_decode($selected_plan['fields_config'], true);
                    if ($fields_config && is_array($fields_config)):
                        foreach ($fields_config as $index => $field): 
                    ?>
                    <div class="form-field" style="margin-bottom: 16px;">
                        <label><?= htmlspecialchars($field['name']) ?> *</label>
                        <input type="text" name="field_<?= $index ?>" placeholder="<?= htmlspecialchars($field['placeholder']) ?>" required>
                    </div>
                    <?php 
                        endforeach;
                    else:
                    ?>
                    <div class="alert alert-error">خطا: تنظیمات فیلدهای این دسته‌بندی یافت نشد</div>
                    <?php endif; ?>
                    
                    <button type="submit" name="add_stock" class="submit-btn submit-btn-secondary">افزودن این موجودی</button>
                    <a href="?tab=stocks" class="submit-btn" style="display: inline-block; text-align: center; background: var(--glass-inset); color: var(--text-2); margin-top: 10px;">لغو</a>
                </form>
            </div>
        </div>
        <?php endif; ?>
        
        <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($stocks) > 0): ?>
                        <?php foreach ($stocks as $stock): 
                            $fields_data = json_decode($stock['fields_data'], true);
                            $preview = '';
                            if ($fields_data && is_array($fields_data)) {
                                foreach ($fields_data as $field) {
                                    $preview .= $field['name'] . ': ' . htmlspecialchars(mb_substr($field['value'], 0, 30)) . ' | ';
                                }
                            }
                        ?>
                            <tr>
                                <td><?= $stock['id'] ?></td>
                                <td><strong><?= htmlspecialchars($stock['plan_name']) ?></strong><br><small>قیمت: <?= number_format($stock['discount_price'] ?: $stock['price']) ?> تومان</small></td>
                                <td><?= htmlspecialchars($stock['category_name']) ?></td>
                                <td class="fields-preview" title="<?= htmlspecialchars($preview) ?>"><?= htmlspecialchars(mb_substr($preview, 0, 60)) ?>...</td>
                                <td><span class="badge badge-active">موجود</span><br><small>فروش نرفته</small></td>
                                <td>
                                    <a href="?delete_stock=<?= $stock['id'] ?>&tab=stocks" class="delete-btn" onclick="return confirm('آیا از حذف این موجودی اطمینان دارید؟')">حذف</a>
                                    <br><small><a href="?add_stock_to=<?= $stock['plan_id'] ?>&tab=stocks">+ جدید</a></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 id="purchasesTab" class="tab-content <?= $active_tab == 'purchases' ? 'active' : '' ?>">
        <div class="data-table">
            <table>
                <thead>
                    <tr>
                        <th>شناسه</th>
                        <th>نماینده</th>
                        <th>نام محصول</th>
                        <th>دسته‌بندی</th>
                        <th>مبلغ پرداختی</th>
                        <th>زمان خرید</th>
                        <th>جزئیات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($purchases) > 0): ?>
                        <?php foreach ($purchases as $purchase): 
                            $fields_data = json_decode($purchase['fields_data'], true);
                        ?>
                            <tr>
                                <td><?= $purchase['id'] ?></td>
                                <td><strong><?= htmlspecialchars($purchase['agent_name']) ?></strong><br><small class="agent-info">توکن: <?= htmlspecialchars($purchase['agent_token']) ?></small></td>
                                <td><?= htmlspecialchars($purchase['plan_name']) ?></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>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="7" 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><td style="display:none;"></td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
</div>

<script>
function buildFields() {
    const count = document.getElementById('fields_count').value;
    const container = document.getElementById('fieldsList');
    const editCat = <?= json_encode($edit_category) ?>;
    let fieldsConfig = [];
    
    if (editCat && editCat.fields_config) {
        try {
            fieldsConfig = JSON.parse(editCat.fields_config);
        } catch(e) {
            fieldsConfig = [];
        }
    }
    
    let html = '';
    for (let i = 1; i <= count; i++) {
        const fieldName = (fieldsConfig[i-1] && fieldsConfig[i-1].name) ? fieldsConfig[i-1].name : '';
        const fieldPlaceholder = (fieldsConfig[i-1] && fieldsConfig[i-1].placeholder) ? fieldsConfig[i-1].placeholder : '';
        html += `
            <div class="field-item">
                <div class="form-field">
                    <label>نام فیلد ${i}</label>
                    <input type="text" name="field_name_${i}" placeholder="مثال: آدرس پنل" value="${escapeHtml(fieldName)}" required>
                </div>
                <div class="form-field">
                    <label>راهنما / پلیس هولدر</label>
                    <input type="text" name="field_placeholder_${i}" placeholder="مثال: https://example.com" value="${escapeHtml(fieldPlaceholder)}">
                </div>
            </div>
        `;
    }
    container.innerHTML = html;
}

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.agent_name) + '<br><small>توکن: ' + escapeHtml(purchase.agent_token) + '</small></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 (document.getElementById('fieldsList')) {
    buildFields();
}
</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>