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

if (!function_exists('displayText')) {
    function displayText($text) {
        if ($text === null) return '';
        return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
    }
}

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

if (isset($_POST['login'])) {
    $token = trim($_POST['token']);
    $stmt = $pdo->prepare("SELECT * FROM agents WHERE token = ?");
    $stmt->execute([$token]);
    $agent = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($agent) {
        $_SESSION['agent_id'] = $agent['id'];
        header("Location: agent.php");
        exit;
    } else {
        $error = "توکن نامعتبر است";
    }
}

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

$announcement = $pdo->query("SELECT * FROM announcements WHERE status = 1 ORDER BY id DESC LIMIT 1")->fetch(PDO::FETCH_ASSOC);

function getAgentStats($pdo, $agent_id) {
    $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM agent_servers WHERE agent_id = ?");
    $stmt->execute([$agent_id]);
    $total_servers = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    $stmt = $pdo->prepare("SELECT COUNT(*) as active FROM agent_servers WHERE agent_id = ? AND (expiry_date > NOW() OR expiry_date IS NULL) AND status = 1");
    $stmt->execute([$agent_id]);
    $active_servers = $stmt->fetch(PDO::FETCH_ASSOC)['active'];
    
    $stmt = $pdo->prepare("SELECT SUM(price) as total FROM agent_servers WHERE agent_id = ?");
    $stmt->execute([$agent_id]);
    $total_spent = $stmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
    
    return [
        'total_servers' => $total_servers,
        'active_servers' => $active_servers,
        'total_spent' => $total_spent
    ];
}

