<?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' && $_SESSION['user_level'] != 'expert' && $_SESSION['user_level'] != 'reporter')) {
    header('Location: ../index.php');
    exit;
}

// ========== دریافت پارامترهای فیلتر ==========
$search_name = $_GET['search_name'] ?? '';
$search_national = $_GET['search_national'] ?? '';
$search_field = $_GET['search_field'] ?? '';
$search_education = $_GET['search_education'] ?? '';
$search_gender = $_GET['search_gender'] ?? '';
$search_contact_status = $_GET['search_contact_status'] ?? '';
$search_document_status = $_GET['search_document_status'] ?? '';
$search_payment = $_GET['search_payment'] ?? '';
$search_from_date = $_GET['from_date'] ?? '';
$search_to_date = $_GET['to_date'] ?? '';
$status_filter = $_GET['status_filter'] ?? '';
$show_deleted = $_GET['show_deleted'] ?? '0';
$export_type = $_GET['export'] ?? '';

// ========== ساخت کوئری اصلی ==========
$query = "SELECT m.*, e.name as education_name, c.name as course_name, r.name as referral_name, u.fullname as created_by_name, rep.fullname as representative_name
          FROM members m 
          LEFT JOIN educations e ON m.education_id = e.id 
          LEFT JOIN courses c ON m.course_id = c.id
          LEFT JOIN referrals r ON m.referral_id = r.id 
          LEFT JOIN users u ON m.created_by = u.id
          LEFT JOIN users rep ON m.representative_id = rep.id
          WHERE 1=1";

$params = [];

// ============================================================
// فیلتر بر اساس نقش کاربر
// ============================================================
if ($_SESSION['user_level'] == 'expert') {
    $expertId = $_SESSION['user_id'];
    $query .= " AND (m.created_by = ? OR m.representative_id IN (SELECT id FROM users WHERE level = 'representative'))";
    $params[] = $expertId;
}

if ($_SESSION['user_level'] == 'representative') {
    $query .= " AND m.representative_id = ?";
    $params[] = $_SESSION['user_id'];
}

// ============================================================
// ادامه فیلترها
// ============================================================
if (!empty($status_filter)) {
    $query .= " AND m.status = ?";
    $params[] = $status_filter;
}

if ($show_deleted == '1') {
    $query .= " AND m.status = 'withdrawn'";
} else {
    $query .= " AND (m.status = 'active' OR m.status = 'completed')";
}

if (!empty($search_name)) {
    $query .= " AND m.fullname LIKE ?";
    $params[] = "%$search_name%";
}
if (!empty($search_national)) {
    $query .= " AND m.national_code = ?";
    $params[] = $search_national;
}
if (!empty($search_field)) {
    $query .= " AND c.name LIKE ?";
    $params[] = "%$search_field%";
}
if (!empty($search_education)) {
    $query .= " AND e.id = ?";
    $params[] = $search_education;
}
if (!empty($search_gender)) {
    $query .= " AND m.gender = ?";
    $params[] = $search_gender;
}
if (!empty($search_contact_status)) {
    $query .= " AND m.registration_status = ?";
    $params[] = $search_contact_status;
}
if (!empty($search_document_status)) {
    $query .= " AND m.document_status = ?";
    $params[] = $search_document_status;
}
if (!empty($search_payment)) {
    $query .= " AND m.payment_status = ?";
    $params[] = $search_payment;
}
if (!empty($search_from_date)) {
    $query .= " AND DATE(m.created_at) >= ?";
    $params[] = $search_from_date;
}
if (!empty($search_to_date)) {
    $query .= " AND DATE(m.created_at) <= ?";
    $params[] = $search_to_date;
}

$query .= " ORDER BY m.created_at DESC";
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$members = $stmt->fetchAll();

// ========== دریافت لیست‌ها برای فیلتر ==========
$educations = $pdo->query("SELECT * FROM educations ORDER BY sort_order")->fetchAll();
$contactStatusOptions = getContactStatusOptions();
$documentStatusOptions = getDocumentStatusOptions();
$paymentStatusOptions = getPaymentStatusOptions();

// ============================================================
// محاسبه آمارها
// ============================================================

// کل دانشجویان (به جز حذف‌شده‌ها)
$totalQuery = "SELECT COUNT(*) FROM members WHERE status != 'deleted'";
$totalStmt = $pdo->query($totalQuery);
$totalMembers = $totalStmt->fetchColumn();

// تأیید شده‌ها (فعال یا تکمیل شده)
$verifiedQuery = "SELECT COUNT(*) FROM members WHERE status IN ('active', 'completed')";
$verifiedStmt = $pdo->query($verifiedQuery);
$verifiedMembers = $verifiedStmt->fetchColumn();

