<?php
// /admission3333/card_printing_dashboard.php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require 'db.php';
require 'helpers.php';
require_committee(); // Using same authentication as committee

$committeeId   = (int)($_SESSION['committee_id'] ?? 0);
$committeeName = (string)($_SESSION['committee_name'] ?? '');
$canAll        = (bool)($_SESSION['committee_can_all'] ?? false);
$scopeCollege  = isset($_SESSION['committee_college_id']) ? (int)$_SESSION['committee_college_id'] : null;

$mysqli1->set_charset('utf8mb4');
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

/* ---------- Filter Parameters ---------- */
$college_id = $_GET['college_id'] ?? '';
$section_id = $_GET['section_id'] ?? '';
$batch_id = $_GET['batch_id'] ?? '';
$program_id = $_GET['program_id'] ?? ''; // NEW: Program filter
$show_all = isset($_GET['show_all']) && $_GET['show_all'] === '1';
$search_query = trim($_GET['search'] ?? '');

/* ---------- Scope WHERE - For single college system ---------- */
$where = " WHERE 1=1 ";
$types = ''; 
$params = [];

if (!$canAll && $scopeCollege !== null) {
    $where .= " AND s.college_id = ? ";
    $types .= 'i'; 
    $params[] = $scopeCollege;
    // Auto-set the college filter if user has scope restriction
    if (!$college_id) {
        $college_id = $scopeCollege;
    }
} elseif (!$canAll && $scopeCollege === null) {
    $where .= " AND 1=0 ";
}

// Apply college filter
if ($college_id !== '' && is_numeric($college_id)) {
    $where .= " AND s.college_id = ? ";
    $types .= 'i';
    $params[] = (int)$college_id;
}

// Apply section filter
if ($section_id !== '' && is_numeric($section_id)) {
    $where .= " AND s.section_id = ? ";
    $types .= 'i';
    $params[] = (int)$section_id;
}

// Apply batch filter
if ($batch_id !== '' && is_numeric($batch_id)) {
    $where .= " AND s.batch_id = ? ";
    $types .= 'i';
    $params[] = (int)$batch_id;
}

// Apply program filter - CHECK STRUCTURE FIRST
// We'll handle this dynamically based on database structure

if ($search_query !== '') {
    $where .= " AND (s.student_id LIKE ? OR s.student_name LIKE ? OR s.student_name_eng LIKE ?) ";
    $types .= 'sss';
    $search_param = '%' . $search_query . '%';
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
}

// Only show accepted students for card printing
$where .= " AND s.interview_status = 'accepted' AND s.medically_fit = 1 ";

/* ---------- Get Colleges, Sections, Batches, Programs for Filters ---------- */
// Colleges
$colleges = [];
$college_stmt = $mysqli1->prepare("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name");
$college_stmt->execute();
$colleges = $college_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$college_stmt->close();

// Sections - based on selected college
$sections = [];
if ($college_id && !empty($college_id)) {
    $section_stmt = $mysqli1->prepare("SELECT id, name FROM sections WHERE parent = ? AND deleted_at IS NULL ORDER BY name");
    $section_stmt->bind_param('i', $college_id);
    $section_stmt->execute();
    $sections = $section_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $section_stmt->close();
} else {
    // Get all sections if no college selected
    $section_stmt = $mysqli1->prepare("SELECT id, name FROM sections WHERE deleted_at IS NULL ORDER BY name");
    $section_stmt->execute();
    $sections = $section_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $section_stmt->close();
}

// Batches
$batches = [];
$batch_stmt = $mysqli1->prepare("SELECT id, value FROM batches WHERE deleted_at IS NULL ORDER BY value DESC");
$batch_stmt->execute();
$batches = $batch_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$batch_stmt->close();

// Programs - Check if programs table exists and get data
$programs = [];
$hasProgramsTable = false;
$hasProgramInStudents = false;

try {
    // Check if programs table exists
    $checkTable = $mysqli1->query("SHOW TABLES LIKE 'programs'");
    if ($checkTable->num_rows > 0) {
        $hasProgramsTable = true;
        $program_stmt = $mysqli1->prepare("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name");
        $program_stmt->execute();
        $programs = $program_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $program_stmt->close();
    }
    
    // Check if program_id exists in students table
    $checkColumn = $mysqli1->query("SHOW COLUMNS FROM students LIKE 'program_id'");
    $hasProgramInStudents = $checkColumn->num_rows > 0;
    
    // Check if program_id exists in batches table
    $checkBatchColumn = $mysqli1->query("SHOW COLUMNS FROM batches LIKE 'program_id'");
    $hasProgramInBatches = $checkBatchColumn->num_rows > 0;
    
} catch (Exception $e) {
    // Ignore errors, just don't show program filter
    $hasProgramsTable = false;
}

/* ---------- Get Students for Card Printing ---------- */
$students = [];
$student_count = 0;

