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

$admin_logged_in = false;
if (isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true) {
    $admin_logged_in = true;
    $stmt = $pdo->prepare("SELECT * FROM admin WHERE id = ?");
    $stmt->execute([$_SESSION['admin_id']]);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);
}

if (isset($_POST['login'])) {
    $username = trim($_POST['username']);
    $password = $_POST['password'];
    
    $stmt = $pdo->prepare("SELECT * FROM admin WHERE username = ?");
    $stmt->execute([$username]);
    $admin_user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($admin_user && password_verify($password, $admin_user['password'])) {
        $_SESSION['admin_logged_in'] = true;
        $_SESSION['admin_id'] = $admin_user['id'];
        $_SESSION['admin_username'] = $admin_user['username'];
        
        $update = $pdo->prepare("UPDATE admin SET last_login = NOW(), last_ip = ? WHERE id = ?");
        $update->execute([$_SERVER['REMOTE_ADDR'], $admin_user['id']]);
        
        header("Location: admin_panel.php");
        exit;
    } else {
        $login_error = "نام کاربری یا رمز عبور اشتباه است";
    }
}

if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: admin_panel.php");
    exit;
}

if ($admin_logged_in) {
    $total_agents = $pdo->query("SELECT COUNT(*) FROM agents")->fetchColumn();
    $total_panels = $pdo->query("SELECT COUNT(*) FROM panels")->fetchColumn();
    $total_plans = $pdo->query("SELECT COUNT(*) FROM plans")->fetchColumn();
    $total_servers = $pdo->query("SELECT COUNT(*) FROM agent_servers")->fetchColumn();
    $active_servers = $pdo->query("SELECT COUNT(*) FROM agent_servers WHERE status = 1 AND (expiry_date > NOW() OR expiry_date IS NULL)")->fetchColumn();
    $total_sales = $pdo->query("SELECT SUM(price) FROM agent_servers")->fetchColumn() ?? 0;
    $total_balance = $pdo->query("SELECT SUM(balance) FROM agents")->fetchColumn() ?? 0;
    $total_announcements = $pdo->query("SELECT COUNT(*) FROM announcements WHERE status = 1")->fetchColumn();
    
    // دریافت تعداد درخواست‌های pending افزایش موجودی
    $pending_requests = 0;
    $tableCheck = $pdo->query("SHOW TABLES LIKE 'balance_requests'");
    if ($tableCheck->rowCount() > 0) {
        $pending_requests = $pdo->query("SELECT COUNT(*) FROM balance_requests WHERE status = 'pending'")->fetchColumn();
    }
    
    // دریافت تعداد تیکت‌های نیازمند پاسخ (pending)
    $unread_tickets = 0;
    $total_tickets = 0;
    $ticketsTableCheck = $pdo->query("SHOW TABLES LIKE 'tickets'");
    if ($ticketsTableCheck->rowCount() > 0) {
        try {
            $unread_tickets = $pdo->query("SELECT COUNT(*) FROM tickets WHERE status = 'pending'")->fetchColumn();
            $total_tickets = $pdo->query("SELECT COUNT(*) FROM tickets")->fetchColumn();
        } catch (PDOException $e) {
            $unread_tickets = 0;
            $total_tickets = 0;
        }
    }
}
?>
<!DOCTYPE html>
<html dir="rtl" lang="fa">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>پنل مدیریت | رهگذر</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        .chart-container {
            background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);
            border-radius: 20px;
            padding: 20px;
            margin: 20px 0 30px 0;
            box-shadow: 0 20px 35px -10px rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(59, 130, 246, 0.2);
        }
        
        .chart-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .chart-title {
            font-size: 1.3rem;
            font-weight: 600;
            color: #fff;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .chart-title svg {
            width: 24px;
            height: 24px;
            stroke: #3b82f6;
        }
        
        .chart-controls {
            display: flex;
            gap: 8px;
            background: rgba(0, 0, 0, 0.3);
            padding: 5px;
            border-radius: 12px;
            flex-wrap: wrap;
        }
        
        .chart-type-btn {
            padding: 8px 16px;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-size: 13px;
            font-weight: 500;
            transition: all 0.3s ease;
            font-family: inherit;
        }
        
        .chart-type-btn.active {
            background: linear-gradient(135deg, #3b82f6, #2563eb);
            color: white;
            box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
        }
        
        .chart-type-btn:not(.active) {
            background: rgba(255, 255, 255, 0.1);
            color: #94a3b8;
        }
        
        .chart-type-btn:not(.active):hover {
            background: rgba(255, 255, 255, 0.2);
            color: #fff;
        }
        
        .range-control {
            display: flex;
            align-items: center;
            gap: 10px;
            background: rgba(0, 0, 0, 0.3);
            padding: 5px 15px;
            border-radius: 12px;
        }
        
        .range-control label {
            color: #94a3b8;
            font-size: 13px;
        }
        
        .range-control input {
            width: 60px;
            padding: 6px 10px;
            border: 1px solid rgba(59, 130, 246, 0.3);
            border-radius: 8px;
            background: rgba(0, 0, 0, 0.3);
            color: white;
            text-align: center;
            font-size: 14px;
        }
        
        .range-control input:focus {
            outline: none;
            border-color: #3b82f6;
        }
        
        .range-control button {
            padding: 6px 15px;
            background: linear-gradient(135deg, #3b82f6, #2563eb);
            border: none;
            border-radius: 8px;
            color: white;
            cursor: pointer;
            font-size: 13px;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .range-control button:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
        }
        
        .chart-wrapper {
            position: relative;
            height: 400px;
        }
        
        canvas {
            max-height: 400px;
            width: 100%;
        }
        
        .chart-total {
            text-align: center;
            margin-top: 20px;
            padding-top: 15px;
            border-top: 1px solid rgba(148, 163, 184, 0.1);
            font-size: 15px;
            color: #94a3b8;
        }
        
        .chart-total span {
            color: #10b981;
            font-weight: bold;
            font-size: 20px;
        }
        
        @media (max-width: 768px) {
            .chart-header {
                flex-direction: column;
                align-items: stretch;
            }
            
            .chart-controls {
                justify-content: center;
            }
            
            .range-control {
                justify-content: center;
            }
            
            .chart-wrapper {
                height: 300px;
            }
        }
    </style>
</head>
<body>

<?php if (!$admin_logged_in): ?>
    <div class="login-container">
        <div class="login-card">
            <img src="picture/rahgozar.png" alt="مدیریت" class="login-logo">
            <div class="login-title">مدیریت</div>
            <div class="login-subtitle">پنل مدیریت سامانه</div>
            
            <?php if(isset($login_error)): ?>
                <div class="alert alert-error"><?= htmlspecialchars($login_error) ?></div>
            <?php endif; ?>
            
            <form method="POST">
                <input type="text" name="username" class="login-input" placeholder="نام کاربری" required>
                <input type="password" name="password" class="login-input" placeholder="رمز عبور" required>
                <button type="submit" name="login" class="login-btn">ورود به پنل مدیریت</button>
            </form>
        </div>
    </div>

<?php else: ?>
    <div class="container">
        <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">
                <div class="admin-welcome">خوش آمدید، <strong><?= htmlspecialchars($admin['full_name'] ?? $admin['username']) ?></strong></div>
                <a href="?logout=1" class="logout-btn">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
                        <polyline points="16 17 21 12 16 7"/>
                        <line x1="21" y1="12" x2="9" y2="12"/>
                    </svg>
                    خروج
                </a>
            </div>
        </div>

        <!-- نمودار فروش حرفه‌ای -->
        <div class="chart-container">
            <div class="chart-header">
                <div class="chart-title">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M21 12v3a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4v-3"/>
                        <path d="M12 2v8m0 0-3-3m3 3 3-3"/>
                        <path d="M3 18h18"/>
                    </svg>
                    <span id="chartTitle">نمودار فروش روزانه</span>
                </div>
                <div class="chart-controls">
                    <button class="chart-type-btn active" data-type="daily" data-default-range="5">روزانه</button>
                    <button class="chart-type-btn" data-type="weekly" data-default-range="4">هفتگی</button>
                    <button class="chart-type-btn" data-type="monthly" data-default-range="6">ماهانه</button>
                    <button class="chart-type-btn" data-type="yearly" data-default-range="5">سالانه</button>
                    <button class="chart-type-btn" data-type="hourly" data-default-range="6">ساعتی</button>
                </div>
                <div class="range-control">
                    <label>آخرین</label>
                    <input type="number" id="rangeInput" min="1" max="30" value="5">
                    <span id="rangeLabel">روز</span>
                    <button id="updateChart">بروزرسانی</button>
                </div>
            </div>
            <div class="chart-wrapper">
                <canvas id="salesChart"></canvas>
            </div>
            <div class="chart-total">
                جمع کل فروش در این بازه: <span id="totalSales">0</span> تومان
            </div>
        </div>

        <div class="stats-grid">
            <a href="files/agents.php" class="stat-card">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                    <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
                    <circle cx="9" cy="7" r="4"/>
                    <path d="M23 21v-2a4 4 0 0 0-3-3.87"/>
                    <path d="M16 3.13a4 4 0 0 1 0 7.75"/>
                </svg>
                <div class="stat-value"><?= number_format($total_agents) ?></div>
                <div class="stat-label">نمایندگان</div>
            </a>
            <a href="files/panels.php" class="stat-card">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                    <rect x="2" y="2" width="9" height="9" rx="1.5"/>
                    <rect x="13" y="2" width="9" height="9" rx="1.5"/>
                    <rect x="2" y="13" width="9" height="9" rx="1.5"/>
                    <rect x="13" y="13" width="9" height="9" rx="1.5"/>
                </svg>
                <div class="stat-value"><?= number_format($total_panels) ?></div>
                <div class="stat-label">پنل‌ها</div>
            </a>
            <a href="files/plans.php" class="stat-card">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                    <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"/>
                    <line x1="8" y1="13" x2="16" y2="13"/>
                    <line x1="8" y1="17" x2="13" y2="17"/>
                </svg>
                <div class="stat-value"><?= number_format($total_plans) ?></div>
                <div class="stat-label">پلن‌ها</div>
            </a>
            <a href="files/servers.php" class="stat-card">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                    <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"/>
                    <path d="M16 10a4 4 0 0 1-8 0"/>
                </svg>
                <div class="stat-value"><?= number_format($total_servers) ?></div>
                <div class="stat-label">سرویس‌های فروخته شده</div>
            </a>
            <div class="stat-card">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                    <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>
                    <polyline points="22 4 12 14.01 9 11.01"/>
                </svg>
                <div class="stat-value"><?= number_format($active_servers) ?></div>
                <div class="stat-label">سرویس فعال</div>
            </div>
            <div class="stat-card">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                    <rect x="1" y="4" width="22" height="16" rx="2" ry="2"/>
                    <line x1="1" y1="10" x2="23" y2="10"/>
                </svg>
                <div class="stat-value"><?= number_format($total_sales) ?></div>
                <div class="stat-label">کل فروش (تومان)</div>
            </div>
            <div class="stat-card">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                    <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>
                <div class="stat-value"><?= number_format($total_balance) ?></div>
                <div class="stat-label">مجموع موجودی نمایندگان</div>
            </div>
            <a href="files/announcements.php" class="stat-card">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                    <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/>
                    <path d="M13.73 21a2 2 0 0 1-3.46 0"/>
                </svg>
                <div class="stat-value"><?= $total_announcements ?></div>
                <div class="stat-label">اطلاعیه‌های فعال</div>
            </a>
            <a href="files/balance_requests.php" class="stat-card">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                    <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"/>
                    <line x1="16" y1="13" x2="8" y2="13"/>
                    <line x1="16" y1="17" x2="8" y2="17"/>
                    <polyline points="10 9 9 9 8 9"/>
                </svg>
                <div class="stat-value"><?= $pending_requests ?></div>
                <div class="stat-label">درخواست‌های افزایش موجودی</div>
            </a>
            <a href="files/admin_tickets.php" class="stat-card">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                    <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
                    <path d="M9 10h6"/>
                    <path d="M12 13h3"/>
                    <path d="M9 7h6"/>
                </svg>
                <div class="stat-value"><?= $unread_tickets ?></div>
                <div class="stat-label">تیکت‌های نیازمند پاسخ</div>
                <div class="stat-label" style="font-size: 10px; margin-top: 4px;">(<?= $total_tickets ?> تیکت کل)</div>
            </a>
            
            <!-- دکمه جدید محصولات دیگر -->
            <a href="files/other_products.php" class="stat-card">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" 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"/>
                    <path d="M16 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-2h-4.18"/>
                    <circle cx="10" cy="14" r="2"/>
                    <path d="M12 10h-2"/>
                    <path d="M16 14h-2"/>
                </svg>
                <div class="stat-value">محصولات</div>
                <div class="stat-label">محصولات دیگر</div>
            </a>
        </div>
    </div>

    <script>
        let chart = null;
        let currentType = 'daily';
        let currentRange = 5;
        
        async function loadChart(type, range) {
            try {
                const response = await fetch(`files/chart_data.php?type=${type}&range=${range}`);
                const data = await response.json();
                
                if (data.error) {
                    console.error('Error:', data.error);
                    return;
                }
                
                // آپدیت عنوان و جمع کل
                document.getElementById('chartTitle').textContent = data.title;
                document.getElementById('totalSales').innerText = data.total.toLocaleString('fa-IR');
                
                // به‌روزرسانی برچسب محدوده
                const rangeLabel = document.getElementById('rangeLabel');
                if (type === 'hourly') {
                    rangeLabel.textContent = 'ساعت';
                } else if (type === 'daily') {
                    rangeLabel.textContent = 'روز';
                } else if (type === 'weekly') {
                    rangeLabel.textContent = 'هفته';
                } else if (type === 'monthly') {
                    rangeLabel.textContent = 'ماه';
                } else {
                    rangeLabel.textContent = 'سال';
                }
                
                const ctx = document.getElementById('salesChart').getContext('2d');
                
                // ایجاد گرادیانت برای پس‌زمینه نمودار
                const gradient = ctx.createLinearGradient(0, 0, 0, 400);
                gradient.addColorStop(0, 'rgba(59, 130, 246, 0.4)');
                gradient.addColorStop(1, 'rgba(59, 130, 246, 0.05)');
                
                if (chart) {
                    chart.destroy();
                }
                
                // انتخاب نوع نمودار بر اساس نوع داده
                let chartType = 'line';
                let isBar = false;
                if (type === 'weekly' || type === 'yearly') {
                    chartType = 'bar';
                    isBar = true;
                }
                
                chart = new Chart(ctx, {
                    type: chartType,
                    data: {
                        labels: data.labels,
                        datasets: [{
                            label: 'فروش (تومان)',
                            data: data.data,
                            borderColor: '#3b82f6',
                            backgroundColor: isBar ? 'rgba(59, 130, 246, 0.7)' : gradient,
                            borderWidth: 3,
                            pointRadius: isBar ? undefined : 5,
                            pointHoverRadius: isBar ? undefined : 8,
                            pointBackgroundColor: '#3b82f6',
                            pointBorderColor: '#ffffff',
                            pointBorderWidth: 2,
                            tension: 0.3,
                            fill: !isBar,
                            borderRadius: isBar ? 8 : undefined,
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: true,
                        plugins: {
                            legend: {
                                labels: {
                                    color: '#94a3b8',
                                    font: {
                                        size: 12,
                                        family: 'Vazir, sans-serif'
                                    }
                                },
                                position: 'top',
                            },
                            tooltip: {
                                backgroundColor: 'rgba(0, 0, 0, 0.8)',
                                titleColor: '#fff',
                                bodyColor: '#94a3b8',
                                borderColor: '#3b82f6',
                                borderWidth: 1,
                                callbacks: {
                                    label: function(context) {
                                        let value = context.raw;
                                        if (value >= 1000000000) {
                                            return context.dataset.label + ': ' + (value / 1000000000).toFixed(2) + ' میلیارد تومان';
                                        } else if (value >= 1000000) {
                                            return context.dataset.label + ': ' + (value / 1000000).toFixed(2) + ' میلیون تومان';
                                        } else if (value >= 1000) {
                                            return context.dataset.label + ': ' + (value / 1000).toFixed(1) + ' هزار تومان';
                                        }
                                        return context.dataset.label + ': ' + value.toLocaleString('fa-IR') + ' تومان';
                                    }
                                }
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                grid: {
                                    color: 'rgba(148, 163, 184, 0.1)',
                                },
                                ticks: {
                                    color: '#94a3b8',
                                    callback: function(value) {
                                        if (value >= 1000000000) {
                                            return (value / 1000000000).toFixed(1) + 'B';
                                        } else if (value >= 1000000) {
                                            return (value / 1000000).toFixed(1) + 'M';
                                        } else if (value >= 1000) {
                                            return (value / 1000).toFixed(0) + 'K';
                                        }
                                        return value;
                                    }
                                },
                                title: {
                                    display: true,
                                    text: 'مبلغ فروش (تومان)',
                                    color: '#94a3b8',
                                    font: {
                                        size: 11
                                    }
                                }
                            },
                            x: {
                                grid: {
                                    color: 'rgba(148, 163, 184, 0.1)',
                                },
                                ticks: {
                                    color: '#94a3b8',
                                    maxRotation: 45,
                                    minRotation: 45
                                }
                            }
                        },
                        interaction: {
                            intersect: false,
                            mode: 'index'
                        }
                    }
                });
                
            } catch (error) {
                console.error('Error loading chart:', error);
            }
        }
        
        // مدیریت کلیک روی دکمه‌های نوع نمودار
        document.querySelectorAll('.chart-type-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                document.querySelectorAll('.chart-type-btn').forEach(b => b.classList.remove('active'));
                this.classList.add('active');
                
                currentType = this.dataset.type;
                const defaultRange = parseInt(this.dataset.defaultRange);
                currentRange = defaultRange;
                
                document.getElementById('rangeInput').value = defaultRange;
                
                // بروزرسانی محدوده مجاز برای rangeInput
                const rangeInput = document.getElementById('rangeInput');
                if (currentType === 'hourly') {
                    rangeInput.max = 24;
                    rangeInput.value = Math.min(defaultRange, 24);
                } else if (currentType === 'daily') {
                    rangeInput.max = 30;
                } else if (currentType === 'weekly') {
                    rangeInput.max = 12;
                } else if (currentType === 'monthly') {
                    rangeInput.max = 24;
                } else if (currentType === 'yearly') {
                    rangeInput.max = 10;
                }
                
                loadChart(currentType, currentRange);
            });
        });
        
        // بروزرسانی با محدوده جدید
        document.getElementById('updateChart').addEventListener('click', function() {
            let newRange = parseInt(document.getElementById('rangeInput').value);
            if (isNaN(newRange) || newRange < 1) {
                newRange = 1;
            }
            
            // محدودیت بر اساس نوع نمودار
            if (currentType === 'hourly' && newRange > 24) {
                newRange = 24;
            } else if (currentType === 'weekly' && newRange > 12) {
                newRange = 12;
            } else if (currentType === 'monthly' && newRange > 24) {
                newRange = 24;
            } else if (currentType === 'yearly' && newRange > 10) {
                newRange = 10;
            } else if (currentType === 'daily' && newRange > 30) {
                newRange = 30;
            }
            
            currentRange = newRange;
            document.getElementById('rangeInput').value = newRange;
            loadChart(currentType, currentRange);
        });
        
        // بارگذاری اولیه
        loadChart('daily', 5);
        
        // بروزرسانی خودکار هر 30 ثانیه
        setInterval(() => {
            loadChart(currentType, currentRange);
        }, 30000);
    </script>
<?php endif; ?>

</body>
</html>