<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once '../config/database.php';
require_once '../includes/functions.php';

if (!isset($_SESSION['user_level']) || $_SESSION['user_level'] != 'admin') {
    header('Location: ../index.php');
    exit;
}

// ========== دریافت آمار ==========
$totalMembers = $pdo->query("SELECT COUNT(*) FROM members")->fetchColumn();
$activeMembers = $pdo->query("SELECT COUNT(*) FROM members WHERE status = 'active'")->fetchColumn();
$completedMembers = $pdo->query("SELECT COUNT(*) FROM members WHERE status = 'completed'")->fetchColumn();
$withdrawnMembers = $pdo->query("SELECT COUNT(*) FROM members WHERE status = 'withdrawn'")->fetchColumn();

// آمار امروز و دیروز
$todayRegistrations = $pdo->query("SELECT COUNT(*) FROM members WHERE DATE(created_at) = CURDATE()")->fetchColumn();
$yesterdayRegistrations = $pdo->query("SELECT COUNT(*) FROM members WHERE DATE(created_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)")->fetchColumn();

// آمار پرداخت
$paymentStats = $pdo->query("SELECT payment_status, COUNT(*) as count FROM members GROUP BY payment_status")->fetchAll(PDO::FETCH_KEY_PAIR);

// آمار جنسیت (برای بخش کوچک)
$genderStats = $pdo->query("SELECT gender, COUNT(*) as count FROM members GROUP BY gender")->fetchAll(PDO::FETCH_KEY_PAIR);

