<?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: #ffffff;
    border-radius: 12px;
    padding: 20px 25px;
    margin-bottom: 25px;
    border: 1px solid #e9edf2;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
}
.dashboard-header .greeting h2 {
    font-weight: 600;
    margin: 0;
    font-size: 1.2rem;
    color: #0f172a;
}
.dashboard-header .greeting p {
    margin: 0;
    font-size: 0.85rem;
    color: #94a3b8;
}
.dashboard-header .stats-badge {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
}
.dashboard-header .stats-badge .badge-item {
    background: #f8fafc;
    padding: 6px 16px;
    border-radius: 8px;
    font-size: 0.8rem;
    display: flex;
    align-items: center;
    gap: 6px;
    color: #475569;
}
.dashboard-header .stats-badge .badge-item .num {
    font-weight: 600;
    color: #0f172a;
}

/* ===== کارت‌های اصلی ===== */
.stat-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 14px;
    margin-bottom: 25px;
}
.stat-card {
    background: #ffffff;
    border-radius: 12px;
    padding: 14px 16px;
    border: 1px solid #e9edf2;
    transition: all 0.2s ease;
}
.stat-card:hover {
    border-color: #cbd5e1;
}
.stat-card .stat-number {
    font-size: 1.5rem;
    font-weight: 600;
    color: #0f172a;
    line-height: 1.1;
}
.stat-card .stat-label {
    font-size: 0.75rem;
    color: #94a3b8;
    font-weight: 500;
}
.stat-card .stat-change {
    font-size: 0.6rem;
    font-weight: 600;
    padding: 1px 8px;
    border-radius: 12px;
    display: inline-block;
    margin-top: 2px;
}
.stat-card .stat-change.up { background: #dcfce7; color: #16a34a; }
.stat-card .stat-change.down { background: #fee2e2; color: #dc2626; }

/* ===== بخش آمار (طراحی سازمانی یکدست) ===== */
.stats-row {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    gap: 14px;
    margin-bottom: 25px;
}
.stats-row-2 {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 14px;
    margin-bottom: 25px;
}
.stats-col {
    background: #ffffff;
    border-radius: 12px;
    padding: 14px 16px;
    border: 1px solid #e9edf2;
}
.stats-col .col-title {
    font-size: 0.7rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.3px;
    color: #94a3b8;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    gap: 6px;
}
.stats-col .col-title i {
    font-size: 0.8rem;
}
.stats-col .col-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 4px 0;
    border-bottom: 1px solid #f1f5f9;
    font-size: 0.8rem;
}
.stats-col .col-item:last-child {
    border-bottom: none;
}
.stats-col .col-item .item-label {
    color: #475569;
}
.stats-col .col-item .item-value {
    font-weight: 600;
    color: #0f172a;
    background: #f8fafc;
    padding: 0 10px;
    border-radius: 10px;
    font-size: 0.75rem;
}

/* ===== جنسیت ===== */
.gender-row {
    display: flex;
    gap: 20px;
    align-items: center;
}
.gender-row .gender-item {
    display: flex;
    align-items: center;
    gap: 5px;
    font-size: 0.8rem;
    font-weight: 500;
    color: #0f172a;
}
.gender-row .gender-item .gender-icon {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.65rem;
    color: white;
}
.gender-row .gender-item .gender-icon.male { background: #4f46e5; }
.gender-row .gender-item .gender-icon.female { background: #ec4899; }

/* ===== جستجو ===== */
.search-section {
    background: #ffffff;
    border-radius: 12px;
    padding: 16px 18px;
    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: 8px;
    border: 1px solid #d1d5db;
    padding: 8px 14px;
    font-size: 0.85rem;
    flex: 1;
    min-width: 180px;
    background: #f8fafc;
}
.search-section .search-form input:focus {
    border-color: #4f46e5;
    outline: none;
    background: #ffffff;
}
.search-section .search-form button {
    background: #4f46e5;
    color: white;
    border: none;
    padding: 8px 22px;
    border-radius: 8px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s ease;
    font-size: 0.85rem;
}
.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.65rem;
    text-transform: uppercase;
    letter-spacing: 0.3px;
    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: #ffffff;
    border-radius: 12px;
    padding: 18px 20px;
    border: 1px solid #e9edf2;
    margin-top: 20px;
}
.calendar-grid {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 4px;
}
.calendar-weekday {
    text-align: center;
    font-weight: 600;
    font-size: 0.65rem;
    color: #94a3b8;
    padding: 6px 0;
}
.calendar-day {
    text-align: center;
    padding: 8px 0;
    border-radius: 8px;
    background: #f8fafc;
    font-size: 0.75rem;
    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.5rem;
    opacity: 0.7;
    display: block;
}

@media (max-width: 768px) {
    .stats-row {
        grid-template-columns: 1fr;
    }
    .stats-row-2 {
        grid-template-columns: 1fr;
    }
    .stat-grid {
        grid-template-columns: repeat(2, 1fr);
    }
    .dashboard-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }
}
</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="stats-row">
    <!-- جنسیت -->
    <div class="stats-col">
        <div class="col-title"><i class="bi bi-gender-ambiguous"></i> جنسیت</div>
        <div class="gender-row">
            <span class="gender-item">
                <span class="gender-icon male"><i class="bi bi-gender-male"></i></span>
                <?php echo toPersianNumbers($genderStats['مرد'] ?? 0); ?>
            </span>
            <span class="gender-item">
                <span class="gender-icon female"><i class="bi bi-gender-female"></i></span>
                <?php echo toPersianNumbers($genderStats['زن'] ?? 0); ?>
            </span>
        </div>
    </div>

    <!-- وضعیت تماس -->
    <div class="stats-col">
        <div class="col-title"><i class="bi bi-telephone"></i> وضعیت تماس</div>
        <?php foreach ($contactStats as $status => $count): ?>
            <div class="col-item">
                <span class="item-label"><?php echo $status; ?></span>
                <span class="item-value"><?php echo toPersianNumbers($count); ?></span>
            </div>
        <?php endforeach; ?>
    </div>

    <!-- وضعیت مدارک -->
    <div class="stats-col">
        <div class="col-title"><i class="bi bi-file-earmark-text"></i> وضعیت مدارک</div>
        <?php foreach ($documentStats as $status => $count): ?>
            <div class="col-item">
                <span class="item-label"><?php echo $status; ?></span>
                <span class="item-value"><?php echo toPersianNumbers($count); ?></span>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- ============================================================
   بخش آمار سازمانی (ردیف دوم: ۳ ستون)
   ============================================================ -->
<div class="stats-row">
    <!-- وضعیت پرداخت -->
    <div class="stats-col">
        <div class="col-title"><i class="bi bi-wallet2"></i> وضعیت پرداخت</div>
        <?php foreach ($paymentStats as $status => $count): ?>
            <div class="col-item">
                <span class="item-label"><?php echo $status; ?></span>
                <span class="item-value"><?php echo toPersianNumbers($count); ?></span>
            </div>
        <?php endforeach; ?>
    </div>

    <!-- رشته‌های تحصیلی -->
    <div class="stats-col">
        <div class="col-title"><i class="bi bi-book"></i> رشته‌های تحصیلی</div>
        <?php foreach ($fieldStats as $field): ?>
            <div class="col-item">
                <span class="item-label"><?php echo htmlspecialchars($field['name'] ?? 'نامشخص'); ?></span>
                <span class="item-value"><?php echo toPersianNumbers($field['count']); ?></span>
            </div>
        <?php endforeach; ?>
    </div>

    <!-- مقاطع تحصیلی -->
    <div class="stats-col">
        <div class="col-title"><i class="bi bi-mortarboard"></i> مقاطع تحصیلی</div>
        <?php foreach ($educationStats as $edu): ?>
            <div class="col-item">
                <span class="item-label"><?php echo htmlspecialchars($edu['name'] ?? 'نامشخص'); ?></span>
                <span class="item-value"><?php echo toPersianNumbers($edu['count']); ?></span>
            </div>
        <?php endforeach; ?>
    </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:0.95rem;"><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; font-size:0.85rem;"><?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 = $hasReg ? "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.85rem;">📋 دانشجویان ثبت‌نام شده در تاریخ <?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(() => fetchLiveResults(query), 300);
    });

    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(() => 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(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) {
        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 => {
                if (data.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.85rem;">📋 دانشجویان ثبت‌نام شده در تاریخ ${date}</h6><div style="overflow-x:auto;"><table class="result-table"><thead><tr><th>نام</th><th>کد ملی</th><th>مقطع</th><th>رشته</th></tr></thead><tbody>`;
                data.forEach(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;
                document.getElementById('dailyMembersContainer').scrollIntoView({ behavior: 'smooth', block: 'start' });
            })
            .catch(() => dailyContainer.innerHTML = '<div style="text-align:center; padding:10px; color:#ef4444;">خطا در دریافت اطلاعات</div>');
    };
});
</script>

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