<?php
// transcript.php - Fixed version with AJAX loading for all filters (no page refresh)
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';
require_committee();

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Validation functions
function validateInt($input, $default = 0) {
    if (isset($input) && ctype_digit((string)$input)) {
        return (int)$input;
    }
    return $default;
}

function validateString($input, $default = '') {
    if (isset($input) && is_string($input)) {
        $clean = trim($input);
        $clean = strip_tags($clean);
        $clean = htmlspecialchars($clean, ENT_QUOTES, 'UTF-8');
        return $clean;
    }
    return $default;
}

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

// Handle AJAX request for sections
if (isset($_GET['ajax']) && $_GET['ajax'] == 'get_sections' && isset($_GET['college_id'])) {
    header('Content-Type: application/json');
    $ajax_college_id = validateInt($_GET['college_id']);
    $sections_data = [];
    
    if ($canAll || ($scopeCollege !== null && $scopeCollege == $ajax_college_id) || $scopeCollege === null) {
        $query = "SELECT id, name FROM sections WHERE parent = $ajax_college_id AND deleted_at IS NULL ORDER BY name";
        $result = $mysqli1->query($query);
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $sections_data[] = [
                    'id' => (int)$row['id'],
                    'name' => validateString($row['name'])
                ];
            }
        }
    }
    
    echo json_encode(['success' => true, 'sections' => $sections_data]);
    exit;
}

// Handle AJAX request for students
if (isset($_GET['ajax']) && $_GET['ajax'] == 'get_students' && isset($_GET['college_id']) && isset($_GET['batch_id'])) {
    header('Content-Type: application/json');
    $ajax_college_id = validateInt($_GET['college_id']);
    $ajax_batch_id = validateInt($_GET['batch_id']);
    $ajax_section_id = isset($_GET['section_id']) ? validateInt($_GET['section_id']) : 0;
    $ajax_program_id = isset($_GET['program_id']) ? validateInt($_GET['program_id']) : 0;
    
    $students_data = [];
    
    $query = "SELECT DISTINCT s.student_id, s.student_name 
              FROM students s 
              WHERE s.college_id = $ajax_college_id 
              AND s.batch_id = $ajax_batch_id 
              AND s.deleted_at IS NULL";
    
    if ($ajax_section_id > 0) {
        $query .= " AND s.section_id = $ajax_section_id";
    }
    
    if ($ajax_program_id > 0) {
        $query .= " AND s.program_id = $ajax_program_id";
    }
    
    $query .= " ORDER BY s.student_name";
    
    $result = $mysqli1->query($query);
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $students_data[] = [
                'id' => validateString($row['student_id']),
                'name' => validateString($row['student_name'])
            ];
        }
    }
    
    echo json_encode(['success' => true, 'students' => $students_data]);
    exit;
}