if ($show_all || $college_id !== '' || $section_id !== '' || $batch_id !== '' || $program_id !== '' || $search_query !== '') {
    // Build dynamic SQL based on available tables
    $selectFields = "
        SELECT 
            s.student_id, 
            s.student_name, 
            s.student_name_eng,
            s.gender,
            s.national_id,
            s.phone_number,
            s.email,
            s.college_id,
            s.section_id,
            s.batch_id,
            s.interview_status,
            s.medically_fit,
            s.profile_completed,
            sec.name AS section_name,
            b.value AS batch_name,
            c.name AS college_name
    ";
    
    $fromClause = "
        FROM students s
        LEFT JOIN sections sec ON sec.id = s.section_id
        LEFT JOIN batches b ON b.id = s.batch_id
        LEFT JOIN colleges c ON c.id = s.college_id
    ";
    
    // Add program join if available
    if ($hasProgramInStudents) {
        $selectFields .= ", p.name AS program_name";
        $fromClause .= " LEFT JOIN programs p ON p.id = s.program_id";
    } elseif ($hasProgramInBatches) {
        $selectFields .= ", p.name AS program_name";
        $fromClause .= " LEFT JOIN programs p ON p.id = b.program_id";
    } else {
        $selectFields .= ", '' AS program_name";
    }
    
    // Handle program filter
    $programWhere = "";
    $programTypes = "";
    $programParams = [];
    
    if ($program_id !== '' && is_numeric($program_id) && $hasProgramsTable) {
        if ($hasProgramInStudents) {
            $programWhere = " AND s.program_id = ? ";
        } elseif ($hasProgramInBatches) {
            $programWhere = " AND b.program_id = ? ";
        }
        
        if ($programWhere) {
            $programTypes = 'i';
            $programParams[] = (int)$program_id;
        }
    }
    
    $sqlStudents = $selectFields . $fromClause . $where . $programWhere . " ORDER BY s.student_id DESC LIMIT 1000";
    
    // Prepare and execute statement
    $stmt = $mysqli1->prepare($sqlStudents);
    
    if ($stmt) {
        // Bind all parameters
        $allParams = array_merge($params, $programParams);
        $allTypes = $types . $programTypes;
        
        if ($allTypes !== '') {
            $stmt->bind_param($allTypes, ...$allParams);
        }
        
        $stmt->execute();
        $students = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $student_count = count($students);
        $stmt->close();
    } else {
        // Fallback query without program
        $fallbackSql = "
            SELECT 
                s.student_id, 
                s.student_name, 
                s.student_name_eng,
                s.gender,
                s.national_id,
                s.phone_number,
                s.email,
                s.college_id,
                s.section_id,
                s.batch_id,
                s.interview_status,
                s.medically_fit,
                s.profile_completed,
                sec.name AS section_name,
                b.value AS batch_name,
                c.name AS college_name,
                '' AS program_name
            FROM students s
            LEFT JOIN sections sec ON sec.id = s.section_id
            LEFT JOIN batches b ON b.id = s.batch_id
            LEFT JOIN colleges c ON c.id = s.college_id
            $where
            ORDER BY s.student_id DESC
            LIMIT 1000
        ";
        
        $fallbackStmt = $mysqli1->prepare($fallbackSql);
        if ($types !== '') {
            $fallbackStmt->bind_param($types, ...$params);
        }
        $fallbackStmt->execute();
        $students = $fallbackStmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $student_count = count($students);
        $fallbackStmt->close();
    }
}

/* ---------- UI ---------- */
include 'header.php';
?>
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">

