<?php
// transcript.php - Complete version with AJAX loading and advanced filters
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 = ? AND deleted_at IS NULL ORDER BY name";
        $stmt = $mysqli1->prepare($query);
        if ($stmt) {
            $stmt->bind_param("i", $ajax_college_id);
            $stmt->execute();
            $result = $stmt->get_result();
            if ($result) {
                while ($row = $result->fetch_assoc()) {
                    $sections_data[] = [
                        'id' => (int)$row['id'],
                        'name' => validateString($row['name'])
                    ];
                }
            }
            $stmt->close();
        }
    }
    
    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 = ? 
              AND s.batch_id = ? 
              AND s.deleted_at IS NULL";
    
    $params = [$ajax_college_id, $ajax_batch_id];
    $types = "ii";
    
    if ($ajax_section_id > 0) {
        $query .= " AND s.section_id = ?";
        $params[] = $ajax_section_id;
        $types .= "i";
    }
    
    if ($ajax_program_id > 0) {
        $query .= " AND s.program_id = ?";
        $params[] = $ajax_program_id;
        $types .= "i";
    }
    
    $query .= " ORDER BY s.student_name";
    
    $stmt = $mysqli1->prepare($query);
    if ($stmt) {
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $students_data[] = [
                    'id' => validateString($row['student_id']),
                    'name' => validateString($row['student_name'])
                ];
            }
        }
        $stmt->close();
    }
    
    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
    $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,
        s.program_id,
        s.section_id
    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, s.program_id
";
        
         $stmt = $mysqli1->prepare($subjectQuery);
if ($stmt) {
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
    $counter = 1;
    while ($row = $result->fetch_assoc()) {
        // Create a unique key combining subject code, program, and section
        $unique_key = $row['subjectcode'] . '_' . $row['program_id'] . '_' . $row['section_id'];
        
        $subject_list[] = [
            'no' => $counter++,
            'unique_key' => $unique_key,
            'code' => validateString($row['subjectcode']),
            'name_ar' => validateString($row['subjectnamea']),
            'credit_hours' => (float)$row['credit_hours'],
            'program_id' => (int)$row['program_id'],
            'section_id' => (int)$row['section_id']
        ];
    }
    $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 with regrade and reregrade
        $studentQuery = "
            SELECT 
                s.student_id,
                s.student_name,
                ss.subjectcode,
                ss.degree,
                ss.grade,
                ss.regrade,
                ss.reregrade,
                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' => []
                    ];
                }
                
                // Get grade values
                $grade_val = $row['grade'] !== null ? validateString($row['grade']) : '';
                $regrade_val = $row['regrade'] !== null ? validateString($row['regrade']) : '';
                $reregrade_val = $row['reregrade'] !== null ? validateString($row['reregrade']) : '';
                
                // Determine final grade based on priority: reregrade > regrade > grade
                $final_grade = '';
                if ($reregrade_val !== '') {
                    $final_grade = $reregrade_val;
                } elseif ($regrade_val !== '') {
                    $final_grade = $regrade_val;
                } else {
                    $final_grade = $grade_val;
                }
                
                // Build display grade in format: reregrade/regrade/grade
                $display_parts = [];
                if ($reregrade_val !== '') {
                    $display_parts[] = $reregrade_val;
                }
                if ($regrade_val !== '') {
                    $display_parts[] = $regrade_val;
                }
                if ($grade_val !== '' && ($reregrade_val !== '' || $regrade_val !== '')) {
                    $display_parts[] = $grade_val;
                }
                
                $display_grade = !empty($display_parts) ? implode('/', $display_parts) : $grade_val;
                
                $all_students[$student_id_key]['grades'][$row['subjectcode']] = [
                    'degree' => $row['degree'] !== null ? (float)$row['degree'] : null,
                    'grade' => $final_grade,
                    'display_grade' => $display_grade,
                    'original_grade' => $grade_val,
                    'regrade' => $regrade_val,
                    'reregrade' => $reregrade_val,
                    '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 = ? AND deleted_at IS NULL ORDER BY name";
    $stmt = $mysqli1->prepare($sections_query);
    if ($stmt) {
        $stmt->bind_param("i", $college_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $sections[] = [
                    'id' => (int)$row['id'],
                    'name' => validateString($row['name'])
                ];
            }
        }
        $stmt->close();
    }
}