// Handle AJAX request for transcript data
if (isset($_GET['ajax']) && $_GET['ajax'] == 'get_transcript') {
    header('Content-Type: application/json');
    
    $college_id = validateInt($_GET['college_id'] ?? 0);
    $section_id = validateInt($_GET['section_id'] ?? 0);
    $program_id = validateInt($_GET['program_id'] ?? 0);
    $batch_id = validateInt($_GET['batch_id'] ?? 0);
    $semester_id = validateInt($_GET['semester_id'] ?? 0);
    $is_final = isset($_GET['is_final']) ? (bool)$_GET['is_final'] : false;
    
    // Get names
    $college_name = '';
    $college_result = $mysqli1->query("SELECT name FROM colleges WHERE id = $college_id");
    if ($college_result && $row = $college_result->fetch_assoc()) {
        $college_name = validateString($row['name']);
    }
    
    $section_name = '';
    $section_result = $mysqli1->query("SELECT name FROM sections WHERE id = $section_id");
    if ($section_result && $row = $section_result->fetch_assoc()) {
        $section_name = validateString($row['name']);
    }
    
    $program_name = '';
    $program_result = $mysqli1->query("SELECT name FROM programs WHERE id = $program_id");
    if ($program_result && $row = $program_result->fetch_assoc()) {
        $program_name = validateString($row['name']);
    }
    
    $batch_value = '';
    $batch_result = $mysqli1->query("SELECT value FROM batches WHERE id = $batch_id");
    if ($batch_result && $row = $batch_result->fetch_assoc()) {
        $batch_value = validateString($row['value']);
    }
    
    $semester_name = '';
    $semester_result = $mysqli1->query("SELECT name FROM semesters WHERE id = $semester_id");
    if ($semester_result && $row = $semester_result->fetch_assoc()) {
        $semester_name = validateString($row['name']);
    }
    
    // Get transcript data (same as before but return JSON)
    $subject_list = [];
    $subject_stats = [];
    $students_data = [];
    
    if ($college_id && $batch_id && $semester_id) {
        
        $whereConditions = "s.college_id = ? AND ss.batch_id = ? AND ss.semester_id = ? AND s.deleted_at IS NULL AND sub.deleted_at IS NULL";
        $params = [$college_id, $batch_id, $semester_id];
        $types = "iii";
        
        if ($section_id > 0) {
            $whereConditions .= " AND s.section_id = ?";
            $params[] = $section_id;
            $types .= "i";
        }
        
        if ($program_id > 0) {
            $whereConditions .= " AND s.program_id = ?";
            $params[] = $program_id;
            $types .= "i";
        }
        
        // Get subjects
        $subjectQuery = "
            SELECT DISTINCT 
                ss.subjectcode,
                sub.subjectnamea,
                sub.credit_hours
            FROM studentsubjects ss
            JOIN subjects sub ON ss.subjectcode = sub.subjectcode
            JOIN students s ON ss.student_id = s.student_id
            WHERE $whereConditions
            ORDER BY ss.subjectcode
        ";
        
        $stmt = $mysqli1->prepare($subjectQuery);
        if ($stmt) {
            $stmt->bind_param($types, ...$params);
            $stmt->execute();
            $result = $stmt->get_result();
            $counter = 1;
            while ($row = $result->fetch_assoc()) {
                $subject_list[] = [
                    'no' => $counter++,
                    'code' => validateString($row['subjectcode']),
                    'name_ar' => validateString($row['subjectnamea']),
                    'credit_hours' => (float)$row['credit_hours']
                ];
            }
            $stmt->close();
        }
        
        // Get statistics
        $statsQuery = "
            SELECT 
                sub.subjectcode,
                sub.subjectnamea,
                sub.credit_hours,
                SUM(CASE WHEN ss.grade = 'A' THEN 1 ELSE 0 END) as A_count,
                SUM(CASE WHEN ss.grade = 'B+' THEN 1 ELSE 0 END) as Bplus_count,
                SUM(CASE WHEN ss.grade = 'B' THEN 1 ELSE 0 END) as B_count,
                SUM(CASE WHEN ss.grade = 'C+' THEN 1 ELSE 0 END) as Cplus_count,
                SUM(CASE WHEN ss.grade = 'C' THEN 1 ELSE 0 END) as C_count,
                SUM(CASE WHEN ss.grade = 'D+' THEN 1 ELSE 0 END) as Dplus_count,
                SUM(CASE WHEN ss.grade = 'D' THEN 1 ELSE 0 END) as D_count,
                SUM(CASE WHEN ss.grade = 'F' OR ss.grade = 'F*' OR ss.grade = 'F**' OR ss.grade = 'F***' THEN 1 ELSE 0 END) as F_count,
                COUNT(DISTINCT ss.student_id) as total_students
            FROM studentsubjects ss
            JOIN subjects sub ON ss.subjectcode = sub.subjectcode
            JOIN students s ON ss.student_id = s.student_id
            WHERE $whereConditions
            GROUP BY sub.subjectcode, sub.subjectnamea, sub.credit_hours
            ORDER BY sub.subjectcode
        ";
        
        $stmt = $mysqli1->prepare($statsQuery);
        if ($stmt) {
            $stmt->bind_param($types, ...$params);
            $stmt->execute();
            $result = $stmt->get_result();
            $counter = 1;
            while ($row = $result->fetch_assoc()) {
                $subject_stats[] = [
                    'no' => $counter++,
                    'code' => validateString($row['subjectcode']),
                    'name_ar' => validateString($row['subjectnamea']),
                    'credit_hours' => (float)$row['credit_hours'],
                    'A' => (int)$row['A_count'],
                    'Bplus' => (int)$row['Bplus_count'],
                    'B' => (int)$row['B_count'],
                    'Cplus' => (int)$row['Cplus_count'],
                    'C' => (int)$row['C_count'],
                    'Dplus' => (int)$row['Dplus_count'],
                    'D' => (int)$row['D_count'],
                    'F' => (int)$row['F_count'],
                    'total' => (int)$row['total_students']
                ];
            }
            $stmt->close();
        }
        
        // Get students
        $enrolledStudentsQuery = "
            SELECT DISTINCT s.student_id, s.student_name
            FROM students s
            WHERE s.college_id = ? AND s.batch_id = ? AND s.deleted_at IS NULL
        ";
        
        $enrolledParams = [$college_id, $batch_id];
        $enrolledTypes = "ii";
        
        if ($section_id > 0) {
            $enrolledStudentsQuery .= " AND s.section_id = ?";
            $enrolledParams[] = $section_id;
            $enrolledTypes .= "i";
        }
        
        if ($program_id > 0) {
            $enrolledStudentsQuery .= " AND s.program_id = ?";
            $enrolledParams[] = $program_id;
            $enrolledTypes .= "i";
        }
        
        $enrolledStudentsQuery .= " ORDER BY s.student_name";
        
        $all_students = [];
        $stmt = $mysqli1->prepare($enrolledStudentsQuery);
        if ($stmt) {
            $stmt->bind_param($enrolledTypes, ...$enrolledParams);
            $stmt->execute();
            $result = $stmt->get_result();
            while ($row = $result->fetch_assoc()) {
                $all_students[$row['student_id']] = [
                    'student_id' => validateString($row['student_id']),
                    'student_name' => validateString($row['student_name']),
                    'grades' => []
                ];
            }
            $stmt->close();
        }
        
        // Get grades
        $studentQuery = "
            SELECT 
                s.student_id,
                s.student_name,
                ss.subjectcode,
                ss.degree,
                ss.grade,
                ss.weight,
                sub.credit_hours
            FROM studentsubjects ss
            JOIN students s ON ss.student_id = s.student_id
            JOIN subjects sub ON ss.subjectcode = sub.subjectcode
            WHERE $whereConditions
            ORDER BY s.student_name, ss.subjectcode
        ";
        
        $stmt = $mysqli1->prepare($studentQuery);
        if ($stmt) {
            $stmt->bind_param($types, ...$params);
            $stmt->execute();
            $result = $stmt->get_result();
            
            while ($row = $result->fetch_assoc()) {
                $student_id_key = $row['student_id'];
                
                if (!isset($all_students[$student_id_key])) {
                    $all_students[$student_id_key] = [
                        'student_id' => validateString($row['student_id']),
                        'student_name' => validateString($row['student_name']),
                        'grades' => []
                    ];
                }
                
                $all_students[$student_id_key]['grades'][$row['subjectcode']] = [
                    'degree' => $row['degree'] !== null ? (float)$row['degree'] : null,
                    'grade' => validateString($row['grade'] ?? ''),
                    'weight' => $row['weight'] !== null ? (float)$row['weight'] : 0,
                    'credit_hours' => (float)$row['credit_hours']
                ];
            }
            $stmt->close();
        }
        
        $students_data = array_values($all_students);
    }
    
    echo json_encode([
        'success' => true,
        'college_name' => $college_name,
        'section_name' => $section_name,
        'program_name' => $program_name,
        'batch_value' => $batch_value,
        'semester_name' => $semester_name,
        'subject_list' => $subject_list,
        'subject_stats' => $subject_stats,
        'students_data' => $students_data,
        'total_students' => count($students_data),
        'is_final' => $is_final
    ]);
    exit;
}

