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

$searchResults = [];
$searchQuery = $_GET['search'] ?? '';
$searchType = $_GET['search_type'] ?? 'name';
if (!empty($searchQuery)) {
    $sql = "SELECT m.*, e.name as education_name, r.name as referral_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 LEFT JOIN referrals r ON m.referral_id = r.id WHERE 1=1";
    $params = [];
    if ($searchType == 'name') { $sql .= " AND m.fullname LIKE ?"; $params[] = "%$searchQuery%"; }
    elseif ($searchType == 'national_code') { $sql .= " AND m.national_code = ?"; $params[] = $searchQuery; }
    elseif ($searchType == 'field') { $sql .= " AND sf.name LIKE ?"; $params[] = "%$searchQuery%"; }
    elseif ($searchType == 'education') { $sql .= " AND e.name LIKE ?"; $params[] = "%$searchQuery%"; }
    $sql .= " ORDER BY m.created_at DESC";
    $stmt = $pdo->prepare($sql); $stmt->execute($params); $searchResults = $stmt->fetchAll();
}

$selectedDate = $_GET['date'] ?? '';
$dailyMembers = [];
if (!empty($selectedDate)) {
    $stmt = $pdo->prepare("SELECT m.*, e.name as education_name, r.name as referral_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 LEFT JOIN referrals r ON m.referral_id = r.id WHERE DATE(m.created_at) = ? ORDER BY m.created_at DESC");
    $stmt->execute([$selectedDate]); $dailyMembers = $stmt->fetchAll();
}
$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);