if ($agent) {
    $stats = getAgentStats($pdo, $agent['id']);
    
    $warnings = [];
    if ($agent['balance'] < 100000) {
        $warnings[] = "موجودی شما کمتر از 100,000 تومان است. لطفاً برای شارژ حساب با پشتیبانی تماس بگیرید.";
    }
    $remaining_limit = $agent['service_limit'] - $stats['total_servers'];
    if ($agent['service_limit'] > 0 && $remaining_limit < 3) {
        $warnings[] = "سقف مجاز سرویس‌های شما نزدیک به اتمام است. تنها {$remaining_limit} سرویس دیگر می‌توانید بسازید.";
    }
}
?>
<!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>
        .charts-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
            gap: 25px;
            margin: 20px 0 30px 0;
        }
        
        .chart-card {
            background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);
            border-radius: 20px;
            padding: 20px;
            box-shadow: 0 20px 35px -10px rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(59, 130, 246, 0.2);
            transition: transform 0.3s ease;
        }
        
        .chart-card:hover {
            transform: translateY(-5px);
        }
        
        .chart-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 10px;
        }
        
        .chart-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: #fff;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .chart-title svg {
            width: 22px;
            height: 22px;
            stroke: #3b82f6;
        }
        
        .chart-controls {
            display: flex;
            gap: 8px;
            background: rgba(0, 0, 0, 0.3);
            padding: 4px;
            border-radius: 10px;
        }
        
        .chart-btn {
            padding: 6px 15px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 12px;
            font-weight: 500;
            transition: all 0.3s ease;
            font-family: inherit;
            background: rgba(255, 255, 255, 0.1);
            color: #94a3b8;
        }
        
        .chart-btn.active {
            background: linear-gradient(135deg, #3b82f6, #2563eb);
            color: white;
            box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
        }
        
        .chart-btn:hover:not(.active) {
            background: rgba(255, 255, 255, 0.2);
            color: #fff;
        }
        
        .chart-wrapper {
            position: relative;
            height: 320px;
        }
        
        .chart-total {
            text-align: center;
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid rgba(148, 163, 184, 0.1);
            font-size: 14px;
            color: #94a3b8;
        }
        
        .chart-total span {
            color: #10b981;
            font-weight: bold;
            font-size: 18px;
        }
        
        .no-data-message {
            text-align: center;
            padding: 50px;
            color: #94a3b8;
            font-size: 14px;
        }
        
        @media (max-width: 768px) {
            .charts-container {
                grid-template-columns: 1fr;
            }
            
            .chart-header {
                flex-direction: column;
                align-items: stretch;
            }
            
            .chart-controls {
                justify-content: center;
            }
            
            .chart-wrapper {
                height: 250px;
            }
        }
    </style>
</head>
<body>

<?php if (!$agent): ?>
    <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($error)): ?>
                <div class="alert alert-error"><?= displayText($error) ?></div>
            <?php endif; ?>
            
            <form method="POST">
                <input type="text" name="token" 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><?= displayText($agent['name']) ?></strong></div>
                <div class="admin-welcome" style="font-size: 11px;">توکن: <?= displayText($agent['token']) ?></div>
                <a href="files/tickets.php" class="logout-btn" style="background: #8b5cf6; margin-left: 10px;">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
                    </svg>
                    تیکت‌ها
                </a>
                <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>

        <?php if(!empty($warnings)): ?>
            <div class="warning-bar">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#f87171" stroke-width="2">
                    <path d="M12 9v4M12 17h.01"/>
                    <path d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z"/>
                </svg>
                <div style="flex: 1;">
                    <?php foreach($warnings as $warning): ?>
                        <div class="warning-text"><?= displayText($warning) ?></div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>

        <!-- نمودارهای تحلیلی -->
        <div class="charts-container">
            <!-- نمودار میزان خرید -->
            <div class="chart-card">
                <div class="chart-header">
                    <div class="chart-title">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M12 2v4M12 22v-4M4 12H2M6 12H4M20 12h-2M22 12h-2M19.07 4.93l-2.83 2.83M4.93 19.07l2.83-2.83M19.07 19.07l-2.83-2.83M4.93 4.93l2.83 2.83"/>
                            <circle cx="12" cy="12" r="3"/>
                        </svg>
                        <span id="purchasesTitle">میزان خرید</span>
                    </div>
                    <div class="chart-controls" id="purchasesControls">
                        <button class="chart-btn active" data-range="daily">روزانه</button>
                        <button class="chart-btn" data-range="weekly">هفتگی</button>
                        <button class="chart-btn" data-range="monthly">ماهانه</button>
                    </div>
                </div>
                <div class="chart-wrapper">
                    <canvas id="purchasesChart"></canvas>
                </div>
                <div class="chart-total">
                    جمع کل خرید: <span id="purchasesTotal">0</span> تومان
                </div>
            </div>

            <!-- نمودار پنل‌های پرفروش -->
            <div class="chart-card">
                <div class="chart-header">
                    <div class="chart-title">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <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>
                        <span>پنل‌های پرفروش</span>
                    </div>
                </div>
                <div class="chart-wrapper">
                    <canvas id="panelsChart"></canvas>
                </div>
                <div class="chart-total">
                    تعداد سرویس‌ها: <span id="panelsTotal">0</span>
                </div>
            </div>
        </div>

        <div class="stats-grid">
            <a href="files/services.php" class="stat-card">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="var(--accent-2)" 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"/>
                    <line x1="8" y1="15" x2="10" y2="15"/>
                    <line x1="12" y1="15" x2="16" y2="15"/>
                </svg>
                <div class="stat-value"><?= number_format($agent['balance']) ?></div>
                <div class="stat-label">موجودی (تومان)</div>
            </a>
            <a href="files/services.php" class="stat-card">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="var(--accent-2)" 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"><?= $stats['total_servers'] ?> / <?= $agent['service_limit'] == 0 ? '∞' : $agent['service_limit'] ?></div>
                <div class="stat-label">تعداد سرویس‌ها</div>
            </a>
            <a href="files/services.php" class="stat-card">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="var(--emerald)" 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"><?= $stats['active_servers'] ?></div>
                <div class="stat-label">سرویس فعال</div>
            </a>
            <a href="files/services.php" class="stat-card">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="var(--emerald)" 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($stats['total_spent']) ?></div>
                <div class="stat-label">کل هزینه شده</div>
            </a>
            <a href="files/services.php" class="stat-card">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="var(--accent-3)" stroke-width="1.5">
                    <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>
                <div class="stat-value"><?= $agent['discount'] ?>%</div>
                <div class="stat-label">تخفیف دائمی</div>
            </a>
            <a href="files/news.php" class="stat-card">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="var(--accent-3)" 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"><?= $announcement ? 1 : 0 ?></div>
                <div class="stat-label">اطلاعیه جدید</div>
            </a>
        </div>

        <div class="quick-actions">
            <a href="files/services.php" class="quick-btn">
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                    <circle cx="12" cy="12" r="10"/>
                    <line x1="12" y1="8" x2="12" y2="16"/>
                    <line x1="8" y1="12" x2="16" y2="12"/>
                </svg>
                ساخت سرویس جدید
            </a>
            <a href="files/increase_balance.php" class="quick-btn" style="background: linear-gradient(135deg, var(--accent-2), var(--accent-3)); color: white;">
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="white" 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>
                افزایش موجودی
            </a>
            <a href="files/tickets.php" class="quick-btn" style="background: linear-gradient(135deg, #8b5cf6, #6366f1); color: white;">
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="white" 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"/>
                    <line x1="9" y1="10" x2="15" y2="10"/>
                    <line x1="12" y1="13" x2="15" y2="13"/>
                    <line x1="9" y1="7" x2="15" y2="7"/>
                </svg>
                پشتیبانی و تیکت‌ها
            </a>
            <a href="files/news.php" class="quick-btn">
                <svg width="22" height="22" 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>
                اطلاعیه‌ها
            </a>
            <a href="files/other_products_agent.php" class="quick-btn" style="background: linear-gradient(135deg, #10b981, #059669); color: white;">
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="white" 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>
                محصولات دیگر
            </a>
        </div>
    </div>

    <script>
    let purchasesChart = null;
    let panelsChart = null;
    let currentRange = 'daily';
    
    async function loadPurchasesChart(range) {
        try {
            const response = await fetch(`files/agent_chart_data.php?type=purchases&range=${range}`);
            const data = await response.json();
            
            if (data.error) {
                console.error('Error:', data.error);
                return;
            }
            
            document.getElementById('purchasesTitle').innerHTML = `
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M12 2v4M12 22v-4M4 12H2M6 12H4M20 12h-2M22 12h-2M19.07 4.93l-2.83 2.83M4.93 19.07l2.83-2.83M19.07 19.07l-2.83-2.83M4.93 4.93l2.83 2.83"/>
                    <circle cx="12" cy="12" r="3"/>
                </svg>
                ${data.title}
            `;
            document.getElementById('purchasesTotal').innerText = data.total.toLocaleString('fa-IR');
            
            const ctx = document.getElementById('purchasesChart').getContext('2d');
            const gradient = ctx.createLinearGradient(0, 0, 0, 320);
            gradient.addColorStop(0, 'rgba(59, 130, 246, 0.4)');
            gradient.addColorStop(1, 'rgba(59, 130, 246, 0.05)');
            
            if (purchasesChart) {
                purchasesChart.destroy();
            }
            
            purchasesChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: data.labels,
                    datasets: [{
                        label: 'مبلغ خرید (تومان)',
                        data: data.data,
                        borderColor: '#3b82f6',
                        backgroundColor: gradient,
                        borderWidth: 3,
                        pointRadius: 4,
                        pointHoverRadius: 7,
                        pointBackgroundColor: '#3b82f6',
                        pointBorderColor: '#ffffff',
                        pointBorderWidth: 2,
                        tension: 0.3,
                        fill: true,
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: { 
                            labels: { 
                                color: '#94a3b8', 
                                font: { size: 11 } 
                            } 
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0, 0, 0, 0.8)',
                            titleColor: '#fff',
                            bodyColor: '#94a3b8',
                            callbacks: {
                                label: function(context) {
                                    let value = context.raw;
                                    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(v) { 
                                    if (v >= 1000000) {
                                        return (v / 1000000).toFixed(1) + 'M';
                                    } else if (v >= 1000) {
                                        return (v / 1000).toFixed(0) + 'K';
                                    }
                                    return v;
                                } 
                            }
                        },
                        x: { 
                            grid: { color: 'rgba(148, 163, 184, 0.1)' }, 
                            ticks: { 
                                color: '#94a3b8',
                                maxRotation: 45,
                                minRotation: 45
                            } 
                        }
                    }
                }
            });
        } catch (error) {
            console.error('Error loading purchases chart:', error);
        }
    }
    
    async function loadPanelsChart() {
        try {
            const response = await fetch('files/agent_chart_data.php?type=top_panels');
            const data = await response.json();
            
            if (data.error) return;
            
            document.getElementById('panelsTotal').innerText = data.total;
            
            const ctx = document.getElementById('panelsChart').getContext('2d');
            
            if (panelsChart) {
                panelsChart.destroy();
            }
            
            // اگر داده وجود ندارد
            if (data.labels.length === 1 && data.labels[0] === 'هیچ سرویسی وجود ندارد') {
                panelsChart = new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: data.labels,
                        datasets: [{
                            label: 'تعداد سرویس',
                            data: data.data,
                            backgroundColor: 'rgba(156, 163, 175, 0.5)',
                            borderColor: '#9ca3af',
                            borderWidth: 1,
                            borderRadius: 8,
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: true,
                        plugins: {
                            legend: { labels: { color: '#94a3b8' } }
                        }
                    }
                });
                return;
            }
            
            panelsChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: data.labels,
                    datasets: [{
                        label: 'تعداد سرویس',
                        data: data.data,
                        backgroundColor: 'rgba(59, 130, 246, 0.7)',
                        borderColor: '#3b82f6',
                        borderWidth: 1,
                        borderRadius: 8,
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: { 
                            labels: { 
                                color: '#94a3b8' 
                            } 
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return `تعداد سرویس‌ها: ${context.raw}`;
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: { 
                                stepSize: 1, 
                                color: '#94a3b8' 
                            },
                            grid: { color: 'rgba(148, 163, 184, 0.1)' }
                        },
                        x: { 
                            ticks: { 
                                color: '#94a3b8',
                                maxRotation: 45,
                                minRotation: 45
                            } 
                        }
                    }
                }
            });
        } catch (error) {
            console.error('Error loading panels chart:', error);
        }
    }
    
    // رویدادهای دکمه‌های نمودار خرید
    document.querySelectorAll('#purchasesControls .chart-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelectorAll('#purchasesControls .chart-btn').forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            currentRange = this.dataset.range;
            loadPurchasesChart(currentRange);
        });
    });
    
    // بارگذاری اولیه
    loadPurchasesChart('daily');
    loadPanelsChart();
    
    // بروزرسانی خودکار هر 60 ثانیه
    setInterval(() => {
        loadPurchasesChart(currentRange);
        loadPanelsChart();
    }, 60000);
</script>
<?php endif; ?>

</body>
</html>