// Get filter data - colleges
$colleges = [];
$colleges_query = "SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name";
if (!$canAll && $scopeCollege !== null) {
    $colleges_query = "SELECT id, name FROM colleges WHERE id = $scopeCollege AND deleted_at IS NULL ORDER BY name";
}
$result = $mysqli1->query($colleges_query);
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $colleges[] = [
            'id' => (int)$row['id'],
            'name' => validateString($row['name'])
        ];
    }
}

// Get batches
$batches = [];
$result = $mysqli1->query("SELECT id, value FROM batches WHERE deleted_at IS NULL ORDER BY id DESC");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $batches[] = [
            'id' => (int)$row['id'],
            'value' => validateString($row['value'])
        ];
    }
}

// Get semesters
$semesters = [];
$result = $mysqli1->query("SELECT id, name FROM semesters WHERE deleted_at IS NULL ORDER BY id");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $semesters[] = [
            'id' => (int)$row['id'],
            'name' => validateString($row['name'])
        ];
    }
}

// Get programs for filter
$programs = [];
$result = $mysqli1->query("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $programs[] = [
            'id' => (int)$row['id'],
            'name' => validateString($row['name'])
        ];
    }
}

// Get filter parameters for initial load
$college_id = validateInt($_GET['college_id'] ?? 0);
$section_id = validateInt($_GET['section_id'] ?? 0);
$program_id = validateInt($_GET['program_id'] ?? 0);
$batch_id = validateInt($_GET['batch_id'] ?? 0);
$semester_id = validateInt($_GET['semester_id'] ?? 0);
$transcript_type = validateString($_GET['transcript_type'] ?? 'batch');
$is_final = isset($_GET['is_final']) ? (bool)$_GET['is_final'] : false;

