<?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();

// آمار ماهانه (برای نمایش در هدر)
$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();

// ============================================================
// آمار وضعیت‌ها
// ============================================================
$paymentStats = $pdo->query("SELECT payment_status, COUNT(*) as count FROM members GROUP BY payment_status")->fetchAll(PDO::FETCH_KEY_PAIR);
$contactStats = $pdo->query("SELECT registration_status, COUNT(*) as count FROM members GROUP BY registration_status")->fetchAll(PDO::FETCH_KEY_PAIR);
$documentStats = $pdo->query("SELECT document_status, COUNT(*) as count FROM members GROUP BY document_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 
    GROUP BY m.study_field_id 
    ORDER BY count DESC 
    LIMIT 10
")->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 
    GROUP BY m.education_id
")->fetchAll();

// ============================================================
// متغیرهای تقویم
// ============================================================
$currentTimestamp = time();
$currentYear = date('Y', $currentTimestamp) - 621;
$currentMonth = date('m', $currentTimestamp);
$currentDay = date('d', $currentTimestamp);
$selectedMonth = $_GET['month'] ?? $currentMonth;
$selectedYear = $_GET['year'] ?? $currentYear;

$datesWithMembers = $pdo->query("
    SELECT DISTINCT DATE(created_at) as date, COUNT(*) as count 
    FROM members 
    GROUP BY DATE(created_at)
")->fetchAll(PDO::FETCH_KEY_PAIR);

// ============================================================
// دانشجویان یک روز خاص (برای تقویم)
// ============================================================
$selectedDate = $_GET['date'] ?? '';
$dailyMembers = [];
if (!empty($selectedDate)) {
    $stmt = $pdo->prepare("
        SELECT m.*, e.name as education_name, sf.name as study_field_name 
        FROM members m 
        LEFT JOIN educations e ON m.education_id = e.id 
        LEFT JOIN study_fields sf ON m.study_field_id = sf.id 
        WHERE DATE(m.created_at) = ? 
        ORDER BY m.created_at DESC
    ");
    $stmt->execute([$selectedDate]);
    $dailyMembers = $stmt->fetchAll();
}

// ============================================================
// متغیرهای جستجو (بدون انتخاب نوع)
// ============================================================
$searchQuery = $_GET['search'] ?? '';
$searchResults = [];

if (!empty($searchQuery)) {
    $sql = "SELECT m.*, e.name as education_name, sf.name as study_field_name 
            FROM members m 
            LEFT JOIN educations e ON m.education_id = e.id 
            LEFT JOIN study_fields sf ON m.study_field_id = sf.id 
            WHERE m.fullname LIKE ? 
               OR m.national_code LIKE ? 
               OR sf.name LIKE ? 
               OR e.name LIKE ?
            ORDER BY m.created_at DESC 
            LIMIT 20";
    $stmt = $pdo->prepare($sql);
    $searchParam = "%$searchQuery%";
    $stmt->execute([$searchParam, $searchParam, $searchParam, $searchParam]);
    $searchResults = $stmt->fetchAll();
}

// ============================================================
// توابع کمکی
// ============================================================
function getPersianMonth($monthNumber) {
    $months = ['01' => 'فروردین', '02' => 'اردیبهشت', '03' => 'خرداد', '04' => 'تیر', '05' => 'مرداد', '06' => 'شهریور', '07' => 'مهر', '08' => 'آبان', '09' => 'آذر', '10' => 'دی', '11' => 'بهمن', '12' => 'اسفند'];
    return $months[$monthNumber] ?? $monthNumber;
}
?>
<?php include '../includes/header.php'; ?>

<!-- ============================================================
   استایل‌های اختصاصی
   ============================================================ -->
<style>
.dashboard-header {
    background: linear-gradient(135deg, #4f46e5, #7c3aed);
    border-radius: 16px;
    padding: 25px 30px;
    color: white;
    margin-bottom: 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
}
.dashboard-header .greeting h2 {
    font-weight: 700;
    margin: 0;
    font-size: 1.4rem;
}
.dashboard-header .greeting p {
    opacity: 0.8;
    margin: 0;
    font-size: 0.9rem;
}
.dashboard-header .stats-badge {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
}
.dashboard-header .stats-badge .badge-item {
    background: rgba(255, 255, 255, 0.15);
    backdrop-filter: blur(5px);
    padding: 6px 16px;
    border-radius: 30px;
    font-size: 0.8rem;
    display: flex;
    align-items: center;
    gap: 6px;
}
.dashboard-header .stats-badge .badge-item .num {
    font-weight: 700;
}

.stat-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
    gap: 16px;
    margin-bottom: 25px;
}
.stat-card {
    background: white;
    border-radius: 14px;
    padding: 16px 18px;
    border: 1px solid #e9edf2;
    transition: all 0.25s ease;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.02);
}
.stat-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.06);
}
.stat-card .stat-number {
    font-size: 1.6rem;
    font-weight: 700;
    color: #0f172a;
    line-height: 1.1;
}
.stat-card .stat-label {
    font-size: 0.8rem;
    color: #94a3b8;
    font-weight: 500;
}
.stat-card .stat-change {
    font-size: 0.65rem;
    font-weight: 600;
    padding: 1px 8px;
    border-radius: 20px;
    display: inline-block;
    margin-top: 2px;
}
.stat-card .stat-change.up {
    background: #dcfce7;
    color: #16a34a;
}
.stat-card .stat-change.down {
    background: #fee2e2;
    color: #dc2626;
}