// آمار رشته‌ها (برای بخش جدید)
$fieldStats = $pdo->query("
    SELECT sf.name, COUNT(m.id) as count 
    FROM members m 
    LEFT JOIN study_fields sf ON m.study_field_id = sf.id 
    WHERE m.study_field_id IS NOT NULL AND m.status = 'active'
    GROUP BY m.study_field_id
    ORDER BY count DESC
")->fetchAll();

// آمار مقاطع
$educationStats = $pdo->query("
    SELECT e.name, COUNT(m.id) as count 
    FROM members m 
    LEFT JOIN educations e ON m.education_id = e.id 
    WHERE m.status = 'active'
    GROUP BY m.education_id
")->fetchAll();

// آمار ماهانه (۱۲ ماه اخیر برای نمودار)
$monthlyStats = $pdo->query("
    SELECT DATE_FORMAT(created_at, '%Y-%m') as month, COUNT(*) as count 
    FROM members 
    GROUP BY month 
    ORDER BY month DESC 
    LIMIT 12
")->fetchAll();
$monthlyStats = array_reverse($monthlyStats);
?>
<?php include '../includes/header.php'; ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<style>
/* ============================================================
   استایل‌های اختصاصی داشبورد
   ============================================================ */
.dashboard-header {
    background: linear-gradient(135deg, #4f46e5, #7c3aed);
    border-radius: 16px;
    padding: 25px 30px;
    color: white;
    margin-bottom: 25px;
}
.dashboard-header h2 {
    font-weight: 700;
    margin: 0;
    font-size: 1.5rem;
}
.dashboard-header p {
    opacity: 0.85;
    margin: 0;
    font-size: 0.9rem;
}
.dashboard-header .badge {
    background: rgba(255,255,255,0.2);
    color: white;
    font-size: 0.85rem;
    padding: 6px 14px;
}

/* کارت‌های آمار */
.stat-card {
    background: white;
    border-radius: 14px;
    padding: 18px 20px;
    border: 1px solid #e9edf2;
    transition: all 0.3s ease;
    height: 100%;
}
.stat-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 25px rgba(0,0,0,0.06);
}
.stat-card .stat-icon {
    width: 44px;
    height: 44px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.3rem;
    color: white;
    flex-shrink: 0;
}
.stat-card .stat-number {
    font-size: 1.8rem;
    font-weight: 700;
    color: #0f172a;
    line-height: 1.2;
}
.stat-card .stat-label {
    color: #94a3b8;
    font-size: 0.8rem;
    font-weight: 500;
    margin-top: 2px;
}
.stat-card .stat-sub {
    font-size: 0.75rem;
    color: #94a3b8;
}
.stat-card .stat-sub .up { color: #16a34a; }
.stat-card .stat-sub .down { color: #dc2626; }

/* رنگ‌های آیکون‌ها */
.bg-gradient-purple { background: linear-gradient(135deg, #8b5cf6, #6d28d9); }
.bg-gradient-blue { background: linear-gradient(135deg, #3b82f6, #1d4ed8); }
.bg-gradient-green { background: linear-gradient(135deg, #22c55e, #15803d); }
.bg-gradient-orange { background: linear-gradient(135deg, #f59e0b, #d97706); }
.bg-gradient-pink { background: linear-gradient(135deg, #ec4899, #be185d); }
.bg-gradient-cyan { background: linear-gradient(135deg, #06b6d4, #0891b2); }
.bg-gradient-red { background: linear-gradient(135deg, #ef4444, #b91c1c); }

/* کارت‌های نمودار */
.chart-card {
    background: white;
    border-radius: 14px;
    border: 1px solid #e9edf2;
    padding: 18px 20px;
    height: 100%;
}
.chart-card .card-title {
    font-weight: 600;
    color: #0f172a;
    margin-bottom: 12px;
    font-size: 0.95rem;
}

/* تفکیک جنسیت کوچک */
.gender-mini {
    display: flex;
    gap: 15px;
    justify-content: center;
    margin-top: 5px;
}
.gender-mini .item {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 0.85rem;
    font-weight: 500;
    color: #0f172a;
}
.gender-mini .item .dot {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    display: inline-block;
}
.gender-mini .item .dot.male { background: #4f46e5; }
.gender-mini .item .dot.female { background: #ef4444; }

/* ============================================================
   ریسپانسیو
   ============================================================ */
@media (max-width: 768px) {
    .dashboard-header { padding: 18px 20px; }
    .dashboard-header h2 { font-size: 1.2rem; }
    .stat-card .stat-number { font-size: 1.4rem; }
    .gender-mini { flex-wrap: wrap; gap: 8px; }
}
</style>

<!-- ============================================================
   هدر داشبورد
   ============================================================ -->
<div class="dashboard-header">
    <div class="row align-items-center">
        <div class="col-md-8">
            <h2>👋 خوش آمدید، <?php echo htmlspecialchars($_SESSION['user_name']); ?></h2>
            <p>مدیریت و نظارت بر سیستم ثبت‌نام</p>
        </div>
        <div class="col-md-4 text-end">
            <span class="badge">📅 <?php echo getCurrentPersianDateTime(); ?></span>
            <span class="badge ms-2">👥 <?php echo number_format($totalMembers); ?> دانشجو</span>
        </div>
    </div>
</div>

<!-- ============================================================
   کارت‌های آمار (۵ تایی + تفکیک جنسیت)
   ============================================================ -->
<div class="row g-3 mb-4">
    <!-- ۱. کل دانشجویان -->
    <div class="col-xl-2 col-lg-4 col-md-6">
        <div class="stat-card">
            <div class="d-flex align-items-start gap-3">
                <div class="stat-icon bg-gradient-purple"><i class="bi bi-people"></i></div>
                <div>
                    <div class="stat-number"><?php echo number_format($totalMembers); ?></div>
                    <div class="stat-label">تعداد کل دانشجویان</div>
                </div>
            </div>
        </div>
    </div>
    <!-- ۲. فعال -->
    <div class="col-xl-2 col-lg-4 col-md-6">
        <div class="stat-card">
            <div class="d-flex align-items-start gap-3">
                <div class="stat-icon bg-gradient-green"><i class="bi bi-check-circle"></i></div>
                <div>
                    <div class="stat-number"><?php echo number_format($activeMembers); ?></div>
                    <div class="stat-label">فعال</div>
                </div>
            </div>
        </div>
    </div>
    <!-- ۳. تکمیل شده -->
    <div class="col-xl-2 col-lg-4 col-md-6">
        <div class="stat-card">
            <div class="d-flex align-items-start gap-3">
                <div class="stat-icon bg-gradient-blue"><i class="bi bi-trophy"></i></div>
                <div>
                    <div class="stat-number"><?php echo number_format($completedMembers); ?></div>
                    <div class="stat-label">تکمیل شده</div>
                </div>
            </div>
        </div>
    </div>
    <!-- ۴. انصرافی -->
    <div class="col-xl-2 col-lg-4 col-md-6">
        <div class="stat-card">
            <div class="d-flex align-items-start gap-3">
                <div class="stat-icon bg-gradient-red"><i class="bi bi-x-circle"></i></div>
                <div>
                    <div class="stat-number"><?php echo number_format($withdrawnMembers); ?></div>
                    <div class="stat-label">انصرافی</div>
                </div>
            </div>
        </div>
    </div>
    <!-- ۵. ثبت‌نام امروز و دیروز -->
    <div class="col-xl-2 col-lg-4 col-md-6">
        <div class="stat-card">
            <div class="d-flex align-items-start gap-3">
                <div class="stat-icon bg-gradient-cyan"><i class="bi bi-calendar-plus"></i></div>
                <div>
                    <div class="stat-number"><?php echo number_format($todayRegistrations); ?></div>
                    <div class="stat-label">ثبت‌نام امروز</div>
                    <div class="stat-sub">دیروز: <span class="<?php echo $yesterdayRegistrations > $todayRegistrations ? 'down' : 'up'; ?>"><?php echo number_format($yesterdayRegistrations); ?></span></div>
                </div>
            </div>
        </div>
    </div>
    <!-- ۶. تفکیک جنسیت (جمع‌وجور) -->
    <div class="col-xl-2 col-lg-4 col-md-6">
        <div class="stat-card">
            <div class="d-flex align-items-start gap-3">
                <div class="stat-icon bg-gradient-pink"><i class="bi bi-gender-ambiguous"></i></div>
                <div>
                    <div class="gender-mini">
                        <span class="item"><span class="dot male"></span> مرد: <?php echo $genderStats['مرد'] ?? 0; ?></span>
                        <span class="item"><span class="dot female"></span> زن: <?php echo $genderStats['زن'] ?? 0; ?></span>
                    </div>
                    <div class="stat-label mt-1">تفکیک جنسیت</div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ============================================================
   آمار رشته‌ها (جدول یا لیست)
   ============================================================ -->
<div class="row g-4 mb-4">
    <div class="col-md-6">
        <div class="chart-card">
            <div class="card-title"><i class="bi bi-book me-2"></i>آمار ثبت‌نام بر اساس رشته</div>
            <?php if (count($fieldStats) > 0): ?>
                <div class="table-responsive">
                    <table class="table table-sm table-hover">
                        <thead>
                            <tr>
                                <th>رشته تحصیلی</th>
                                <th class="text-end">تعداد</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($fieldStats as $row): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($row['name'] ?? 'نامشخص'); ?></td>
                                <td class="text-end"><span class="badge bg-primary"><?php echo $row['count']; ?></span></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <p class="text-muted text-center py-3">هیچ داده‌ای برای نمایش وجود ندارد</p>
            <?php endif; ?>
        </div>
    </div>

    <!-- نمودار ماهانه (خطی) -->
    <div class="col-md-6">
        <div class="chart-card">
            <div class="card-title"><i class="bi bi-graph-up me-2"></i>روند ثبت‌نام ماهانه</div>
            <canvas id="monthlyChart" height="200"></canvas>
        </div>
    </div>
</div>

<!-- ============================================================
   تفکیک مقاطع (ردیف پایین)
   ============================================================ -->
<div class="row g-4">
    <div class="col-md-12">
        <div class="chart-card">
            <div class="card-title"><i class="bi bi-mortarboard me-2"></i>تفکیک مقاطع تحصیلی</div>
            <div class="row">
                <?php foreach ($educationStats as $row): ?>
                <div class="col-md-2 col-6 mb-2">
                    <div class="d-flex justify-content-between align-items-center p-2 bg-light rounded">
                        <span><?php echo htmlspecialchars($row['name'] ?? 'نامشخص'); ?></span>
                        <span class="badge bg-primary"><?php echo $row['count']; ?></span>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>

<!-- ============================================================
   اسکریپت نمودار ماهانه
   ============================================================ -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    // ===== نمودار ماهانه =====
    const monthlyCtx = document.getElementById('monthlyChart').getContext('2d');
    new Chart(monthlyCtx, {
        type: 'line',
        data: {
            labels: [<?php 
                $months = array_column($monthlyStats, 'month');
                $persianMonths = [];
                foreach ($months as $m) {
                    $parts = explode('-', $m);
                    $persianMonths[] = getPersianMonthForStat($parts[1]) . ' ' . ($parts[0] - 621);
                }
                echo "'" . implode("','", $persianMonths) . "'";
            ?>],
            datasets: [{
                data: [<?php echo implode(',', array_column($monthlyStats, 'count')); ?>],
                borderColor: '#4f46e5',
                backgroundColor: 'rgba(79, 70, 229, 0.1)',
                fill: true,
                tension: 0.4,
                pointBackgroundColor: '#4f46e5',
                pointRadius: 4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: { display: false }
            },
            scales: {
                y: { beginAtZero: true, grid: { color: '#f1f5f9' } },
                x: { grid: { display: false } }
            }
        }
    });
});

// تابع تبدیل ماه به فارسی
function getPersianMonthForStat(month) {
    const months = {
        '01': 'فروردین', '02': 'اردیبهشت', '03': 'خرداد',
        '04': 'تیر', '05': 'مرداد', '06': 'شهریور',
        '07': 'مهر', '08': 'آبان', '09': 'آذر',
        '10': 'دی', '11': 'بهمن', '12': 'اسفند'
    };
    return months[month] || month;
}
</script>

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