<style>
    body, h1,h2,h3,h4,h5,h6, p, a, button, label { 
        font-family: 'Cairo', system-ui, -apple-system, sans-serif !important; 
    }
    .dash-card {
        border: 1px solid #e5e7eb;
        border-radius: 16px;
        padding: 20px;
        background: #fff;
        box-shadow: 0 10px 24px rgba(0,0,0,.06);
        margin-bottom: 20px;
    }
    .filter-card {
        background: linear-gradient(135deg, #f8f9fa, #e9ecef);
    }
    .btn-primary { 
        background: linear-gradient(135deg, #f39c12, #e67e22);
        border: none;
        font-weight: 600;
    }
    .btn-primary:hover {
        background: linear-gradient(135deg, #e67e22, #f39c12);
        transform: translateY(-1px);
    }
    .btn-success { 
        background: linear-gradient(135deg, #27ae60, #2ecc71);
        border: none;
        font-weight: 600;
    }
    .btn-success:hover {
        background: linear-gradient(135deg, #2ecc71, #27ae60);
        transform: translateY(-1px);
    }
    .btn-info {
        background: linear-gradient(135deg, #3498db, #2980b9);
        border: none;
        font-weight: 600;
    }
    .btn-info:hover {
        background: linear-gradient(135deg, #2980b9, #3498db);
        transform: translateY(-1px);
    }
    .chip {
        display: inline-block;
        padding: 0.2rem 0.5rem;
        border-radius: 999px;
        font-size: 0.85rem;
        font-weight: 600;
    }
    .chip.green { background: #d1fae5; color: #065f46; }
    .chip.blue { background: #dbeafe; color: #1e3a8a; }
    .chip.purple { background: #e9d5ff; color: #7e22ce; }
    .chip.orange { background: #fed7aa; color: #9a3412; }
    .chip.red { background: #fecaca; color: #991b1b; }
    .chip.teal { background: #99f6e4; color: #115e59; }
    .student-card {
        border: 2px solid #e5e7eb;
        border-radius: 12px;
        padding: 15px;
        margin-bottom: 15px;
        background: white;
        transition: all 0.3s ease;
    }
    .student-card:hover {
        border-color: #f39c12;
        box-shadow: 0 5px 15px rgba(243, 156, 18, 0.1);
    }
    .student-card.selected {
        border-color: #27ae60;
        background: #f0f9ff;
    }
    .print-section {
        position: sticky;
        bottom: 0;
        background: white;
        padding: 15px;
        border-top: 2px solid #e5e7eb;
        margin-top: 20px;
        box-shadow: 0 -5px 15px rgba(0,0,0,0.05);
    }
    .form-select, .form-control {
        border-radius: 10px;
        border: 1px solid #d1d5db;
        padding: 10px;
    }
    .form-select:focus, .form-control:focus {
        border-color: #f39c12;
        box-shadow: 0 0 0 0.2rem rgba(243, 156, 18, 0.25);
    }
    .status-badge {
        font-size: 0.75rem;
        padding: 0.2rem 0.5rem;
        border-radius: 4px;
    }
    .badge-accepted { background: #d1fae5; color: #065f46; }
    .badge-medical { background: #dbeafe; color: #1e3a8a; }
    .badge-pending { background: #fef3c7; color: #92400e; }
    .badge-rejected { background: #fecaca; color: #991b1b; }
    .filter-row {
        margin-bottom: 15px;
    }
    .student-info-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 10px;
    }
    .database-info {
        background: #e8f4fd;
        border-left: 4px solid #3498db;
        padding: 10px;
        border-radius: 8px;
        margin-bottom: 15px;
    }
</style>

<div class="container py-4">
    <!-- Header -->
    <div class="d-flex align-items-center mb-4">
        <div>
            <h3 class="fw-bold mb-1">نظام طباعة البطاقات</h3>
            <p class="text-muted mb-0">طباعة بطاقات الطلاب المقبولين واللائقين طبياً</p>
        </div>
        <div class="ms-auto">
            <span class="chip orange">مرحباً، <?= e($committeeName ?: 'مسؤول الطباعة') ?></span>
            <a href="committee_dashboard.php" class="btn btn-sm btn-outline-secondary ms-2">لوحة التحكم</a>
        </div>
    </div>

    <!-- Database Structure Info -->
    <?php if (!$hasProgramsTable): ?>
    <div class="database-info">
        <h6><i class="fas fa-database me-2"></i>معلومات قاعدة البيانات:</h6>
        <p class="mb-0">
            جدول البرامج غير متوفر. فلتر البرنامج قد لا يعمل بشكل كامل.
            <?php if ($hasProgramInStudents): ?>
                <span class="badge bg-success ms-2">برنامج موجود في جدول الطلاب</span>
            <?php elseif ($hasProgramInBatches): ?>
                <span class="badge bg-info ms-2">برنامج موجود في جدول الدفعات</span>
            <?php else: ?>
                <span class="badge bg-warning ms-2">برنامج غير متوفر</span>
            <?php endif; ?>
        </p>
    </div>
    <?php endif; ?>

    <!-- Filters Card -->
    <div class="dash-card filter-card">
        <h5 class="fw-bold mb-3"><i class="fas fa-filter me-2"></i>تصفية الطلاب</h5>
        
        <form method="get" class="row g-3">
            <!-- College Filter -->
            <div class="col-md-3">
                <label class="form-label fw-semibold"><i class="fas fa-university me-1"></i> الكلية</label>
                <select name="college_id" class="form-select" id="collegeSelect" onchange="this.form.submit()">
                    <option value="">جميع الكليات</option>
                    <?php foreach ($colleges as $college): ?>
                        <?php 
                        // Don't show college filter if user has scope restriction
                        if (!$canAll && $scopeCollege !== null && $college['id'] != $scopeCollege) {
                            continue;
                        }
                        ?>
                        <option value="<?= $college['id'] ?>" <?= $college_id == $college['id'] ? 'selected' : '' ?>>
                            <?= e($college['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <!-- Section Filter -->
            <div class="col-md-3">
                <label class="form-label fw-semibold"><i class="fas fa-layer-group me-1"></i> القسم/الشعبة</label>
                <select name="section_id" class="form-select" id="sectionSelect" <?= !$college_id ? 'disabled' : '' ?>>
                    <option value="">جميع الأقسام</option>
                    <?php foreach ($sections as $section): ?>
                        <option value="<?= $section['id'] ?>" <?= $section_id == $section['id'] ? 'selected' : '' ?>>
                            <?= e($section['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <?php if (!$college_id): ?>
                    <small class="text-muted"><i class="fas fa-info-circle me-1"></i>الرجاء اختيار كلية أولاً</small>
                <?php endif; ?>
            </div>

            <!-- Batch Filter -->
            <div class="col-md-3">
                <label class="form-label fw-semibold"><i class="fas fa-users me-1"></i> الدفعة</label>
                <select name="batch_id" class="form-select">
                    <option value="">جميع الدفعات</option>
                    <?php foreach ($batches as $batch): ?>
                        <option value="<?= $batch['id'] ?>" <?= $batch_id == $batch['id'] ? 'selected' : '' ?>>
                            <?= e($batch['value']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <!-- Program Filter - Conditionally shown -->
            <?php if ($hasProgramsTable || $hasProgramInStudents || $hasProgramInBatches): ?>
            <div class="col-md-3">
                <label class="form-label fw-semibold"><i class="fas fa-graduation-cap me-1"></i> البرنامج</label>
                <select name="program_id" class="form-select">
                    <option value="">جميع البرامج</option>
                    <?php foreach ($programs as $program): ?>
                        <option value="<?= $program['id'] ?>" <?= $program_id == $program['id'] ? 'selected' : '' ?>>
                            <?= e($program['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <?php if (!$hasProgramsTable && ($hasProgramInStudents || $hasProgramInBatches)): ?>
                    <small class="text-muted"><i class="fas fa-exclamation-triangle me-1"></i>فلتر البرنامج محدود</small>
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <!-- Search -->
            <div class="col-md-<?= ($hasProgramsTable || $hasProgramInStudents || $hasProgramInBatches) ? '6' : '9' ?>">
                <label class="form-label fw-semibold"><i class="fas fa-search me-1"></i> بحث</label>
                <div class="input-group">
                    <span class="input-group-text"><i class="fas fa-user"></i></span>
                    <input type="text" name="search" class="form-control" placeholder="ابحث بالاسم أو الرقم الجامعي..." 
                           value="<?= e($search_query) ?>">
                </div>
            </div>

            <!-- Status Filters -->
            <div class="col-md-3">
                <label class="form-label fw-semibold"><i class="fas fa-check-circle me-1"></i> حالة الطالب</label>
                <div class="d-flex gap-2">
                    <span class="badge badge-accepted">✓ مقبول</span>
                    <span class="badge badge-medical">⚕️ لائق طبياً</span>
                    <span class="badge badge-pending">⏳ قيد المراجعة</span>
                </div>
                <small class="text-muted">(يتم عرض المقبولين واللائقين طبياً فقط)</small>
            </div>

            <!-- Action Buttons -->
            <div class="col-12">
                <div class="d-flex gap-2">
                    <button type="submit" name="show_all" value="1" class="btn btn-primary">
                        <i class="fas fa-eye me-1"></i> عرض الطلاب
                    </button>
                    <button type="submit" class="btn btn-outline-primary">
                        <i class="fas fa-sync-alt me-1"></i> تطبيق التصفية
                    </button>
                    <a href="card_printing_dashboard.php" class="btn btn-outline-danger">
                        <i class="fas fa-times me-1"></i> مسح الكل
                    </a>
                    <div class="ms-auto">
                        <button type="button" class="btn btn-outline-info" onclick="showPrintHelp()">
                            <i class="fas fa-question-circle me-1"></i> مساعدة
                        </button>
                        <?php if (!$hasProgramsTable): ?>
                        <button type="button" class="btn btn-outline-warning" onclick="showDatabaseHelp()">
                            <i class="fas fa-database me-1"></i> قاعدة البيانات
                        </button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <!-- Results Summary -->
    <?php if ($show_all || $student_count > 0): ?>
    <div class="dash-card">
        <div class="d-flex align-items-center justify-content-between mb-3">
            <h5 class="fw-bold mb-0">
                <i class="fas fa-list me-2"></i>نتائج البحث 
                <span class="badge bg-primary fs-6"><?= number_format($student_count) ?> طالب</span>
            </h5>
            <div class="d-flex gap-2">
                <button type="button" class="btn btn-sm btn-outline-primary" onclick="selectAllStudents()">
                    <i class="fas fa-check-square me-1"></i>تحديد الكل
                </button>
                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="deselectAllStudents()">
                    <i class="fas fa-times-circle me-1"></i>إلغاء الكل
                </button>
                <button type="button" class="btn btn-sm btn-outline-success" onclick="exportSelectedStudents()">
                    <i class="fas fa-file-export me-1"></i>تصدير المحدد
                </button>
            </div>
        </div>

        <!-- Quick Stats -->
        <?php if ($student_count > 0): ?>
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card border-0 bg-light">
                    <div class="card-body text-center">
                        <h6 class="text-muted mb-1">طلاب مكتملي الملف</h6>
                        <h4 class="fw-bold text-primary">
                            <?= count(array_filter($students, function($s) { return $s['profile_completed'] == 1; })) ?>
                        </h4>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card border-0 bg-light">
                    <div class="card-body text-center">
                        <h6 class="text-muted mb-1">ذكور</h6>
                        <h4 class="fw-bold text-info">
                            <?= count(array_filter($students, function($s) { return $s['gender'] == 'male'; })) ?>
                        </h4>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card border-0 bg-light">
                    <div class="card-body text-center">
                        <h6 class="text-muted mb-1">إناث</h6>
                        <h4 class="fw-bold text-purple">
                            <?= count(array_filter($students, function($s) { return $s['gender'] == 'female'; })) ?>
                        </h4>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card border-0 bg-light">
                    <div class="card-body text-center">
                        <h6 class="text-muted mb-1">حد العرض</h6>
                        <h4 class="fw-bold text-success">1000</h4>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Students List -->
        <div id="studentsContainer">
            <?php if ($student_count > 0): ?>
                <?php foreach ($students as $student): ?>
                    <div class="student-card" data-student-id="<?= e($student['student_id']) ?>" 
                         data-college-id="<?= e($student['college_id']) ?>"
                         data-section-id="<?= e($student['section_id']) ?>"
                         data-batch-id="<?= e($student['batch_id']) ?>">
                        <div class="row align-items-center">
                            <div class="col-1 text-center">
                                <input type="checkbox" class="form-check-input student-checkbox" 
                                       value="<?= e($student['student_id']) ?>" 
                                       style="transform: scale(1.2); cursor: pointer;">
                            </div>
                            <div class="col-2">
                                <strong class="d-block fs-6"><?= e($student['student_id']) ?></strong>
                                <small class="text-muted d-block">الرقم الجامعي</small>
                                <div class="mt-1">
                                    <span class="status-badge badge-accepted">مقبول</span>
                                    <span class="status-badge badge-medical">لائق</span>
                                </div>
                            </div>
                            <div class="col-2">
                                <strong class="d-block"><?= e($student['student_name']) ?></strong>
                                <small class="text-muted d-block"><?= e($student['student_name_eng']) ?></small>
                                <small class="d-block mt-1">
                                    <i class="fas fa-<?= $student['gender'] === 'female' ? 'female' : 'male' ?> me-1"></i>
                                    <?= e($student['gender'] === 'female' ? 'أنثى' : 'ذكر') ?>
                                </small>
                            </div>
                            <div class="col-2">
                                <span class="chip blue d-block mb-1"><?= e($student['college_name'] ?? '—') ?></span>
                                <?php if (!empty($student['program_name'])): ?>
                                    <span class="chip teal d-block"><?= e($student['program_name']) ?></span>
                                <?php endif; ?>
                            </div>
                            <div class="col-2">
                                <span class="chip purple d-block mb-1"><?= e($student['section_name'] ?? 'غير محدد') ?></span>
                                <span class="chip orange d-block">دفعة <?= e($student['batch_name'] ?? 'غير محدد') ?></span>
                            </div>
                            <div class="col-2">
                                <div class="text-muted small">
                                    <div class="mb-1">
                                        <i class="fas fa-phone me-1"></i>
                                        <?= e($student['phone_number'] ?? '—') ?>
                                    </div>
                                    <div>
                                        <i class="fas fa-envelope me-1"></i>
                                        <?= e($student['email'] ?? '—') ?>
                                    </div>
                                </div>
                            </div>
                            <div class="col-1 text-center">
                                <button type="button" class="btn btn-sm btn-outline-info" 
                                        onclick="printSelectedCards('<?= e($student['student_id']) ?>')"
                                        title="معاينة البطاقة">
                                    <i class="fas fa-eye"></i>
                                </button>
                                
                                
                                 
                            
                            
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="text-center py-5">
                    <div class="text-muted">
                        <i class="fas fa-search fa-3x mb-3" style="color: #95a5a6;"></i>
                        <h5>لا توجد نتائج</h5>
                        <p class="mb-3">لم يتم العثور على طلاب مطابقين لمعايير البحث.</p>
                        <div class="alert alert-warning w-50 mx-auto">
                            <h6><i class="fas fa-exclamation-triangle me-2"></i>ملاحظة</h6>
                            <p class="mb-0">يتم عرض الطلاب المقبولين في المقابلة واللائقين طبياً فقط.</p>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Print Section -->
    <?php if ($student_count > 0): ?>
        <div class="print-section">
            <div class="dash-card">
                <div class="row align-items-center">
                    <div class="col-md-6">
                        <h6 class="fw-bold mb-2"><i class="fas fa-print me-2"></i>خيارات الطباعة</h6>
                        <div class="d-flex align-items-center gap-3">
                            <div>
                                <span class="badge bg-primary fs-6" id="selectedCount">0</span>
                                <span class="text-muted">طالب محدد</span>
                            </div>
                            <div>
                                <span class="badge bg-secondary fs-6"><?= $student_count ?></span>
                                <span class="text-muted">طالب في القائمة</span>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="printBothSides">
                                <label class="form-check-label" for="printBothSides">
                                    طباعة وجه وظهر معاً
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 text-end">
                        <div class="d-flex gap-2 justify-content-end flex-wrap">
                            <button type="button" class="btn btn-success btn-lg" onclick="printSelectedCards()" disabled id="printBtn">
                                <i class="fas fa-print me-2"></i>طباعة المحددة
                            </button>
                            <button type="button" class="btn btn-primary btn-lg" onclick="printAllCards()">
                                <i class="fas fa-print me-2"></i>طباعة الكل
                            </button>
                            <button type="button" class="btn btn-info btn-lg" onclick="printBackSide()">
                                <i class="fas fa-id-card me-2"></i>طباعة الخلفية
                            </button>
                            <button type="button" class="btn btn-warning btn-lg" onclick="printTestPage()">
                                <i class="fas fa-vial me-2"></i>صفحة اختبار
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Print Settings -->
                <div class="row mt-3" id="printSettings" style="display: none;">
                    <div class="col-md-12">
                        <div class="card border-0 bg-light">
                            <div class="card-body">
                                <h6><i class="fas fa-cog me-2"></i>إعدادات الطباعة</h6>
                                <div class="row g-3">
                                    <div class="col-md-3">
                                        <label class="form-label">نوع الورق</label>
                                        <select class="form-select" id="paperType">
                                            <option value="cr80" selected>CR80 (54×85.6mm)</option>
                                            <option value="a4">A4</option>
                                            <option value="letter">Letter</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">عدد النسخ</label>
                                        <input type="number" class="form-control" id="copiesCount" value="1" min="1" max="10">
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">التوجيه</label>
                                        <select class="form-select" id="printOrientation">
                                            <option value="portrait">عمودي</option>
                                            <option value="landscape">أفقي</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">الجودة</label>
                                        <select class="form-select" id="printQuality">
                                            <option value="draft">مسودة</option>
                                            <option value="normal" selected>عادية</option>
                                            <option value="high">عالية</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <?php else: ?>
        <!-- Welcome Message -->
        <div class="dash-card text-center py-5">
            <div class="text-muted">
                <i class="fas fa-print fa-4x mb-4" style="color: #f39c12;"></i>
                <h4>مرحباً في نظام طباعة البطاقات</h4>
                <p class="mb-3">استخدم عوامل التصفية أعلاه للعثور على الطلاب المقبولين واللائقين طبياً لطباعة بطاقاتهم.</p>
                <div class="row justify-content-center">
                    <div class="col-md-8">
                        <div class="alert alert-info">
                            <h6><i class="fas fa-lightbulb me-2"></i>💡 ملاحظة:</h6>
                            <ul class="text-start mb-0">
                                <li>سيتم عرض الطلاب المقبولين في المقابلة واللائقين طبياً فقط.</li>
                                <?php if ($hasProgramsTable || $hasProgramInStudents || $hasProgramInBatches): ?>
                                <li>يمكنك استخدام فلتر البرنامج للبحث عن طلاب برنامج معين.</li>
                                <?php endif; ?>
                                <li>الحد الأقصى للعرض هو 1000 طالب في كل عملية بحث.</li>
                                <li>يمكنك تحديد الطلاب بشكل فردي أو طباعة الجميع.</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<!-- Help Modal -->
<div class="modal fade" id="helpModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-question-circle me-2"></i>مساعدة - نظام طباعة البطاقات</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <h6>🎯 كيفية الاستخدام:</h6>
                <ol>
                    <li>استخدم عوامل التصفية للبحث عن الطلاب المطلوبين</li>
                    <li>حدد الطلاب الذين تريد طباعة بطاقاتهم</li>
                    <li>اضغط على زر "طباعة المحددة" أو "طباعة الكل"</li>
                    <li>ستفتح نافذة جديدة تحتوي على البطاقات جاهزة للطباعة</li>
                </ol>
                
                <h6>🖨️ إعدادات الطباعة الموصى بها:</h6>
                <ul>
                    <li><strong>نوع الورق:</strong> CR80 (بطاقات بلاستيكية)</li>
                    <li><strong>الحجم:</strong> 54mm × 85.6mm</li>
                    <li><strong>الهوامش:</strong> بدون هوامش (Margin: None)</li>
                    <li><strong>التدرج:</strong> ملون (Color)</li>
                </ul>
                
                <h6>⚙️ الفلاتر المتاحة:</h6>
                <ul>
                    <li><strong>الكلية:</strong> تصفية حسب الكلية</li>
                    <li><strong>القسم:</strong> تصفية حسب القسم/الشعبة</li>
                    <li><strong>الدفعة:</strong> تصفية حسب سنة الدفعة</li>
                    <?php if ($hasProgramsTable || $hasProgramInStudents || $hasProgramInBatches): ?>
                    <li><strong>البرنامج:</strong> تصفية حسب البرنامج الدراسي</li>
                    <?php endif; ?>
                    <li><strong>البحث:</strong> بحث بالاسم أو الرقم الجامعي</li>
                </ul>
                
                <h6>🔧 إصلاح مشاكل قاعدة البيانات:</h6>
                <p>إذا كان فلتر البرنامج لا يعمل، قد يكون بسبب:</p>
                <ol>
                    <li>عدم وجود جدول البرامج في قاعدة البيانات</li>
                    <li>عدم وجود حقل <code>program_id</code> في جدول الطلاب أو الدفعات</li>
                    <li>عدم وجود علاقة بين الجداول بشكل صحيح</li>
                </ol>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-bs-dismiss="modal">فهمت</button>
                <button type="button" class="btn btn-outline-secondary" onclick="showDatabaseStructure()">
                    <i class="fas fa-database me-1"></i> عرض هيكل قاعدة البيانات
                </button>
            </div>
        </div>
    </div>
</div>

<script>
// Student selection management
let selectedStudents = new Set();

function updateSelection() {
    const checkboxes = document.querySelectorAll('.student-checkbox');
    selectedStudents.clear();
    
    checkboxes.forEach(checkbox => {
        if (checkbox.checked) {
            selectedStudents.add(checkbox.value);
            checkbox.closest('.student-card').classList.add('selected');
        } else {
            checkbox.closest('.student-card').classList.remove('selected');
        }
    });
    
    // Update selected count
    const selectedCount = selectedStudents.size;
    document.getElementById('selectedCount').textContent = selectedCount;
    
    // Enable/disable print button
    document.getElementById('printBtn').disabled = selectedCount === 0;
    
    // Update print button text
    if (selectedCount > 0) {
        document.getElementById('printBtn').innerHTML = 
            `<i class="fas fa-print me-2"></i>طباعة المحددة (${selectedCount})`;
    } else {
        document.getElementById('printBtn').innerHTML = 
            `<i class="fas fa-print me-2"></i>طباعة المحددة`;
    }
}

function selectAllStudents() {
    const checkboxes = document.querySelectorAll('.student-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.checked = true;
    });
    updateSelection();
    showToast('تم تحديد جميع الطلاب', 'success');
}

function deselectAllStudents() {
    const checkboxes = document.querySelectorAll('.student-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.checked = false;
    });
    updateSelection();
    showToast('تم إلغاء تحديد جميع الطلاب', 'info');
}

function exportSelectedStudents() {
    if (selectedStudents.size === 0) {
        showToast('يرجى تحديد طلاب أولاً', 'warning');
        return;
    }
    
    const studentIds = Array.from(selectedStudents);
    const csvContent = "data:text/csv;charset=utf-8," 
        + "الرقم الجامعي,الاسم,الكليـة,القسم,الدفعة,البرنامج\n"
        + studentIds.map(id => {
            const card = document.querySelector(`[data-student-id="${id}"]`);
            if (card) {
                const name = card.querySelector('strong').textContent;
                const college = card.querySelector('.chip.blue')?.textContent || '';
                const section = card.querySelector('.chip.purple')?.textContent || '';
                const batch = card.querySelector('.chip.orange')?.textContent || '';
                const program = card.querySelector('.chip.teal')?.textContent || '';
                return `"${id}","${name}","${college}","${section}","${batch}","${program}"`;
            }
            return id;
        }).join("\n");
    
    const encodedUri = encodeURI(csvContent);
    const link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", `students_${new Date().toISOString().slice(0,10)}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    showToast(`تم تصدير ${selectedStudents.size} طالب`, 'success');
}

// Print functions
function printSelectedCards() {
    if (selectedStudents.size === 0) {
        showToast('يرجى تحديد طلاب لطباعة بطاقاتهم.', 'warning');
        return;
    }
    
    const studentIds = Array.from(selectedStudents);
    printStudentCards(studentIds, 'selected');
}

function printAllCards() {
    const studentIds = [];
    document.querySelectorAll('.student-checkbox').forEach(checkbox => {
        studentIds.push(checkbox.value);
    });
    
    if (studentIds.length === 0) {
        showToast('لا توجد بطاقات للطباعة.', 'warning');
        return;
    }
    
    printStudentCards(studentIds, 'all');
}

function printStudentCards(studentIds, type = 'selected') {
    // Get print settings
    const printBothSides = document.getElementById('printBothSides')?.checked || false;
    const paperType = document.getElementById('paperType')?.value || 'cr80';
    const copies = document.getElementById('copiesCount')?.value || 1;
    
    // Build print URL
    let printUrl = `card_print_page.php?students=${studentIds.join(',')}`;
    printUrl += `&paper=${paperType}`;
    printUrl += `&copies=${copies}`;
    if (printBothSides) {
        printUrl += '&both_sides=1';
    }
    
    // Open print page in new window
    const printWindow = window.open(printUrl, '_blank');
    
    // Show success message
    const message = type === 'selected' 
        ? `سيتم فتح نافذة جديدة لطباعة ${studentIds.length} بطاقة طالب.`
        : `سيتم فتح نافذة جديدة لطباعة جميع البطاقات (${studentIds.length} بطاقة).`;
    
    showToast(message, 'info');
    
    // Auto-print after 2 seconds if in same domain
    setTimeout(() => {
        try {
            if (printWindow && !printWindow.closed) {
                printWindow.focus();
            }
        } catch (e) {
            // Cross-origin error, ignore
        }
    }, 2000);
}

function printBackSide() {
    const studentIds = Array.from(selectedStudents);
    
    if (studentIds.length === 0) {
        // If no students selected, use all students
        studentIds.length = 0;
        document.querySelectorAll('.student-checkbox').forEach(checkbox => {
            studentIds.push(checkbox.value);
        });
    }
    
    if (studentIds.length === 0) {
        showToast('لا توجد بطاقات لطباعة الخلفية.', 'warning');
        return;
    }
    
    // Open back side page in new window
    const backSideUrl = `card_back_page.php?students=${studentIds.join(',')}`;
    window.open(backSideUrl, '_blank');
    
    // Show success message
    showToast(`سيتم فتح نافذة جديدة لطباعة ظهر ${studentIds.length} بطاقة.`, 'info');
}

function printTestPage() {
    // Open test page
    window.open('card_test_page.php', '_blank');
    showToast('تم فتح صفحة الاختبار للطباعة', 'info');
}

function previewCard(studentId) {
    // Open preview in new window
    const previewUrl = `card_preview.php?student=${studentId}`;
    window.open(previewUrl, '_blank', 'width=800,height=600');
    showToast('جاري فتح معاينة البطاقة...', 'info');
}

function showPrintHelp() {
    const modal = new bootstrap.Modal(document.getElementById('helpModal'));
    modal.show();
}

function showDatabaseHelp() {
    alert('يبدو أن هناك مشكلة في هيكل قاعدة البيانات الخاصة بالبرامج.\n\n' +
          'يمكن أن يكون بسبب:\n' +
          '1. جدول البرامج غير موجود\n' +
          '2. حقل البرنامج غير موجود في جدول الطلاب أو الدفعات\n' +
          '3. عدم وجود علاقة بين الجداول\n\n' +
          'سيتم عرض الطلاب بدون فلتر البرنامج.');
}

function showDatabaseStructure() {
    // AJAX request to check database structure
    fetch('ajax/check_database.php?table=programs')
        .then(response => response.json())
        .then(data => {
            let message = 'هيكل قاعدة البيانات:\n\n';
            
            if (data.error) {
                message += 'خطأ: ' + data.error;
            } else {
                message += 'الجداول المتوفرة:\n';
                data.tables?.forEach(table => {
                    message += `- ${table}\n`;
                });
                
                if (data.columns) {
                    message += '\nأعمدة جدول الطلاب:\n';
                    data.columns.forEach(col => {
                        message += `- ${col.Field} (${col.Type})\n`;
                    });
                }
            }
            
            alert(message);
        })
        .catch(error => {
            console.error('Error:', error);
            alert('تعذر الحصول على معلومات قاعدة البيانات');
        });
}

function showToast(message, type = 'info') {
    // Create toast element
    const toastId = 'toast-' + Date.now();
    const toastHtml = `
        <div id="${toastId}" class="toast align-items-center text-white bg-${type} border-0" role="alert">
            <div class="d-flex">
                <div class="toast-body">
                    ${message}
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
            </div>
        </div>
    `;
    
    // Add to container
    const container = document.querySelector('.toast-container') || (() => {
        const div = document.createElement('div');
        div.className = 'toast-container position-fixed bottom-0 end-0 p-3';
        document.body.appendChild(div);
        return div;
    })();
    
    container.innerHTML = toastHtml;
    
    // Show toast
    const toastElement = document.getElementById(toastId);
    const toast = new bootstrap.Toast(toastElement, { delay: 3000 });
    toast.show();
    
    // Remove after hide
    toastElement.addEventListener('hidden.bs.toast', function () {
        toastElement.remove();
    });
}

// Initialize event listeners
document.addEventListener('DOMContentLoaded', function() {
    // Add event listeners to checkboxes
    document.addEventListener('change', function(e) {
        if (e.target.classList.contains('student-checkbox')) {
            updateSelection();
        }
    });
    
    // Initialize selection state
    updateSelection();
    
    // Enable/disable section select based on college selection
    const collegeSelect = document.getElementById('collegeSelect');
    const sectionSelect = document.getElementById('sectionSelect');
    
    if (collegeSelect && sectionSelect) {
        collegeSelect.addEventListener('change', function() {
            sectionSelect.disabled = !this.value;
        });
        
        if (!collegeSelect.value) {
            sectionSelect.disabled = true;
        }
    }
    
    // Show/hide print settings
    const printSettingsBtn = document.createElement('button');
    printSettingsBtn.className = 'btn btn-sm btn-outline-secondary ms-2';
    printSettingsBtn.innerHTML = '<i class="fas fa-cog"></i>';
    printSettingsBtn.title = 'إعدادات الطباعة';
    printSettingsBtn.onclick = function() {
        const settings = document.getElementById('printSettings');
        settings.style.display = settings.style.display === 'none' ? 'block' : 'none';
    };
    
    const printSection = document.querySelector('.print-section h6');
    if (printSection) {
        printSection.parentElement.appendChild(printSettingsBtn);
    }
    
    // Add keyboard shortcuts
    document.addEventListener('keydown', function(e) {
        // Ctrl+A to select all
        if (e.ctrlKey && e.key === 'a') {
            e.preventDefault();
            selectAllStudents();
        }
        // Ctrl+D to deselect all
        if (e.ctrlKey && e.key === 'd') {
            e.preventDefault();
            deselectAllStudents();
        }
        // Ctrl+P to print selected
        if (e.ctrlKey && e.key === 'p') {
            e.preventDefault();
            printSelectedCards();
        }
        // Escape to deselect all
        if (e.key === 'Escape') {
            deselectAllStudents();
        }
    });
    
    // Add click handler for student cards
    document.addEventListener('click', function(e) {
        if (e.target.closest('.student-card') && !e.target.matches('input, button, a')) {
            const checkbox = e.target.closest('.student-card').querySelector('.student-checkbox');
            if (checkbox) {
                checkbox.checked = !checkbox.checked;
                updateSelection();
            }
        }
    });
    
    // Show welcome message for first time users
    if (!localStorage.getItem('cardPrintingWelcomeShown')) {
        setTimeout(() => {
            showToast('مرحباً! يمكنك استخدام Ctrl+A لتحديد الكل وCtrl+P للطباعة السريعة', 'info');
            localStorage.setItem('cardPrintingWelcomeShown', 'true');
        }, 1000);
    }
});

// Handle AJAX loading of sections based on college
if (document.getElementById('collegeSelect')) {
    document.getElementById('collegeSelect').addEventListener('change', function() {
        const collegeId = this.value;
        const sectionSelect = document.getElementById('sectionSelect');
        
        if (!collegeId) {
            sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
            sectionSelect.disabled = true;
            return;
        }
        
        // Show loading
        sectionSelect.innerHTML = '<option value="">جاري التحميل...</option>';
        sectionSelect.disabled = false;
        
        // Fetch sections for this college
        fetch(`ajax/get_sections.php?college_id=${collegeId}`)
            .then(response => response.json())
            .then(data => {
                sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
                data.forEach(section => {
                    const option = document.createElement('option');
                    option.value = section.id;
                    option.textContent = section.name;
                    sectionSelect.appendChild(option);
                });
                
                // Restore previously selected section if any
                const currentSectionId = '<?= $section_id ?>';
                if (currentSectionId) {
                    sectionSelect.value = currentSectionId;
                }
            })
            .catch(error => {
                console.error('Error loading sections:', error);
                sectionSelect.innerHTML = '<option value="">خطأ في التحميل</option>';
            });
    });
}
</script>

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