/* ===== وضعیت‌ها با طراحی جدید و بزرگ‌تر ===== */
.status-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
}
.status-item {
    background: #f8fafc;
    padding: 10px 14px;
    border-radius: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-right: 4px solid #4f46e5;
    transition: all 0.2s ease;
}
.status-item:hover {
    background: #f1f5f9;
}
.status-item .status-label {
    font-size: 0.85rem;
    font-weight: 500;
    color: #1e293b;
}
.status-item .status-badge {
    font-size: 0.85rem;
    font-weight: 600;
    padding: 4px 16px;
    border-radius: 20px;
    color: white;
    min-width: 40px;
    text-align: center;
}

.field-list {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 6px;
}
.field-item {
    background: #f8fafc;
    padding: 5px 10px;
    border-radius: 8px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 0.8rem;
}
.field-item .field-count {
    background: #4f46e5;
    color: white;
    padding: 0 10px;
    border-radius: 12px;
    font-size: 0.6rem;
    font-weight: 600;
}

.gender-mini {
    display: flex;
    gap: 18px;
    align-items: center;
    justify-content: center;
    margin-top: 6px;
}
.gender-mini .gender-item {
    display: flex;
    align-items: center;
    gap: 5px;
    font-size: 0.85rem;
    font-weight: 500;
    color: #1e293b;
}
.gender-mini .gender-item .gender-icon {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.8rem;
    color: white;
}
.gender-mini .gender-item .gender-icon.male {
    background: #4f46e5;
}
.gender-mini .gender-item .gender-icon.female {
    background: #ec4899;
}

.search-section {
    background: white;
    border-radius: 14px;
    padding: 18px 20px;
    border: 1px solid #e9edf2;
    margin-bottom: 25px;
}
.search-section .search-form {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}
.search-section .search-form input {
    border-radius: 10px;
    border: 1px solid #d1d5db;
    padding: 8px 14px;
    font-size: 0.85rem;
    flex: 1;
    min-width: 200px;
}
.search-section .search-form button {
    background: #4f46e5;
    color: white;
    border: none;
    padding: 8px 22px;
    border-radius: 10px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s ease;
}
.search-section .search-form button:hover {
    background: #4338ca;
}