// Get sections for initial load
$sections = [];
if ($college_id > 0) {
    $sections_query = "SELECT id, name FROM sections WHERE parent = $college_id AND deleted_at IS NULL ORDER BY name";
    $result = $mysqli1->query($sections_query);
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $sections[] = [
                'id' => (int)$row['id'],
                'name' => validateString($row['name'])
            ];
        }
    }
}

include 'header.php';
?>

<link rel="stylesheet" href="css/csstranscript.css">

<div class="transcript-wrapper">
    <div class="page-header d-flex justify-content-between align-items-center flex-wrap">
        <div>
            <h1><i class="fas fa-print ms-3"></i> كشف الدرجات - Transcript</h1>
            <p>طباعة كشوفات الدرجات للطلاب والدفعات</p>
        </div>
        <div class="mt-3 mt-md-0">
            <a href="admin_dashboard.php" class="btn-reset">
                <i class="fas fa-arrow-right ms-2"></i> العودة للوحة التحكم
            </a>
        </div>
    </div>

    <!-- Filter Section -->
    <div class="filter-card no-print">
        <form method="GET" action="" id="transcriptForm">
            <div class="row g-3">
                <div class="col-md-2">
                    <label class="form-label required-field">نوع الكشف</label>
                    <select class="form-select" name="transcript_type" id="transcript_type">
                        <option value="batch" <?= $transcript_type == 'batch' ? 'selected' : '' ?>>كشف دفعة كاملة</option>
                        <option value="student" <?= $transcript_type == 'student' ? 'selected' : '' ?>>كشف طالب فردي</option>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label required-field">الكلية</label>
                    <select class="form-select" name="college_id" id="college_id">
                        <option value="">اختر الكلية</option>
                        <?php foreach ($colleges as $college): ?>
                            <option value="<?= $college['id'] ?>" <?= $college_id == $college['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($college['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label">القسم</label>
                    <select class="form-select" name="section_id" id="section_id">
                        <option value="">جميع الأقسام</option>
                        <?php foreach ($sections as $section): ?>
                            <option value="<?= $section['id'] ?>" <?= $section_id == $section['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($section['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label">البرنامج</label>
                    <select class="form-select" name="program_id" id="program_id">
                        <option value="">جميع البرامج</option>
                        <?php foreach ($programs as $program): ?>
                            <option value="<?= $program['id'] ?>" <?= $program_id == $program['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($program['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-2" id="student_div" style="display: <?= $transcript_type == 'student' ? 'block' : 'none' ?>;">
                    <label class="form-label required-field">الطالب</label>
                    <select class="form-select" name="student_id" id="student_id">
                        <option value="">اختر الطالب</option>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label required-field">الدفعة</label>
                    <select class="form-select" name="batch_id" id="batch_id">
                        <option value="">اختر الدفعة</option>
                        <?php foreach ($batches as $batch): ?>
                            <option value="<?= $batch['id'] ?>" <?= $batch_id == $batch['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($batch['value']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label required-field">الفصل الدراسي</label>
                    <select class="form-select" name="semester_id" id="semester_id">
                        <option value="">اختر الفصل</option>
                        <?php foreach ($semesters as $semester): ?>
                            <option value="<?= $semester['id'] ?>" <?= $semester_id == $semester['id'] ? 'selected' : '' ?>>
                                الفصل <?= htmlspecialchars($semester['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-12">
                    <div class="d-flex gap-3 justify-content-end">
                        <input type="hidden" name="is_final" id="is_final" value="<?= $is_final ? '1' : '0' ?>">
                        <button type="button" id="toggleFinalBtn" class="btn-toggle <?= $is_final ? 'final' : '' ?>">
                            <i class="fas fa-toggle-<?= $is_final ? 'on' : 'off' ?> ms-2"></i>
                            <?= $is_final ? 'المجلس العلمي' : 'نتائج سنوية' ?>
                        </button>
                        <button type="button" id="resetBtn" class="btn-reset">
                            <i class="fas fa-redo-alt ms-2"></i> إعادة تعيين
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <!-- Loading Indicator -->
    <div id="loadingIndicator" style="display: none; text-align: center; padding: 20px;">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">جاري التحميل...</span>
        </div>
        <p>جاري تحميل البيانات...</p>
    </div>

    <!-- Transcript Display Container -->
    <div id="transcriptContainer">
        <!-- Content will be loaded here via AJAX -->
        <div class="transcript-card text-center">
            <i class="fas fa-filter fa-3x text-muted mb-3 opacity-50"></i>
            <h4>اختر معايير البحث</h4>
            <p class="text-muted">الرجاء اختيار الكلية، الدفعة، والفصل الدراسي لعرض كشف الدرجات</p>
        </div>
    </div>
    
    <!-- Floating Action Buttons -->
    <div class="action-buttons no-print" id="actionButtons" style="display: none;">
        <button onclick="window.print()" class="btn-floating" title="طباعة">
            <i class="fas fa-print"></i>
        </button>
        <button onclick="downloadAsPDF()" class="btn-floating" title="تحميل PDF" style="background: linear-gradient(135deg, #f093fb, #f5576c);">
            <i class="fas fa-file-pdf"></i>
        </button>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>

<script>
$(document).ready(function() {
    var currentStudentId = '';
    
    // Function to load transcript data via AJAX
    function loadTranscriptData() {
        var collegeId = $('#college_id').val();
        var sectionId = $('#section_id').val();
        var programId = $('#program_id').val();
        var batchId = $('#batch_id').val();
        var semesterId = $('#semester_id').val();
        var isFinal = $('#is_final').val();
        
        if (!collegeId || !batchId || !semesterId) {
            return;
        }
        
        // Show loading indicator
        $('#loadingIndicator').show();
        $('#transcriptContainer').html('');
        $('#actionButtons').hide();
        
        // Make AJAX request
        $.ajax({
            url: window.location.pathname,
            type: 'GET',
            data: {
                ajax: 'get_transcript',
                college_id: collegeId,
                section_id: sectionId,
                program_id: programId,
                batch_id: batchId,
                semester_id: semesterId,
                is_final: isFinal
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    renderTranscript(response);
                    $('#actionButtons').show();
                } else {
                    $('#transcriptContainer').html('<div class="transcript-card text-center"><h4>لا توجد بيانات</h4><p class="text-muted">لم يتم العثور على بيانات</p></div>');
                    $('#actionButtons').hide();
                }
            },
            error: function(xhr, status, error) {
                console.error('Error:', error);
                $('#transcriptContainer').html('<div class="transcript-card text-center"><h4>خطأ</h4><p class="text-muted">حدث خطأ في تحميل البيانات</p></div>');
                $('#actionButtons').hide();
            },
            complete: function() {
                $('#loadingIndicator').hide();
            }
        });
    }
    
    // Function to render transcript
    function renderTranscript(data) {
        var html = '';
        
        if (data.subject_list.length === 0 || data.students_data.length === 0) {
            html = '<div class="transcript-card text-center"><i class="fas fa-database fa-3x text-danger mb-3"></i><h4>لا توجد بيانات</h4><p class="text-muted">لم يتم العثور على مواد مسجلة أو طلاب</p></div>';
            $('#transcriptContainer').html(html);
            return;
        }
        
        html += '<div class="transcript-card" id="transcriptContent">';
        
        // Header
        html += '<div class="university-header">';
        html += '<div class="university-name">بسم الله الرحمن الرحيم</div>';
        html += '<div class="college-name">' + data.college_name + '</div>';
        html += '<div class="dept-name">القسم: ' + (data.section_name || 'العام') + '</div>';
        html += '<div class="dept-name">البرنامج: ' + (data.program_name || 'البكالريوس') + '</div>';
        html += '<div class="dept-name">الدفعة: ' + data.batch_value + '</div>';
        html += '<div style="margin-top: 10px;"></div>';
        html += '<div class="dept-name">الفصل الدراسي: ' + data.semester_name + '</div>';
        html += '<div class="dept-name">عدد الطلاب: ' + data.total_students + '</div>';
        html += '<div class="dept-name">نوع النتيجة: ' + (data.is_final ? 'المجلس العلمي للخريجين' : 'نتيجة نقل من عام إلى عام') + '</div>';
        html += '</div>';
        
        html += '<div class="filter-info">';
        html += '<span class="filter-tag"><i class="fas fa-university"></i> الكلية: ' + data.college_name + '</span>';
        if (data.section_name) html += '<span class="filter-tag"><i class="fas fa-layer-group"></i> القسم: ' + data.section_name + '</span>';
        if (data.program_name) html += '<span class="filter-tag"><i class="fas fa-graduation-cap"></i> البرنامج: ' + data.program_name + '</span>';
        html += '<span class="filter-tag"><i class="fas fa-users"></i> الدفعة: ' + data.batch_value + '</span>';
        html += '<span class="filter-tag"><i class="fas fa-calendar-alt"></i> الفصل: ' + data.semester_name + '</span>';
        html += '<span class="filter-tag"><i class="fas fa-print"></i> تاريخ الطباعة: ' + new Date().toLocaleDateString('ar-EG') + '</span>';
        html += '</div>';
        
        html += '<h4 style="text-align: center; margin: 15px 0; font-weight: bold;">كشف درجات الفصل</h4>';
        
        // Table 1: Subjects
        html += '<div class="table-header"><i class="fas fa-book ms-2"></i> جدول (1) المقررات الدراسية</div>';
        html += '<div class="scroll-wrapper"><table class="report-table"><thead><tr>';
        html += '<th width="5%">م</th><th width="15%">رمز المادة</th><th width="55%">اسم المادة (عربي)</th><th width="10%">عدد الساعات</th><th width="15%">Subject Name (EN)</th>';
        html += '</tr></thead><tbody>';
        
        $.each(data.subject_list, function(i, subject) {
            html += '<tr>';
            html += '<td>' + subject.no + '</td>';
            html += '<td>' + escapeHtml(subject.code) + '</td>';
            html += '<td class="text-right">' + escapeHtml(subject.name_ar) + '</td>';
            html += '<td>' + subject.credit_hours.toFixed(1) + '</td>';
            html += '<td>' + escapeHtml(subject.code) + '</td>';
            html += '</tr>';
        });
        
        html += '</tbody></table></div>';
        
        // Table 2: Statistics (simplified for brevity)
        html += '<div class="table-header"><i class="fas fa-chart-bar ms-2"></i> جدول (2) توزيع الدرجات</div>';
        html += '<div class="scroll-wrapper"><table class="report-table"><thead><tr>';
        html += '<th rowspan="2">م</th><th rowspan="2">رمز المادة</th><th rowspan="2">اسم المادة</th><th rowspan="2">س</th>';
        html += '<th colspan="8">توزيع الدرجات</th><th rowspan="2">المجموع</th></tr>';
        html += '<tr><th>A</th><th>B+</th><th>B</th><th>C+</th><th>C</th><th>D+</th><th>D</th><th>F</th></tr>';
        html += '</thead><tbody>';
        
        $.each(data.subject_stats, function(i, stat) {
            html += '<tr>';
            html += '<td>' + stat.no + '</td>';
            html += '<td>' + escapeHtml(stat.code) + '</td>';
            html += '<td class="text-right">' + escapeHtml(stat.name_ar) + '</td>';
            html += '<td>' + stat.credit_hours.toFixed(1) + '</td>';
            html += '<td>' + stat.A + '</td><td>' + stat.Bplus + '</td><td>' + stat.B + '</td>';
            html += '<td>' + stat.Cplus + '</td><td>' + stat.C + '</td><td>' + stat.Dplus + '</td>';
            html += '<td>' + stat.D + '</td><td>' + stat.F + '</td>';
            html += '<td>' + stat.total + '</td>';
            html += '</tr>';
        });
        
        html += '</tbody></table></div>';
        
        // Table 3: Students (simplified)
        html += '<div class="table-header"><i class="fas fa-users ms-2"></i> جدول (3) درجات الطلاب</div>';
        html += '<div class="scroll-wrapper"><table class="report-table" style="font-size: 10px; min-width: 1200px;"><thead><tr>';
        html += '<th rowspan="2">م</th><th rowspan="2">رقم الطالب</th><th rowspan="2">اسم الطالب</th>';
        
        $.each(data.subject_list, function(i, subject) {
            html += '<th colspan="2">' + escapeHtml(subject.code) + '</th>';
        });
        
        html += '<th rowspan="2">الحالة</th></tr><tr>';
        
        $.each(data.subject_list, function(i, subject) {
            html += '<th>تقدير</th><th>درجة</th>';
        });
        
        html += '</tr></thead><tbody>';
        
        var rowNo = 1;
        $.each(data.students_data, function(i, student) {
            html += '<tr>';
            html += '<td>' + rowNo++ + '</td>';
            html += '<td>' + escapeHtml(student.student_id) + '</td>';
            html += '<td class="text-right">' + escapeHtml(student.student_name) + '</td>';
            
            $.each(data.subject_list, function(j, subject) {
                var grade = student.grades[subject.code] || null;
                var gradeText = (grade && grade.grade) ? grade.grade : '--';
                var degreeText = (grade && grade.degree !== null) ? Math.round(grade.degree) : '--';
                html += '<td>' + escapeHtml(gradeText) + '</td>';
                html += '<td>' + degreeText + '</td>';
            });
            
            html += '<td>--</td>';
            html += '</tr>';
        });
        
        html += '</tbody></table></div>';
        
        // Footer
        html += '<div class="summary-footer">';
        html += '<div>تم الطباعة بتاريخ: ' + new Date().toLocaleString('ar-EG') + '</div>';
        html += '<div>عدد الطلاب: ' + data.total_students + '</div>';
        html += '<div>عدد المقررات: ' + data.subject_list.length + '</div>';
        html += '</div>';
        
        html += '</div>';
        
        $('#transcriptContainer').html(html);
    }
    
    // Helper function to escape HTML
    function escapeHtml(text) {
        if (!text) return '';
        var map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return String(text).replace(/[&<>"']/g, function(m) { return map[m]; });
    }
    
    // Function to load sections based on college
    function loadSections(collegeId) {
        var $sectionSelect = $('#section_id');
        
        if (collegeId && collegeId != '') {
            $sectionSelect.empty();
            $sectionSelect.append('<option value="">جار التحميل...</option>');
            $sectionSelect.prop('disabled', true);
            
            $.ajax({
                url: window.location.pathname,
                type: 'GET',
                data: { ajax: 'get_sections', college_id: collegeId },
                dataType: 'json',
                success: function(response) {
                    $sectionSelect.empty();
                    $sectionSelect.append('<option value="">جميع الأقسام</option>');
                    
                    if (response.success && response.sections.length > 0) {
                        $.each(response.sections, function(index, section) {
                            $sectionSelect.append('<option value="' + section.id + '">' + escapeHtml(section.name) + '</option>');
                        });
                    }
                    $sectionSelect.prop('disabled', false);
                },
                error: function() {
                    $sectionSelect.empty();
                    $sectionSelect.append('<option value="">خطأ في تحميل الأقسام</option>');
                    $sectionSelect.prop('disabled', false);
                }
            });
        } else {
            $sectionSelect.empty();
            $sectionSelect.append('<option value="">جميع الأقسام</option>');
            $sectionSelect.prop('disabled', false);
        }
    }
    
    // Function to load students
    function loadStudents() {
        var collegeId = $('#college_id').val();
        var batchId = $('#batch_id').val();
        var sectionId = $('#section_id').val();
        var programId = $('#program_id').val();
        var transcriptType = $('#transcript_type').val();
        
        if (transcriptType == 'student' && collegeId && batchId) {
            var $studentSelect = $('#student_id');
            $studentSelect.empty();
            $studentSelect.append('<option value="">جار التحميل...</option>');
            $studentSelect.prop('disabled', true);
            
            $.ajax({
                url: window.location.pathname,
                type: 'GET',
                data: {
                    ajax: 'get_students',
                    college_id: collegeId,
                    batch_id: batchId,
                    section_id: sectionId,
                    program_id: programId
                },
                dataType: 'json',
                success: function(response) {
                    $studentSelect.empty();
                    $studentSelect.append('<option value="">اختر الطالب</option>');
                    
                    if (response.success && response.students.length > 0) {
                        $.each(response.students, function(index, student) {
                            $studentSelect.append('<option value="' + student.id + '">' + escapeHtml(student.name) + '</option>');
                        });
                    } else {
                        $studentSelect.append('<option value="">لا يوجد طلاب</option>');
                    }
                    $studentSelect.prop('disabled', false);
                },
                error: function() {
                    $studentSelect.empty();
                    $studentSelect.append('<option value="">خطأ في تحميل الطلاب</option>');
                    $studentSelect.prop('disabled', false);
                }
            });
        }
    }
    
    // Event handlers - NO AUTOMATIC PAGE REFRESH
    $('#transcript_type').on('change', function() {
        if ($(this).val() === 'student') {
            $('#student_div').show();
            loadStudents();
        } else {
            $('#student_div').hide();
            $('#student_id').val('');
        }
        loadTranscriptData();
    });
    
    $('#college_id').on('change', function() {
        var collegeId = $(this).val();
        loadSections(collegeId);
        loadTranscriptData();
    });
    
    $('#section_id, #program_id, #batch_id, #semester_id').on('change', function() {
        loadTranscriptData();
        if ($('#transcript_type').val() == 'student') {
            loadStudents();
        }
    });
    
    $('#toggleFinalBtn').on('click', function() {
        var currentVal = $('#is_final').val();
        var newVal = currentVal == '1' ? '0' : '1';
        $('#is_final').val(newVal);
        
        if (newVal == '1') {
            $(this).addClass('final');
            $(this).html('<i class="fas fa-toggle-on ms-2"></i> المجلس العلمي');
        } else {
            $(this).removeClass('final');
            $(this).html('<i class="fas fa-toggle-off ms-2"></i> نتائج سنوية');
        }
        
        loadTranscriptData();
    });
    
    $('#resetBtn').on('click', function() {
        $('#college_id').val('');
        $('#section_id').empty().append('<option value="">جميع الأقسام</option>');
        $('#program_id').val('');
        $('#batch_id').val('');
        $('#semester_id').val('');
        $('#student_id').empty().append('<option value="">اختر الطالب</option>');
        $('#is_final').val('0');
        $('#toggleFinalBtn').removeClass('final').html('<i class="fas fa-toggle-off ms-2"></i> نتائج سنوية');
        $('#transcriptContainer').html('<div class="transcript-card text-center"><i class="fas fa-filter fa-3x text-muted mb-3 opacity-50"></i><h4>اختر معايير البحث</h4><p class="text-muted">الرجاء اختيار الكلية، الدفعة، والفصل الدراسي لعرض كشف الدرجات</p></div>');
        $('#actionButtons').hide();
    });
    
    // Initial load if filters are selected
    if ($('#college_id').val() && $('#batch_id').val() && $('#semester_id').val()) {
        loadSections($('#college_id').val());
        loadTranscriptData();
        if ($('#transcript_type').val() == 'student') {
            loadStudents();
        }
    }
});

// PDF Download Function
function downloadAsPDF() {
    var element = document.getElementById('transcriptContent');
    if (!element) return;
    
    var loadingMsg = $('<div class="pdf-loading-message">جاري إنشاء ملف PDF...<br>قد يستغرق هذا بضع ثوانٍ</div>');
    $('body').append(loadingMsg);
    loadingMsg.fadeIn(200);
    
    var opt = {
        margin: [0.2, 0.2, 0.2, 0.2],
        filename: 'transcript_' + new Date().getTime() + '.pdf',
        image: { type: 'jpeg', quality: 0.98 },
        html2canvas: { scale: 2, letterRendering: true, useCORS: true, logging: false },
        jsPDF: { unit: 'in', format: 'a4', orientation: 'landscape' }
    };
    
    html2pdf().set(opt).from(element).save().then(function() {
        loadingMsg.fadeOut(200, function() { $(this).remove(); });
    }).catch(function(err) {
        console.error('PDF Error:', err);
        loadingMsg.fadeOut(200, function() { $(this).remove(); });
        alert('حدث خطأ أثناء تحميل PDF. يرجى استخدام زر الطباعة (Ctrl+P).');
    });
}
</script>

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