include 'header.php';
?>

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

<style>
/* CSS to make dropdown arrows appear on the left for RTL */
.form-select {
    background-position: left 0.75rem center !important;
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e") !important;
    background-repeat: no-repeat !important;
    background-size: 16px 12px !important;
    padding-right: 0.75rem !important;
    padding-left: 2rem !important;
    text-align: right;
}

/* For select elements with RTL text */
select.form-select {
    direction: rtl;
}

/* Ensure options text aligns properly */
select.form-select option {
    direction: rtl;
    text-align: right;
}

/* Grade display styling */
.grade-display {
    font-weight: 500;
}

.grade-with-history {
    cursor: help;
    border-bottom: 1px dotted #999;
}

.grade-history-tooltip {
    font-size: 11px;
    color: #666;
}

/* Custom grade display cell */
.grade-cell {
    font-family: monospace;
    font-weight: bold;
    direction: ltr;
    text-align: center;
}

/* F grade highlighting */
.f-grade-highlight {
    background-color: #ffebee !important;
    color: #c62828 !important;
    font-weight: bold !important;
}

/* Additional styling for filter section */
.btn-primary {
    transition: all 0.3s ease;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}

.filter-controls {
    background: #f8f9fa;
    padding: 15px;
    border-radius: 10px;
    margin-top: 10px;
}
</style>