.result-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 10px;
    font-size: 0.8rem;
}
.result-table th {
    text-align: right;
    padding: 6px 10px;
    background: #f8fafc;
    color: #475569;
    font-weight: 600;
    font-size: 0.7rem;
    text-transform: uppercase;
    border-bottom: 2px solid #e9edf2;
}
.result-table td {
    padding: 6px 10px;
    border-bottom: 1px solid #f1f5f9;
}
.result-table td a {
    color: #4f46e5;
    text-decoration: none;
    font-weight: 500;
}
.result-table td a:hover {
    text-decoration: underline;
}

.calendar-wrapper {
    background: white;
    border-radius: 14px;
    padding: 20px;
    border: 1px solid #e9edf2;
    margin-top: 20px;
}
.calendar-grid {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 5px;
}
.calendar-weekday {
    text-align: center;
    font-weight: 600;
    font-size: 0.7rem;
    color: #94a3b8;
    padding: 6px 0;
}
.calendar-day {
    text-align: center;
    padding: 8px 0;
    border-radius: 10px;
    background: #f8fafc;
    font-size: 0.8rem;
    transition: all 0.2s ease;
    cursor: default;
}
.calendar-day.has-member {
    background: #eef2ff;
    color: #4f46e5;
    cursor: pointer;
}
.calendar-day.has-member:hover {
    background: #dbeafe;
}
.calendar-day.today {
    border: 2px solid #4f46e5;
}
.calendar-day .day-count {
    font-size: 0.55rem;
    opacity: 0.7;
    display: block;
}

@media (max-width: 768px) {
    .stat-grid {
        grid-template-columns: repeat(2, 1fr);
    }
    .status-grid {
        grid-template-columns: 1fr;
    }
    .field-list {
        grid-template-columns: 1fr;
    }
    .dashboard-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }
    .dashboard-header .stats-badge {
        width: 100%;
        justify-content: flex-start;
    }
}
</style>

<!-- ============================================================
   هدر (بدون ساعت)
   ============================================================ -->
<div class="dashboard-header">
    <div class="greeting">
        <h2>👋 خوش آمدید، <?php echo htmlspecialchars($_SESSION['user_name']); ?></h2>
        <p>مدیریت و نظارت بر سیستم ثبت‌نام</p>
    </div>
    <div class="stats-badge">
        <span class="badge-item"><i class="bi bi-calendar3"></i> <?php echo getCurrentPersianDateTimeFa(); ?></span>
        <span class="badge-item"><i class="bi bi-people"></i> <span class="num"><?php echo toPersianNumbers(number_format($totalMembers)); ?></span> دانشجو</span>
        <span class="badge-item"><i class="bi bi-calendar-plus"></i> امروز: <span class="num"><?php echo toPersianNumbers(number_format($todayRegistrations)); ?></span></span>
        <span class="badge-item"><i class="bi bi-calendar-minus"></i> دیروز: <span class="num"><?php echo toPersianNumbers(number_format($yesterdayRegistrations)); ?></span></span>
        <span class="badge-item"><i class="bi bi-graph-up"></i> ماه: <span class="num"><?php 
            $currentMonthTotal = 0;
            foreach ($monthlyStats as $m) {
                if (substr($m['month'], 0, 7) == date('Y-m')) {
                    $currentMonthTotal = $m['count'];
                }
            }
            echo toPersianNumbers(number_format($currentMonthTotal)); 
        ?></span></span>
    </div>
</div>

<!-- ============================================================
   کارت‌های آمار اصلی
   ============================================================ -->