function getPersianMonth($monthNumber) {
    $months = ['01'=>'فروردین','02'=>'اردیبهشت','03'=>'خرداد','04'=>'تیر','05'=>'مرداد','06'=>'شهریور','07'=>'مهر','08'=>'آبان','09'=>'آذر','10'=>'دی','11'=>'بهمن','12'=>'اسفند'];
    return $months[$monthNumber] ?? $monthNumber;
}
function getPersianMonthForStat($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-card { border-radius: 15px; padding: 20px; margin-bottom: 20px; background: white; box-shadow: 0 1px 3px rgba(0,0,0,0.04); border: 1px solid #e9edf2; }
.dashboard-card h3 { font-size: 2.5rem; margin: 0; font-weight: 700; }
.dashboard-card .label { color: #94a3b8; font-size: 0.9rem; }
.stat-icon { font-size: 2rem; margin-right: 10px; }
.calendar-container { background: #ffffff; border: 1px solid #e9edf2; border-radius: 12px; padding: 20px; }
.calendar-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 6px; }
.calendar-weekday { text-align: center; font-weight: 600; font-size: 0.8rem; color: #94a3b8; padding: 8px 0; }
.calendar-day { text-align: center; padding: 8px 0; border-radius: 8px; background: #f8fafc; border: 1px solid transparent; transition: all 0.2s ease; cursor: default; }
.calendar-day.has-member { background: #4f46e5; color: #ffffff; cursor: pointer; }
.calendar-day.today { border-color: #4f46e5; }
.calendar-day .day-count { font-size: 0.65rem; opacity: 0.8; }
</style>

<!-- ===== هدر داشبورد ===== -->
<div class="dashboard-header" style="background: linear-gradient(135deg, #4f46e5, #7c3aed); border-radius: 16px; padding: 20px 25px; color: white; margin-bottom: 25px;">
    <div class="row align-items-center">
        <div class="col-md-8">
            <h2 style="font-weight: 700; margin: 0; font-size: 1.5rem;">👋 خوش آمدید، <?php echo htmlspecialchars($_SESSION['user_name']); ?></h2>
            <p style="opacity: 0.85; margin: 0; font-size: 0.9rem;">مدیریت و نظارت بر سیستم ثبت‌نام</p>
        </div>
        <div class="col-md-4 text-end">
            <span class="badge" style="background: rgba(255,255,255,0.2); color: white; font-size: 0.85rem; padding: 6px 14px;">📅 <?php echo getCurrentPersianDateTimeFa(); ?></span>
            <span class="badge ms-2" style="background: rgba(255,255,255,0.2); color: white; font-size: 0.85rem; padding: 6px 14px;">👥 <?php echo toPersianNumbers(number_format($totalMembers)); ?> دانشجو</span>
        </div>
    </div>
</div>

<!-- ===== کارت‌های آمار ===== -->
<div class="row">
    <div class="col-md-3"><div class="dashboard-card text-center"><div class="stat-icon">👥</div><h3><?php echo toPersianNumbers(number_format($totalMembers)); ?></h3><div class="label">تعداد کل دانشجویان</div></div></div>
    <div class="col-md-3"><div class="dashboard-card text-center"><div class="stat-icon">✅</div><h3><?php echo toPersianNumbers(number_format($activeMembers)); ?></h3><div class="label">فعال</div></div></div>
    <div class="col-md-3"><div class="dashboard-card text-center"><div class="stat-icon">🎓</div><h3><?php echo toPersianNumbers(number_format($completedMembers)); ?></h3><div class="label">تکمیل شده</div></div></div>
    <div class="col-md-3"><div class="dashboard-card text-center"><div class="stat-icon">📤</div><h3><?php echo toPersianNumbers(number_format($withdrawnMembers)); ?></h3><div class="label">انصرافی</div></div></div>
</div>

<div class="row mt-4">
    <div class="col-md-6"><div class="dashboard-card"><h5>👫 تفکیک جنسیت</h5><table class="table table-sm"><tr><td>مرد</td><td><span class="badge bg-primary"><?php echo toPersianNumbers($genderStats['مرد'] ?? 0); ?></span></td></tr><tr><td>زن</td><td><span class="badge bg-danger"><?php echo toPersianNumbers($genderStats['زن'] ?? 0); ?></span></td></tr></table></div></div>
    <div class="col-md-6"><div class="dashboard-card"><h5>💰 تفکیک وضعیت پرداخت</h5><table class="table table-sm"><tr><td>پرداخت شده</td><td><span class="badge bg-success"><?php echo toPersianNumbers($paymentStats['پرداخت شده'] ?? 0); ?></span></td></tr><tr><td>پرداخت نشده</td><td><span class="badge bg-danger"><?php echo toPersianNumbers($paymentStats['پرداخت نشده'] ?? 0); ?></span></td></tr><tr><td>در انتظار پرداخت</td><td><span class="badge bg-warning"><?php echo toPersianNumbers($paymentStats['در انتظار پرداخت'] ?? 0); ?></span></td></tr><tr><td>عودت وجه</td><td><span class="badge bg-info"><?php echo toPersianNumbers($paymentStats['عودت وجه'] ?? 0); ?></span></td></tr></table></div></div>
</div>

<!-- ===== جستجو ===== -->
<div class="row mt-4">
    <div class="col-md-12"><div class="dashboard-card"><h5>🔍 جستجوی پیشرفته</h5><form method="GET" class="row"><div class="col-md-6"><input type="text" name="search" class="form-control" placeholder="متن جستجو..." value="<?php echo htmlspecialchars($searchQuery); ?>"></div><div class="col-md-3"><select name="search_type" class="form-control"><option value="name" <?php echo $searchType=='name'?'selected':''; ?>>نام</option><option value="national_code" <?php echo $searchType=='national_code'?'selected':''; ?>>کد ملی</option><option value="field" <?php echo $searchType=='field'?'selected':''; ?>>رشته</option><option value="education" <?php echo $searchType=='education'?'selected':''; ?>>مقطع</option></select></div><div class="col-md-3"><button type="submit" class="btn btn-pastel w-100">🔍 جستجو</button></div></form>
    <?php if (!empty($searchQuery) && !empty($searchResults)): ?><div class="mt-3"><h6>نتایج جستجو (<?php echo toPersianNumbers(count($searchResults)); ?> نفر)</h6><table class="table table-pastel table-sm"><thead><tr><th>نام</th><th>کد ملی</th><th>مقطع</th><th>رشته</th><th>تاریخ ثبت</th></tr></thead><tbody><?php foreach($searchResults as $row): ?><tr><td><?php echo htmlspecialchars($row['fullname']); ?></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><?php elseif (!empty($searchQuery)): ?><div class="alert alert-info mt-3">هیچ نتیجه‌ای یافت نشد</div><?php endif; ?></div></div>
</div>

<!-- ===== تفکیک مقاطع و رشته‌ها ===== -->
<div class="row mt-4">
    <div class="col-md-6"><div class="dashboard-card"><h5>📚 تفکیک مقاطع</h5><table class="table table-sm"><?php foreach($educationStats as $row): ?><tr><td><?php echo htmlspecialchars($row['name'] ?? 'نامشخص'); ?></td><td><span class="badge bg-primary"><?php echo toPersianNumbers($row['count']); ?></span></td></tr><?php endforeach; ?></table></div></div>
    <div class="col-md-6"><div class="dashboard-card"><h5>🎓 تفکیک رشته‌ها</h5><table class="table table-sm"><?php foreach($fieldStats as $row): ?><tr><td><?php echo htmlspecialchars($row['name'] ?? 'نامشخص'); ?></td><td><span class="badge bg-success"><?php echo toPersianNumbers($row['count']); ?></span></td></tr><?php endforeach; ?></table></div></div>
</div>

<!-- ===== تقویم ===== -->
<div class="row mt-4">
    <div class="col-md-12">
        <div class="calendar-container">
            <div class="calendar-header d-flex justify-content-between align-items-center mb-3"><h5>📅 تقویم ثبت‌نام ماهانه</h5><div></div></div>
            <div class="calendar-grid">
                <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 $currentTimestamp = time(); $currentYear = date('Y', $currentTimestamp) - 621; $currentMonth = date('m', $currentTimestamp); $currentDay = date('d', $currentTimestamp); $selectedMonth = $_GET['month'] ?? $currentMonth; $selectedYear = $_GET['year'] ?? $currentYear; $daysInMonth = 31; if ($selectedMonth > 6) $daysInMonth = 30; if ($selectedMonth == 12) $daysInMonth = ($selectedYear % 4 == 0) ? 30 : 29; $firstDayOfMonth = 0; for ($i = 0; $i < $firstDayOfMonth; $i++) echo '<div class="calendar-day empty"></div>'; 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; echo '<div class="calendar-day ' . ($isToday ? 'today' : '') . ($hasReg ? ' has-member' : '') . '" onclick="location.href=\'?date=' . sprintf("%04d-%02d-%02d", $selectedYear + 621, $selectedMonth, $day) . '\'" title="' . $day . ' ' . getPersianMonth(str_pad($selectedMonth, 2, '0', STR_PAD_LEFT)) . ' - ' . toPersianNumbers($count) . ' نفر"><span class="day-number">' . toPersianNumbers($day) . '</span>' . ($hasReg ? '<span class="day-count">' . toPersianNumbers($count) . ' نفر</span>' : '') . '</div>'; } ?>
            </div>
            <?php if (!empty($selectedDate)): ?><div class="mt-4"><h6>📋 دانشجویان ثبت‌نام شده در تاریخ <?php echo convertToPersianDateOnlyFa($selectedDate); ?></h6><div class="table-responsive"><table class="table table-pastel table-sm"><thead><tr><th>نام</th><th>کد ملی</th><th>مقطع</th><th>رشته</th></tr></thead><tbody><?php if(count($dailyMembers) > 0): foreach($dailyMembers as $row): ?><tr><td><?php echo htmlspecialchars($row['fullname']); ?></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; else: ?><tr><td colspan="4">هیچ دانشجویی در این تاریخ ثبت‌نام نکرده است</td></tr><?php endif; ?></tbody></table></div></div><?php endif; ?>
        </div>
    </div>
</div>

<!-- ===== آمار ماهانه ===== -->
<div class="row mt-4">
    <div class="col-md-12"><div class="dashboard-card"><h5>📊 آمار ماهانه ثبت‌نام</h5><table class="table table-sm"><thead><tr><th>ماه</th><th>تعداد ثبت‌نام</th></tr></thead><tbody><?php foreach($monthlyStats as $row): $monthParts = explode('-', $row['month']); $year = $monthParts[0]; $month = $monthParts[1]; $persianYear = $year - 621; ?><tr><td><?php echo getPersianMonthForStat($month) . ' ' . toPersianNumbers($persianYear); ?></td><td><span class="badge bg-info"><?php echo toPersianNumbers($row['count']); ?></span></td></tr><?php endforeach; ?></tbody></table></div></div>
</div>

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