<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>
            
            <!-- Advanced Filter Controls -->
            <div class="filter-controls mt-3">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">عرض الدرجات</label>
                        <select class="form-select" id="display_mode">
                            <option value="grade_only">عرض التقدير فقط</option>
                            <option value="degree_only">عرض الدرجة فقط</option>
                            <option value="both">عرض التقدير والدرجة</option>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label">تمييز درجة F</label>
                        <select class="form-select" id="highlight_f">
                            <option value="no">لا</option>
                            <option value="yes">نعم، تمييز باللون الأحمر</option>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label">عرض المواد بـ</label>
                        <select class="form-select" id="subject_display">
                            <option value="code">رمز المادة</option>
                            <option value="name">اسم المادة</option>
                            <option value="both">الرمز والاسم</option>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <div class="d-flex gap-3 justify-content-end">
                            <button type="button" id="applyFiltersBtn" class="btn-primary" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none; padding: 8px 20px; border-radius: 8px; color: white; margin-top: 30px;">
                                <i class="fas fa-filter ms-2"></i> تطبيق
                            </button>
                        </div>
                    </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();
        var displayMode = $('#display_mode').val();
        var highlightF = $('#highlight_f').val();
        var subjectDisplay = $('#subject_display').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, displayMode, highlightF, subjectDisplay);
                    $('#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 get grade display with history
    function getGradeWithHistory(gradeData) {
        if (!gradeData) {
            return '--';
        }
        
        var displayGrade = gradeData.display_grade || '';
        
        if (!displayGrade) {
            return '--';
        }
        
        // Build history string for tooltip
        var historyParts = [];
        if (gradeData.reregrade) {
            historyParts.push('إعادة تقدير ثانية: ' + gradeData.reregrade);
        }
        if (gradeData.regrade) {
            historyParts.push('إعادة تقدير: ' + gradeData.regrade);
        }
        if (gradeData.original_grade && (gradeData.reregrade || gradeData.regrade)) {
            historyParts.push('الدرجة الأصلية: ' + gradeData.original_grade);
        }
        
        if (historyParts.length > 0) {
            return '<span class="grade-with-history grade-cell" title="' + historyParts.join(' | ') + '">' + displayGrade + '</span>';
        }
        
        return '<span class="grade-cell">' + displayGrade + '</span>';
    }
    
    // Function to render transcript with new features
    function renderTranscript(data, displayMode, highlightF, subjectDisplay) {
        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
        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 - with display mode and highlight F
        html += '<div class="table-header"><i class="fas fa-users ms-2"></i> جدول (3) درجات الطلاب</div>';
        
        var colspanCount = (displayMode === 'both') ? 2 : 1;
        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>';
        
        // Subject headers based on display mode
        $.each(data.subject_list, function(i, subject) {
            var subjectHeader = '';
            if (subjectDisplay === 'code') {
                subjectHeader = escapeHtml(subject.code);
            } else if (subjectDisplay === 'name') {
                subjectHeader = escapeHtml(subject.name_ar);
            } else {
                subjectHeader = escapeHtml(subject.code) + '<br><small>' + escapeHtml(subject.name_ar) + '</small>';
            }
            html += '<th colspan="' + colspanCount + '">' + subjectHeader + '</th>';
        });
        
        html += '<th rowspan="2">الحالة</th></tr>';
        html += '</thead><thead>';
        
        // Sub-headers based on display mode
        if (displayMode === 'both') {
            $.each(data.subject_list, function(i, subject) {
                html += '<th>تقدير</th><th>درجة</th>';
            });
        } else if (displayMode === 'grade_only') {
            $.each(data.subject_list, function(i, subject) {
                html += '<th>تقدير</th>';
            });
        } else {
            $.each(data.subject_list, function(i, subject) {
                html += '<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 gradeData = student.grades[subject.code] || null;
                var gradeText = (gradeData && gradeData.display_grade) ? gradeData.display_grade : '--';
                var degreeText = (gradeData && gradeData.degree !== null) ? Math.round(gradeData.degree) : '--';
                
                // Check if grade contains F for highlighting
                var hasF = (gradeText && gradeText.indexOf('F') !== -1);
                var highlightClass = (highlightF === 'yes' && hasF) ? 'f-grade-highlight' : '';
                
                if (displayMode === 'both') {
                    // Show both grade and degree
                    html += '<td class="' + highlightClass + '" style="text-align: center;">' + gradeText + '</td>';
                    html += '<td class="' + highlightClass + '" style="text-align: center;">' + degreeText + '</td>';
                } else if (displayMode === 'grade_only') {
                    // Show only grade
                    html += '<td class="' + highlightClass + '" style="text-align: center;">' + gradeText + '</td>';
                } else {
                    // Show only degree
                    html += '<td class="' + highlightClass + '" style="text-align: center;">' + 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>';
        
        // Legend
        html += '<div class="grade-legend no-print" style="margin-top: 10px; padding: 8px; background: #f8f9fa; border-radius: 5px; font-size: 11px; direction: rtl;">';
        html += '<strong><i class="fas fa-info-circle"></i> ملاحظة:</strong> ';
        html += 'الدرجات تظهر بالتنسيق: <strong>إعادة تقدير ثانية / إعادة تقدير / الدرجة الأصلية</strong> (مثال: F/F/A يعني إعادة تقدير ثانية=F، إعادة تقدير=F، الدرجة الأصلية=A)';
        if (highlightF === 'yes') {
            html += ' | <span style="background-color: #ffebee; color: #c62828; padding: 2px 5px; border-radius: 3px;">الدرجات التي تحتوي على F مميزة باللون الأحمر</span>';
        }
        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 && 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(xhr, status, error) {
                    console.error('AJAX Error:', error);
                    $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 && 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
    $('#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();
        if (collegeId) {
            loadSections(collegeId);
        } else {
            $('#section_id').empty().append('<option value="">جميع الأقسام</option>');
        }
        loadTranscriptData();
    });
    
    $('#section_id, #program_id, #batch_id, #semester_id').on('change', function() {
        loadTranscriptData();
        if ($('#transcript_type').val() == 'student') {
            loadStudents();
        }
    });
    
    $('#display_mode, #highlight_f, #subject_display').on('change', function() {
        loadTranscriptData();
    });
    
    $('#applyFiltersBtn').on('click', function() {
        loadTranscriptData();
    });
    
    $('#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');
        $('#display_mode').val('grade_only');
        $('#highlight_f').val('no');
        $('#subject_display').val('code');
        $('#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'; ?>