<div class="stat-grid">
    <div class="stat-card">
        <div class="stat-number"><?php echo toPersianNumbers(number_format($totalMembers)); ?></div>
        <div class="stat-label">👥 کل دانشجویان</div>
        <span class="stat-change up"><i class="bi bi-arrow-up"></i> 12%</span>
    </div>
    <div class="stat-card">
        <div class="stat-number"><?php echo toPersianNumbers(number_format($activeMembers)); ?></div>
        <div class="stat-label">✅ فعال</div>
        <span class="stat-change up"><i class="bi bi-arrow-up"></i> 8%</span>
    </div>
    <div class="stat-card">
        <div class="stat-number"><?php echo toPersianNumbers(number_format($completedMembers)); ?></div>
        <div class="stat-label">🎓 تکمیل شده</div>
        <span class="stat-change up"><i class="bi bi-arrow-up"></i> 5%</span>
    </div>
    <div class="stat-card">
        <div class="stat-number"><?php echo toPersianNumbers(number_format($withdrawnMembers)); ?></div>
        <div class="stat-label">📤 انصرافی</div>
        <span class="stat-change down"><i class="bi bi-arrow-down"></i> 2%</span>
    </div>
</div>

<!-- ============================================================
   بخش آمار وضعیت‌ها و جنسیت (با طراحی جدید)
   ============================================================ -->
<div class="row g-4 mb-4">
    <!-- جنسیت با آیکون‌های مینیمال -->
    <div class="col-md-3">
        <div class="chart-box" style="background:white; border-radius:14px; padding:16px 20px; border:1px solid #e9edf2; height:100%;">
            <div style="font-weight:600; font-size:0.9rem; color:#0f172a; margin-bottom:8px;"><i class="bi bi-gender-ambiguous" style="color:#4f46e5;"></i> جنسیت</div>
            <div class="gender-mini">
                <span class="gender-item">
                    <span class="gender-icon male"><i class="bi bi-gender-male"></i></span>
                    مرد: <strong><?php echo toPersianNumbers($genderStats['مرد'] ?? 0); ?></strong>
                </span>
                <span class="gender-item">
                    <span class="gender-icon female"><i class="bi bi-gender-female"></i></span>
                    زن: <strong><?php echo toPersianNumbers($genderStats['زن'] ?? 0); ?></strong>
                </span>
            </div>
        </div>
    </div>

    <!-- آمار وضعیت تماس (بزرگ‌تر و مدرن‌تر) -->
    <div class="col-md-3">
        <div class="chart-box" style="background:white; border-radius:14px; padding:16px 20px; border:1px solid #e9edf2; height:100%;">
            <div style="font-weight:600; font-size:0.9rem; color:#0f172a; margin-bottom:10px;"><i class="bi bi-telephone" style="color:#4f46e5;"></i> وضعیت تماس</div>
            <?php foreach ($contactStats as $status => $count): ?>
                <div class="status-item" style="border-right-color: <?php echo $status == 'تماس گرفته شده' ? '#22c55e' : ($status == 'تماس گرفته نشده' ? '#94a3b8' : ($status == 'در انتظار پاسخ' ? '#f59e0b' : '#ef4444')); ?>;">
                    <span class="status-label"><?php echo $status; ?></span>
                    <span class="status-badge" style="background: <?php echo $status == 'تماس گرفته شده' ? '#22c55e' : ($status == 'تماس گرفته نشده' ? '#94a3b8' : ($status == 'در انتظار پاسخ' ? '#f59e0b' : '#ef4444')); ?>;"><?php echo toPersianNumbers($count); ?></span>
                </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- آمار وضعیت مدارک (بزرگ‌تر و مدرن‌تر) -->
    <div class="col-md-3">
        <div class="chart-box" style="background:white; border-radius:14px; padding:16px 20px; border:1px solid #e9edf2; height:100%;">
            <div style="font-weight:600; font-size:0.9rem; color:#0f172a; margin-bottom:10px;"><i class="bi bi-file-earmark-text" style="color:#4f46e5;"></i> وضعیت مدارک</div>
            <?php foreach ($documentStats as $status => $count): ?>
                <div class="status-item" style="border-right-color: <?php echo $status == 'تایید شده' ? '#22c55e' : ($status == 'مدارک تکمیل شده' ? '#3b82f6' : ($status == 'در انتظار تکمیل مدرک' ? '#f59e0b' : '#ef4444')); ?>;">
                    <span class="status-label"><?php echo $status; ?></span>
                    <span class="status-badge" style="background: <?php echo $status == 'تایید شده' ? '#22c55e' : ($status == 'مدارک تکمیل شده' ? '#3b82f6' : ($status == 'در انتظار تکمیل مدرک' ? '#f59e0b' : '#ef4444')); ?>;"><?php echo toPersianNumbers($count); ?></span>
                </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- آمار وضعیت پرداخت (بزرگ‌تر و مدرن‌تر) -->
    <div class="col-md-3">
        <div class="chart-box" style="background:white; border-radius:14px; padding:16px 20px; border:1px solid #e9edf2; height:100%;">
            <div style="font-weight:600; font-size:0.9rem; color:#0f172a; margin-bottom:10px;"><i class="bi bi-wallet2" style="color:#4f46e5;"></i> وضعیت پرداخت</div>
            <?php foreach ($paymentStats as $status => $count): ?>
                <div class="status-item" style="border-right-color: <?php echo $status == 'پرداخت شده' ? '#22c55e' : ($status == 'پرداخت نشده' ? '#ef4444' : ($status == 'در انتظار پرداخت' ? '#f59e0b' : '#8b5cf6')); ?>;">
                    <span class="status-label"><?php echo $status; ?></span>
                    <span class="status-badge" style="background: <?php echo $status == 'پرداخت شده' ? '#22c55e' : ($status == 'پرداخت نشده' ? '#ef4444' : ($status == 'در انتظار پرداخت' ? '#f59e0b' : '#8b5cf6')); ?>;"><?php echo toPersianNumbers($count); ?></span>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- ============================================================
   رشته‌های تحصیلی و مقاطع
   ============================================================ -->