// در انتظار پیگیری (وضعیت pending)
$pendingQuery = "SELECT COUNT(*) FROM members WHERE status = 'pending'";
$pendingStmt = $pdo->query($pendingQuery);
$pendingMembers = $pendingStmt->fetchColumn();

// ثبت‌نام امروز
$todayQuery = "SELECT COUNT(*) FROM members WHERE DATE(created_at) = CURDATE()";
$todayStmt = $pdo->query($todayQuery);
$todayRegistrations = $todayStmt->fetchColumn();

// ========== پرینت ==========
if ($export_type == 'print') {
    $printQuery = "SELECT m.*, e.name as education_name, c.name as course_name, r.name as referral_name
                   FROM members m 
                   LEFT JOIN educations e ON m.education_id = e.id 
                   LEFT JOIN courses c ON m.course_id = c.id
                   LEFT JOIN referrals r ON m.referral_id = r.id 
                   WHERE 1=1";
    
    $printParams = [];
    
    if ($_SESSION['user_level'] == 'expert') {
        $expertId = $_SESSION['user_id'];
        $printQuery .= " AND (m.created_by = ? OR m.representative_id IN (SELECT id FROM users WHERE level = 'representative'))";
        $printParams[] = $expertId;
    }
    
    if ($_SESSION['user_level'] == 'representative') {
        $printQuery .= " AND m.representative_id = ?";
        $printParams[] = $_SESSION['user_id'];
    }
    
    if ($show_deleted == '1') {
        $printQuery .= " AND m.status = 'withdrawn'";
    } else {
        $printQuery .= " AND (m.status = 'active' OR m.status = 'completed')";
    }
    
    if (!empty($search_name)) {
        $printQuery .= " AND m.fullname LIKE ?";
        $printParams[] = "%$search_name%";
    }
    if (!empty($search_national)) {
        $printQuery .= " AND m.national_code = ?";
        $printParams[] = $search_national;
    }
    if (!empty($search_field)) {
        $printQuery .= " AND c.name LIKE ?";
        $printParams[] = "%$search_field%";
    }
    if (!empty($search_education)) {
        $printQuery .= " AND e.id = ?";
        $printParams[] = $search_education;
    }
    if (!empty($search_gender)) {
        $printQuery .= " AND m.gender = ?";
        $printParams[] = $search_gender;
    }
    if (!empty($search_contact_status)) {
        $printQuery .= " AND m.registration_status = ?";
        $printParams[] = $search_contact_status;
    }
    if (!empty($search_document_status)) {
        $printQuery .= " AND m.document_status = ?";
        $printParams[] = $search_document_status;
    }
    if (!empty($search_payment)) {
        $printQuery .= " AND m.payment_status = ?";
        $printParams[] = $search_payment;
    }
    if (!empty($search_from_date)) {
        $printQuery .= " AND DATE(m.created_at) >= ?";
        $printParams[] = $search_from_date;
    }
    if (!empty($search_to_date)) {
        $printQuery .= " AND DATE(m.created_at) <= ?";
        $printParams[] = $search_to_date;
    }
    
    $printQuery .= " ORDER BY m.created_at DESC";
    $printStmt = $pdo->prepare($printQuery);
    $printStmt->execute($printParams);
    $printMembers = $printStmt->fetchAll();
    ?>
    <!DOCTYPE html>
    <html dir="rtl">
    <head>
        <meta charset="UTF-8">
        <title>پرینت گزارش</title>
        <style>
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body { font-family: 'Vazir', 'Tahoma', 'Arial', sans-serif; padding: 20px; background: #ffffff; color: #000000; font-size: 13px; }
            .print-header { text-align: center; margin-bottom: 20px; padding-bottom: 12px; border-bottom: 2px solid #000000; }
            .print-header h2 { font-size: 20px; font-weight: 700; color: #000000; margin: 0; }
            .print-header p { font-size: 13px; color: #333333; margin: 4px 0; }
            .print-header .sub { font-size: 12px; color: #555555; }
            table { width: 100%; border-collapse: collapse; font-size: 12px; margin-top: 10px; }
            table th { background: #000000 !important; color: #ffffff !important; padding: 8px 6px; border: 1px solid #000000; text-align: center; font-weight: 700; font-size: 12px; }
            table td { padding: 6px 6px; border: 1px solid #cccccc; text-align: center; color: #000000; background: #ffffff; }
            table tr:nth-child(even) td { background: #f5f5f5; }
            .badge-print { padding: 2px 8px; border-radius: 4px; font-size: 11px; display: inline-block; font-weight: 600; border: 1px solid #000000; }
            .badge-print.bg-success { background: #ffffff; color: #000000; }
            .badge-print.bg-danger { background: #ffffff; color: #000000; }
            .badge-print.bg-warning { background: #ffffff; color: #000000; }
            .badge-print.bg-info { background: #ffffff; color: #000000; }
            .badge-print.bg-secondary { background: #ffffff; color: #000000; }
            .badge-print.bg-primary { background: #000000; color: #ffffff; }
            .print-footer { text-align: center; margin-top: 20px; padding-top: 10px; border-top: 2px solid #000000; font-size: 11px; color: #555555; }
            .print-actions { text-align: center; margin-top: 25px; padding: 15px 0; border-top: 1px solid #dddddd; }
            .print-actions button { padding: 10px 35px; border: none; border-radius: 8px; font-size: 15px; font-weight: 600; cursor: pointer; margin: 0 8px; transition: all 0.2s ease; }
            .btn-print { background: #4f46e5; color: #ffffff; }
            .btn-print:hover { background: #4338ca; transform: scale(1.02); }
            .btn-close { background: #dc3545; color: #ffffff; }
            .btn-close:hover { background: #b91c1c; transform: scale(1.02); }
            @media print {
                .no-print { display: none !important; }
                body { padding: 10px; font-size: 11px; }
                table th { background: #000000 !important; color: #ffffff !important; -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
                table td { background: #ffffff !important; -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
                table tr:nth-child(even) td { background: #f5f5f5 !important; -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
                .badge-print { -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
                .badge-print.bg-primary { background: #000000 !important; color: #ffffff !important; }
                .print-footer { border-top-color: #000000; }
                .print-header { border-bottom-color: #000000; }
            }
        </style>
    </head>
    <body>
        <div class="print-header">
            <h2>📊 گزارش لیست دانشجویان</h2>
            <p>تاریخ چاپ: <?php echo getCurrentPersianDateTimeFa(); ?></p>
            <div class="sub">تعداد کل: <?php echo toPersianNumbers(count($printMembers)); ?> نفر</div>
        </div>
        <table>
            <thead>
                <tr>
                    <th style="width:5%;">#</th>
                    <th style="width:13%;">نام</th>
                    <th style="width:10%;">شماره تماس</th>
                    <th style="width:10%;">کد ملی</th>
                    <th style="width:10%;">مقطع</th>
                    <th style="width:12%;">رشته</th>
                    <th style="width:8%;">وضعیت کلی</th>
                    <th style="width:10%;">وضعیت تماس</th>
                    <th style="width:10%;">وضعیت مدارک</th>
                    <th style="width:9%;">وضعیت پرداخت</th>
                    <th style="width:10%;">معرف</th>
                </tr>
            </thead>
            <tbody>
                <?php $counter = 1; ?>
                <?php foreach ($printMembers as $row): ?>
                <tr>
                    <td><?php echo toPersianNumbers($counter++); ?></td>
                    <td><?php echo htmlspecialchars($row['fullname'] ?? '-'); ?></td>
                    <td><?php echo toPersianNumbers($row['phone'] ?? '-'); ?></td>
                    <td><?php echo toPersianNumbers($row['national_code'] ?? '-'); ?></td>
                    <td><?php echo htmlspecialchars($row['education_name'] ?? '-'); ?></td>
                    <td><?php echo htmlspecialchars($row['course_name'] ?? '-'); ?></td>
                    <td><span class="badge-print bg-<?php echo getStatusColor($row['status']); ?>"><?php echo getStatusLabel($row['status']); ?></span></td>
                    <td><span class="badge-print bg-<?php echo getContactStatusColor($row['registration_status']); ?>"><?php echo htmlspecialchars($row['registration_status'] ?? '-'); ?></span></td>
                    <td><span class="badge-print bg-<?php echo getDocumentStatusColor($row['document_status']); ?>"><?php echo htmlspecialchars($row['document_status'] ?? '-'); ?></span></td>
                    <td><span class="badge-print bg-<?php echo $row['payment_status'] == 'پرداخت شده' ? 'success' : ($row['payment_status'] == 'پرداخت نشده' ? 'danger' : ($row['payment_status'] == 'عودت وجه' ? 'warning' : 'info')); ?>"><?php echo htmlspecialchars($row['payment_status'] ?? '-'); ?></span></td>
                    <td><?php echo htmlspecialchars($row['referral_name'] ?? '-'); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <div class="print-footer">سامانه جامع مهدی - تمامی حقوق محفوظ است</div>
        <div class="print-actions no-print">
            <button onclick="window.print()" class="btn-print">🖨️ پرینت</button>
            <button onclick="window.close()" class="btn-close">❌ بستن</button>
        </div>
    </body>
    </html>
    <?php
    exit;
}
?>
<?php include '../includes/header.php'; ?>

<style>
.stat-card { background: white; border-radius: 14px; padding: 16px 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.6rem; font-weight: 700; color: #0f172a; line-height: 1.2; }
.stat-card .stat-label { color: #94a3b8; font-size: 0.8rem; font-weight: 500; }
.bg-gradient-purple { background: linear-gradient(135deg, #8b5cf6, #6d28d9); }
.bg-gradient-green { background: linear-gradient(135deg, #22c55e, #15803d); }
.bg-gradient-orange { background: linear-gradient(135deg, #f59e0b, #d97706); }
.bg-gradient-cyan { background: linear-gradient(135deg, #06b6d4, #0891b2); }
.search-section { background: #f8fafc; border-radius: 14px; padding: 20px; border: 1px solid #e9edf2; margin-bottom: 20px; }
.search-wrapper { position: relative; }
.search-wrapper .form-control { padding-right: 45px; border-radius: 10px; height: 50px; font-size: 1rem; }
.search-wrapper .search-icon { position: absolute; right: 15px; top: 50%; transform: translateY(-50%); color: #94a3b8; font-size: 1.2rem; }
.search-results { position: absolute; top: 100%; left: 0; right: 0; background: white; border: 1px solid #e9edf2; border-radius: 12px; box-shadow: 0 12px 40px rgba(0,0,0,0.1); max-height: 350px; overflow-y: auto; z-index: 1000; display: none; margin-top: 4px; }
.search-results.show { display: block; }
.search-result-item { padding: 12px 16px; border-bottom: 1px solid #f1f5f9; cursor: pointer; transition: background 0.2s ease; }
.search-result-item:hover { background: #f8fafc; }
.search-result-item:last-child { border-bottom: none; }
.search-result-empty { padding: 20px; text-align: center; color: #94a3b8; }
.filter-btn { padding: 6px 16px; border-radius: 20px; border: 1px solid #e9edf2; background: white; color: #475569; font-size: 0.8rem; transition: all 0.2s ease; cursor: pointer; }
.filter-btn:hover { border-color: #4f46e5; color: #4f46e5; }
.filter-btn.active { background: #4f46e5; color: white; border-color: #4f46e5; }
.loading-spinner { display: none; text-align: center; padding: 20px; }
.loading-spinner .spinner-border { width: 2rem; height: 2rem; color: #4f46e5; }
.table-modern { font-size: 0.85rem; }
.table-modern thead th { background: #f8fafc; color: #475569; font-weight: 600; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.3px; padding: 10px 14px; border-bottom: 2px solid #e9edf2; }
.table-modern tbody td { padding: 10px 14px; border-bottom: 1px solid #f1f5f9; vertical-align: middle; }
.table-modern tbody tr:hover { background: #f8fafc; }
.search-results::-webkit-scrollbar { width: 6px; }
.search-results::-webkit-scrollbar-track { background: #f1f5f9; border-radius: 10px; }
.search-results::-webkit-scrollbar-thumb { background: #d1d5db; border-radius: 10px; }
@media (max-width: 768px) { .stat-card .stat-number { font-size: 1.2rem; } .filter-btn { padding: 4px 12px; font-size: 0.7rem; } }
</style>

<!-- ============================================================
کارت‌های آماری
============================================================ -->
<div class="row g-3 mb-4">
    <div class="col-xl-3 col-lg-3 col-md-6"><div class="stat-card"><div class="d-flex align-items-center gap-3"><div class="stat-icon bg-gradient-purple"><i class="bi bi-people"></i></div><div><div class="stat-number"><?php echo toPersianNumbers(number_format($totalMembers)); ?></div><div class="stat-label">کل دانشجویان</div></div></div></div></div>
    <div class="col-xl-3 col-lg-3 col-md-6"><div class="stat-card"><div class="d-flex align-items-center gap-3"><div class="stat-icon bg-gradient-green"><i class="bi bi-check-circle"></i></div><div><div class="stat-number"><?php echo toPersianNumbers(number_format($verifiedMembers)); ?></div><div class="stat-label">تأیید شده</div></div></div></div></div>
    <div class="col-xl-3 col-lg-3 col-md-6"><div class="stat-card"><div class="d-flex align-items-center gap-3"><div class="stat-icon bg-gradient-orange"><i class="bi bi-clock"></i></div><div><div class="stat-number"><?php echo toPersianNumbers(number_format($pendingMembers)); ?></div><div class="stat-label">در انتظار پیگیری</div></div></div></div></div>
    <div class="col-xl-3 col-lg-3 col-md-6"><div class="stat-card"><div class="d-flex align-items-center gap-3"><div class="stat-icon bg-gradient-cyan"><i class="bi bi-calendar-plus"></i></div><div><div class="stat-number"><?php echo toPersianNumbers(number_format($todayRegistrations)); ?></div><div class="stat-label">ثبت‌نام امروز</div></div></div></div></div>
</div>

<!-- ============================================================
بخش جستجو
============================================================ -->
<div class="search-section" id="searchSection">
    <div class="row g-3">
        <div class="col-md-6">
            <div class="search-wrapper">
                <i class="bi bi-search search-icon"></i>
                <input type="text" id="liveSearch" class="form-control" placeholder="نام، کد ملی یا رشته را وارد کنید..." autocomplete="off">
                <div id="searchResults" class="search-results"></div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="d-flex flex-wrap gap-2 align-items-center h-100">
                <button class="filter-btn active" data-filter="all">🔍 همه</button>
                <button class="filter-btn" data-filter="active">✅ فعال</button>
                <button class="filter-btn" data-filter="pending">⏳ در انتظار</button>
                <button class="filter-btn" data-filter="verified">✔️ تأیید شده</button>
                <button class="filter-btn" data-filter="withdrawn">📤 انصرافی</button>
            </div>
        </div>
    </div>
</div>

<!-- ============================================================
اسپینر لودینگ
============================================================ -->
<div id="loadingSpinner" class="loading-spinner">
    <div class="spinner-border" role="status"><span class="visually-hidden">در حال بارگذاری...</span></div>
    <p class="text-muted mt-2">در حال جستجو...</p>
</div>

<!-- ============================================================
دکمه‌ها
============================================================ -->
<div class="row mb-3">
    <div class="col-md-12">
        <a href="?export=print&<?php echo http_build_query($_GET); ?>" class="btn btn-info" target="_blank"><i class="bi bi-printer"></i> پرینت</a>
        <a href="export_excel.php<?php echo !empty($_GET) ? '?' . http_build_query($_GET) : ''; ?>" class="btn btn-success"><i class="bi bi-file-earmark-excel"></i> خروجی اکسل</a>
        <button onclick="location.reload()" class="btn btn-secondary"><i class="bi bi-arrow-counterclockwise"></i> نمایش همه</button>
    </div>
</div>

<!-- ============================================================
جدول نتایج
============================================================ -->
<div class="card">
    <div class="card-header"><i class="bi bi-table"></i> لیست دانشجویان</div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-modern mb-0" id="resultsTable">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>نام</th>
                        <th>کد ملی</th>
                        <th>مقطع</th>
                        <th>رشته</th>
                        <th>وضعیت کلی</th>
                        <th>عملیات</th>
                    </tr>
                </thead>
                <tbody id="tableBody">
                    <?php
                    $initialQuery = "SELECT m.id, m.fullname, m.national_code, c.name as course_name, e.name as education_name, m.status
                                     FROM members m 
                                     LEFT JOIN courses c ON m.course_id = c.id
                                     LEFT JOIN educations e ON m.education_id = e.id
                                     WHERE m.status != 'deleted'";
                    $initialParams = [];
                    if ($_SESSION['user_level'] == 'expert') {
                        $initialQuery .= " AND (m.created_by = ? OR m.representative_id IN (SELECT id FROM users WHERE level = 'representative'))";
                        $initialParams[] = $_SESSION['user_id'];
                    }
                    if ($_SESSION['user_level'] == 'representative') {
                        $initialQuery .= " AND m.representative_id = ?";
                        $initialParams[] = $_SESSION['user_id'];
                    }
                    $initialQuery .= " ORDER BY m.created_at DESC LIMIT 50";
                    $initialStmt = $pdo->prepare($initialQuery);
                    $initialStmt->execute($initialParams);
                    $initialResults = $initialStmt->fetchAll();
                    $counter = 1;
                    foreach ($initialResults as $row):
                    ?>
                    <tr>
                        <td><?php echo toPersianNumbers($counter++); ?></td>
                        <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['course_name'] ?? 'نامشخص'); ?></td>
                        <td><span class="badge bg-<?php echo getStatusColor($row['status']); ?>"><?php echo getStatusLabel($row['status']); ?></span></td>
                        <td><a href="edit_member.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-primary"><i class="bi bi-pencil"></i></a></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script src="/portal/assets/js/reports.js"></script>
<?php include '../includes/footer.php'; ?>