<div class="row g-4 mb-4">
    <div class="col-md-6">
        <div class="chart-box" style="background:white; border-radius:14px; padding:16px 20px; border:1px solid #e9edf2; height:100%;">
            <div style="font-weight:600; font-size:0.9rem; color:#0f172a; margin-bottom:10px;"><i class="bi bi-book" style="color:#4f46e5;"></i> رشته‌های تحصیلی</div>
            <div class="field-list">
                <?php foreach ($fieldStats as $field): ?>
                    <div class="field-item">
                        <span><?php echo htmlspecialchars($field['name'] ?? 'نامشخص'); ?></span>
                        <span class="field-count"><?php echo toPersianNumbers($field['count']); ?></span>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="chart-box" style="background:white; border-radius:14px; padding:16px 20px; border:1px solid #e9edf2; height:100%;">
            <div style="font-weight:600; font-size:0.9rem; color:#0f172a; margin-bottom:10px;"><i class="bi bi-mortarboard" style="color:#4f46e5;"></i> مقاطع تحصیلی</div>
            <div class="field-list">
                <?php foreach ($educationStats as $edu): ?>
                    <div class="field-item">
                        <span><?php echo htmlspecialchars($edu['name'] ?? 'نامشخص'); ?></span>
                        <span class="field-count"><?php echo toPersianNumbers($edu['count']); ?></span>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>

<!-- ============================================================
   بخش جستجو (جامع - بدون انتخاب نوع)
   ============================================================ -->
<div class="search-section" id="searchSection">
    <form method="GET" class="search-form" id="searchForm" onsubmit="event.preventDefault(); performSearch();">
        <input type="text" 
               id="liveSearch" 
               name="search" 
               class="form-control" 
               placeholder="جستجوی نام، کد ملی، رشته یا مقطع..." 
               value="<?php echo htmlspecialchars($searchQuery ?? ''); ?>"
               autocomplete="off">
        <button type="submit"><i class="bi bi-search"></i> جستجو</button>
    </form>

    <!-- نتایج جستجو -->
    <div id="searchResultsContainer">
        <?php if (!empty($searchQuery) && !empty($searchResults)): ?>
            <div style="margin-top:10px;">
                <div style="font-weight:600; font-size:0.85rem; margin-bottom:4px;">نتایج جستجو (<?php echo toPersianNumbers(count($searchResults)); ?> نفر)</div>
                <div style="overflow-x:auto;">
                    <table class="result-table">
                        <thead><tr><th>نام</th><th>کد ملی</th><th>مقطع</th><th>رشته</th><th>تاریخ ثبت</th></tr></thead>
                        <tbody>
                            <?php foreach ($searchResults as $row): ?>
                                <tr>
                                    <td><a href="/portal/admin/edit_member.php?id=<?php echo $row['id']; ?>"><?php echo htmlspecialchars($row['fullname']); ?></a></td>
                                    <td><?php echo toPersianNumbers($row['national_code']); ?></td>
                                    <td><?php echo htmlspecialchars($row['education_name']); ?></td>
                                    <td><?php echo htmlspecialchars($row['study_field_name']); ?></td>
                                    <td><?php echo convertToPersianDateFa($row['created_at']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- ============================================================
   تقویم (با نمایش اسامی قابل کلیک)
   ============================================================ -->
<div class="calendar-wrapper" id="calendarWrapper">
    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:12px;">
        <h5 style="margin:0; font-weight:600; font-size:1rem;"><i class="bi bi-calendar3" style="color:#4f46e5;"></i> تقویم ثبت‌نام ماهانه</h5>
        <div>
            <button onclick="location.href='?month=<?php echo $selectedMonth - 1; ?>&year=<?php echo $selectedYear; ?>'" class="btn btn-sm btn-outline-primary">‹</button>
            <span style="margin:0 10px; font-weight:500;"><?php echo getPersianMonth(str_pad((string)$selectedMonth, 2, '0', STR_PAD_LEFT)) . ' ' . toPersianNumbers($selectedYear); ?></span>
            <button onclick="location.href='?month=<?php echo $selectedMonth + 1; ?>&year=<?php echo $selectedYear; ?>'" class="btn btn-sm btn-outline-primary">›</button>
        </div>
    </div>

    <div class="calendar-grid" id="calendarGrid">
        <div class="calendar-weekday">شنبه</div>
        <div class="calendar-weekday">یکشنبه</div>
        <div class="calendar-weekday">دوشنبه</div>
        <div class="calendar-weekday">سه‌شنبه</div>
        <div class="calendar-weekday">چهارشنبه</div>
        <div class="calendar-weekday">پنج‌شنبه</div>
        <div class="calendar-weekday">جمعه</div>

        <?php
        $daysInMonth = 31;
        if ($selectedMonth > 6) $daysInMonth = 30;
        if ($selectedMonth == 12) $daysInMonth = ($selectedYear % 4 == 0) ? 30 : 29;

        for ($day = 1; $day <= $daysInMonth; $day++) {
            $hasReg = isset($datesWithMembers[sprintf("%04d-%02d-%02d", $selectedYear + 621, $selectedMonth, $day)]);
            $isToday = ($day == $currentDay && $selectedMonth == $currentMonth && $selectedYear == $currentYear);
            $count = $datesWithMembers[sprintf("%04d-%02d-%02d", $selectedYear + 621, $selectedMonth, $day)] ?? 0;
            
            // استفاده از onclick با event.preventDefault() برای جلوگیری از پرش به بالا
            $onclick = '';
            if ($hasReg) {
                $onclick = "onclick=\"event.preventDefault(); loadDailyMembers('" . sprintf("%04d-%02d-%02d", $selectedYear + 621, $selectedMonth, $day) . "', this);\"";
            }
            
            echo '<div class="calendar-day ' . ($isToday ? 'today' : '') . ($hasReg ? ' has-member' : '') . '" ' . $onclick . ' title="' . toPersianNumbers($count) . ' نفر">';
            echo toPersianNumbers($day);
            if ($hasReg) echo '<span class="day-count">' . toPersianNumbers($count) . '</span>';
            echo '</div>';
        }
        ?>
    </div>

    <!-- ===== نمایش اسامی دانشجویان در پایین تقویم (قابل کلیک) ===== -->
    <div id="dailyMembersContainer" style="margin-top:15px; padding-top:12px; border-top:1px solid #e9edf2;">
        <?php if (!empty($selectedDate)): ?>
            <h6 style="font-weight:600; font-size:0.9rem;">📋 دانشجویان ثبت‌نام شده در تاریخ <?php echo convertToPersianDateOnlyFa($selectedDate); ?></h6>
            <div style="overflow-x:auto;">
                <table class="result-table">
                    <thead><tr><th>نام</th><th>کد ملی</th><th>مقطع</th><th>رشته</th></tr></thead>
                    <tbody>
                        <?php if (count($dailyMembers) > 0): ?>
                            <?php foreach ($dailyMembers as $row): ?>
                                <tr>
                                    <td><a href="/portal/admin/edit_member.php?id=<?php echo $row['id']; ?>"><?php echo htmlspecialchars($row['fullname']); ?></a></td>
                                    <td><?php echo toPersianNumbers($row['national_code']); ?></td>
                                    <td><?php echo htmlspecialchars($row['education_name']); ?></td>
                                    <td><?php echo htmlspecialchars($row['study_field_name']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="4" style="text-align:center; color:#94a3b8;">هیچ دانشجویی در این تاریخ ثبت‌نام نکرده است</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- ============================================================
   اسکریپت جستجوی زنده و تقویم
   ============================================================ -->
<script>
// تابع تبدیل اعداد به فارسی
function toPersianNumbers(number) {
    if (number === null || number === undefined || number === '') return '';
    const persian = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
    const english = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    return String(number).replace(/[0-9]/g, function(w) {
        return persian[english.indexOf(w)];
    });
}

document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('liveSearch');
    const resultsContainer = document.getElementById('searchResultsContainer');
    const searchForm = document.getElementById('searchForm');
    const dailyContainer = document.getElementById('dailyMembersContainer');
    let searchTimer = null;

    // ============================================================
    // جستجوی زنده با تایپ کردن
    // ============================================================
    searchInput.addEventListener('input', function() {
        clearTimeout(searchTimer);
        const query = this.value.trim();
        
        if (query.length < 2) {
            if (query.length === 0) {
                resultsContainer.innerHTML = '';
            }
            return;
        }

        searchTimer = setTimeout(function() {
            fetchLiveResults(query);
        }, 300);
    });

    // ============================================================
    // جستجو با کلیک روی دکمه یا Enter
    // ============================================================
    searchForm.addEventListener('submit', function(e) {
        e.preventDefault();
        const query = searchInput.value.trim();
        if (query.length >= 2) {
            fetchLiveResults(query);
        }
    });

    // ============================================================
    // تابع دریافت نتایج جستجو
    // ============================================================
    function fetchLiveResults(query) {
        resultsContainer.innerHTML = '<div style="text-align:center; padding:10px; color:#94a3b8;"><i class="bi bi-hourglass-split"></i> در حال جستجو...</div>';

        fetch(`reports_ajax.php?search=${encodeURIComponent(query)}&search_type=all`)
            .then(response => response.json())
            .then(data => {
                displaySearchResults(data, query);
            })
            .catch(error => {
                console.error('Error:', error);
                resultsContainer.innerHTML = '<div style="text-align:center; padding:10px; color:#ef4444;">خطا در ارتباط با سرور</div>';
            });
    }

    // ============================================================
    // تابع نمایش نتایج جستجو
    // ============================================================
    function displaySearchResults(results, query) {
        if (results.length === 0) {
            resultsContainer.innerHTML = `
                <div style="margin-top:10px; color:#94a3b8; text-align:center;">
                    <i class="bi bi-search"></i> هیچ نتیجه‌ای برای "${query}" یافت نشد
                </div>
            `;
            return;
        }

        let html = `
            <div style="margin-top:10px;">
                <div style="font-weight:600; font-size:0.85rem; margin-bottom:4px;">
                    نتایج جستجو (${toPersianNumbers(results.length)} نفر)
                </div>
                <div style="overflow-x:auto;">
                    <table class="result-table">
                        <thead>
                            <tr>
                                <th>نام</th>
                                <th>کد ملی</th>
                                <th>مقطع</th>
                                <th>رشته</th>
                                <th>تاریخ ثبت</th>
                            </tr>
                        </thead>
                        <tbody>
        `;

        results.forEach(function(row) {
            html += `
                <tr>
                    <td><a href="/portal/admin/edit_member.php?id=${row.id}">${row.fullname}</a></td>
                    <td>${toPersianNumbers(row.national_code)}</td>
                    <td>${row.education_name || 'نامشخص'}</td>
                    <td>${row.study_field_name || 'نامشخص'}</td>
                    <td>${row.created_at}</td>
                </tr>
            `;
        });

        html += `
                        </tbody>
                    </table>
                </div>
            </div>
        `;

        resultsContainer.innerHTML = html;
        document.getElementById('searchSection').scrollIntoView({ behavior: 'smooth', block: 'start' });
    }

    // ============================================================
    // تابع بارگذاری دانشجویان یک روز خاص (برای تقویم)
    // ============================================================
    window.loadDailyMembers = function(date, element) {
        // حذف کلاس active از همه روزها
        document.querySelectorAll('.calendar-day.has-member').forEach(el => {
            el.style.background = '#eef2ff';
            el.style.color = '#4f46e5';
        });
        
        // فعال کردن روز انتخاب شده
        if (element) {
            element.style.background = '#4f46e5';
            element.style.color = 'white';
        }

        fetch(`reports_ajax.php?date=${encodeURIComponent(date)}&search_type=date`)
            .then(response => response.json())
            .then(data => {
                displayDailyMembers(data, date);
                // اسکرول به بخش نمایش اسامی
                document.getElementById('dailyMembersContainer').scrollIntoView({ behavior: 'smooth', block: 'start' });
            })
            .catch(error => {
                console.error('Error:', error);
                dailyContainer.innerHTML = '<div style="text-align:center; padding:10px; color:#ef4444;">خطا در دریافت اطلاعات</div>';
            });
    };

    // ============================================================
    // تابع نمایش دانشجویان یک روز خاص
    // ============================================================
    function displayDailyMembers(results, date) {
        if (results.length === 0) {
            dailyContainer.innerHTML = `
                <div style="text-align:center; padding:10px; color:#94a3b8;">
                    هیچ دانشجویی در تاریخ ${date} ثبت‌نام نکرده است
                </div>
            `;
            return;
        }

        let html = `
            <h6 style="font-weight:600; font-size:0.9rem;">📋 دانشجویان ثبت‌نام شده در تاریخ ${date}</h6>
            <div style="overflow-x:auto;">
                <table class="result-table">
                    <thead>
                        <tr>
                            <th>نام</th>
                            <th>کد ملی</th>
                            <th>مقطع</th>
                            <th>رشته</th>
                        </tr>
                    </thead>
                    <tbody>
        `;

        results.forEach(function(row) {
            html += `
                <tr>
                    <td><a href="/portal/admin/edit_member.php?id=${row.id}">${row.fullname}</a></td>
                    <td>${toPersianNumbers(row.national_code)}</td>
                    <td>${row.education_name || 'نامشخص'}</td>
                    <td>${row.study_field_name || 'نامشخص'}</td>
                </tr>
            `;
        });

        html += `
                    </tbody>
                </table>
            </div>
        `;

        dailyContainer.innerHTML = html;
    }
});
</script>

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