<?php
//pagelayout of project
include('session_validator.php');
include('includes/db.php');

$alert = "";


// Initialize variables
$search = '';
$class_id = '';
$section_id = '';
$exam_id = '';
$subject_id = '';
$mark_type = '';
$marks_data = [];
$message = '';
$message_type = '';

// Check if user is logged in
$user_id = $_SESSION['user_id'] ?? 0;
$user_role = $_SESSION['user_role'] ?? '';
$teacher_id = $_SESSION['teacher_id'] ?? '';

// Handle form submission for fetching marks
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['fetch_marks'])) {
        $class_id = $_POST['class_id'] ?? '';
        $section_id = $_POST['section_id'] ?? '';
        $exam_id = $_POST['exam_id'] ?? '';
        $subject_id = $_POST['subject_id'] ?? '';
        $mark_type = $_POST['mark_type'] ?? '';
        
        // Validate all fields are selected
        if ($class_id && $section_id && $exam_id && $subject_id && $mark_type) {
            // Fetch marks data
            $query = "SELECT 
                        m.id, 
                        m.student_id,
                        s.name as student_name,
                        s.symbol_no,
                        s.regd_id,
                        m.class_id,
                        c.class,
                        m.section_id,
                        sec.section_name,
                        m.subject_id,
                        sub.subject_name,
                        m.exam_type,
                        et.exam_type as exam_type_name,
                        m.full_marks,
                        m.marks,
                        t1.name as entered_by_name,
                        t2.name as updated_by_name,
                        m.academic_year_id,
                        ay.ay_bs as academic_year,
                        m.mark_type,
                        m.created_at,
                        m.updated_at
                      FROM marks m
                      LEFT JOIN students s ON m.student_id = s.student_id
                      LEFT JOIN classes c ON m.class_id = c.class_id
                      LEFT JOIN sections sec ON m.section_id = sec.section_id
                      LEFT JOIN subjects sub ON m.subject_id = sub.id
                      LEFT JOIN examination_type et ON m.exam_type = et.id
                      LEFT JOIN academic_years ay ON m.academic_year_id = ay.year_id
                      LEFT JOIN teachers t1 ON m.entered_by = t1.teacher_id
                      LEFT JOIN teachers t2 ON m.updated_by = t2.teacher_id
                      WHERE m.class_id = ? 
                        AND m.section_id = ? 
                        AND m.exam_type = ? 
                        AND m.subject_id = ? 
                        AND m.mark_type = ?";
            
            $stmt = $conn->prepare($query);
            $stmt->bind_param("iiiss", $class_id, $section_id, $exam_id, $subject_id, $mark_type);
            $stmt->execute();
            $result = $stmt->get_result();
            $marks_data = $result->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            
            if (empty($marks_data)) {
                $message = "No marks found for the selected criteria.";
                $message_type = 'warning';
            }
        } else {
            $message = "Please select all fields to fetch marks.";
            $message_type = 'warning';
        }
    }
    
    // Handle mark update via AJAX
    if (isset($_POST['update_marks'])) {
        $mark_id = $_POST['mark_id'];
        $new_marks = floatval($_POST['marks']);
        $full_marks = floatval($_POST['full_marks']);
        
        // Validate marks
        if ($new_marks < 0 || $new_marks > $full_marks) {
            $response = array(
                'success' => false,
                'message' => "Error: Marks must be between 0 and $full_marks"
            );
            echo json_encode($response);
            exit;
        }
        
        $sql = "UPDATE marks SET marks = ?, updated_by = ?, updated_at = NOW() WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("dii", $new_marks, $user_id, $mark_id);
        
        if ($stmt->execute()) {
            // Get updated row data
            $query = "SELECT 
                        m.marks,
                        m.full_marks,
                        ROUND((m.marks / m.full_marks) * 100, 2) as percentage,
                        CASE WHEN (m.marks / m.full_marks) * 100 >= 40 THEN 'Pass' ELSE 'Fail' END as status,
                        t2.name as updated_by_name,
                        m.updated_at
                      FROM marks m
                      LEFT JOIN teachers t2 ON m.updated_by = t2.teacher_id
                      WHERE m.id = ?";
            $stmt2 = $conn->prepare($query);
            $stmt2->bind_param("i", $mark_id);
            $stmt2->execute();
            $result = $stmt2->get_result();
            $updated_data = $result->fetch_assoc();
            $stmt2->close();
            
            // Log activity
            $log_sql = "INSERT INTO activity_log (user_id, activity, ip_address, user_agent) VALUES (?, ?, ?, ?)";
            $log_stmt = $conn->prepare($log_sql);
            $activity = "Updated marks ID: $mark_id to $new_marks";
            $log_stmt->bind_param("isss", $user_id, $activity, $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT']);
            $log_stmt->execute();
            $log_stmt->close();
            
            $response = array(
                'success' => true,
                'message' => "Marks updated successfully!",
                'data' => $updated_data
            );
            echo json_encode($response);
        } else {
            $response = array(
                'success' => false,
                'message' => "Error updating marks: " . $conn->error
            );
            echo json_encode($response);
        }
        $stmt->close();
        exit;
    }
    
    // Handle mark deletion via AJAX
    if (isset($_POST['delete_mark'])) {
        $mark_id = $_POST['mark_id'];
        
        $sql = "DELETE FROM marks WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $mark_id);
        
        if ($stmt->execute()) {
            // Log activity
            $log_sql = "INSERT INTO activity_log (user_id, activity, ip_address, user_agent) VALUES (?, ?, ?, ?)";
            $log_stmt = $conn->prepare($log_sql);
            $activity = "Deleted marks ID: $mark_id";
            $log_stmt->bind_param("isss", $user_id, $activity, $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT']);
            $log_stmt->execute();
            $log_stmt->close();
            
            $response = array(
                'success' => true,
                'message' => "Mark record deleted successfully!"
            );
            echo json_encode($response);
        } else {
            $response = array(
                'success' => false,
                'message' => "Error deleting record: " . $conn->error
            );
            echo json_encode($response);
        }
        $stmt->close();
        exit;
    }
}

// Fetch dropdown data
$classes = $conn->query("SELECT class_id, class FROM classes WHERE status = 1 ORDER BY class_numeric")->fetch_all(MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<title>Class Master</title>
<link rel="stylesheet" href="css/bootstrap.min.css" media="screen" >
<link rel="stylesheet" href="css/font-awesome.min.css" media="screen" >
<link rel="stylesheet" href="css/animate-css/animate.min.css" media="screen" >
<link rel="stylesheet" href="css/lobipanel/lobipanel.min.css" media="screen" >
<link rel="stylesheet" href="css/prism/prism.css" media="screen" >
<link rel="stylesheet" href="css/select2/select2.min.css" >
<link rel="stylesheet" href="css/main.css" media="screen" >
<script src="js/modernizr/modernizr.min.js"></script>


<style>
    body {
        background-color: #f5f7fa;
        font-size: 13px;
        padding: 10px 0;
    }
    
    .card {
        border: none;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.08);
        margin-bottom: 20px;
    }
    
    .card-header {
        background: #4e73df;
        color: white;
        padding: 12px 15px;
        border-radius: 8px 8px 0 0 !important;
    }
    
    .card-header h4 {
        font-size: 16px;
        margin: 0;
        font-weight: 600;
    }
    
    .form-label {
        font-size: 12px;
        font-weight: 600;
        color: #4a5568;
        margin-bottom: 4px;
    }
    
    .form-control, .form-select, .select2-container .select2-selection--single {
        height: 34px !important;
        font-size: 13px !important;
        border: 1px solid #d2d6dc;
        border-radius: 4px;
    }
    
    .btn {
        padding: 6px 12px;
        font-size: 12px;
        height: 32px;
        border-radius: 4px;
        display: inline-flex;
        align-items: center;
        gap: 5px;
    }
    
    .badge {
        font-size: 11px;
        padding: 3px 8px;
        font-weight: 500;
    }
    
    .badge-pass {
        background-color: #28a745;
    }
    
    .badge-fail {
        background-color: #dc3545;
    }
    
    .table th {
        font-size: 12px;
        padding: 8px 6px;
        background: #f8f9fc;
        color: #4a5568;
        font-weight: 600;
        border-bottom: 1px solid #e2e8f0;
    }
    
    .table td {
        font-size: 12px;
        padding: 8px 6px;
        vertical-align: middle;
    }
    
    .selection-row {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin-bottom: 10px;
    }
    
    .selection-row .form-group {
        flex: 1;
        min-width: 140px;
        margin-bottom: 0;
    }
    
    .action-buttons {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
        margin-top: 15px;
        padding-top: 15px;
        border-top: 1px solid #e2e8f0;
    }
    
    .loading-overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(255,255,255,0.9);
        z-index: 9999;
        text-align: center;
        padding-top: 20%;
    }
    
    .marks-section {
        display: none;
    }
    
    .marks-input-edit {
        width: 80px;
        height: 30px;
        font-size: 13px;
        text-align: center;
        border: 1px solid #d2d6dc;
        border-radius: 4px;
        padding: 4px;
    }
    
    .info-card {
        background: white;
        border: 1px solid #e2e8f0;
        border-radius: 8px;
        padding: 12px;
        margin-bottom: 15px;
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
        align-items: center;
    }
    
    .info-item {
        display: flex;
        flex-direction: column;
        min-width: 120px;
    }
    
    .info-label {
        font-size: 10px;
        text-transform: uppercase;
        color: #a0aec0;
        font-weight: 600;
        margin-bottom: 1px;
    }
    
    .info-value {
        font-size: 12px;
        font-weight: 600;
        color: #4a5568;
    }
    
    @media (max-width: 768px) {
        .selection-row .form-group {
            min-width: 100%;
        }
        
        .action-buttons {
            flex-direction: column;
        }
        
        .btn {
            width: 100%;
            justify-content: center;
        }
    }
</style>
</head>

<body class="top-navbar-fixed">
    <div class="main-wrapper">
        <?php include('includes/topbar.php'); ?>

        <div class="content-wrapper">
            <div class="content-container">
                <?php include('includes/leftbar.php'); ?>

                <div class="main-page">
                    <div class="container-fluid">
                       <!--  <div class="row page-title-div">
                            <div class="col-md-6">
                                <h2 class="title">Subject Creation</h2>
                            </div>
                        </div> -->
                        <div class="row breadcrumb-div">
                            <div class="col-md-6">
                                <ul class="breadcrumb">
                                    <li><a href="dashboard.php"><i class="fa fa-home"></i> Home</a></li>
                                    <li> Marks </li>
                                    <li class="">Marks Management</li>
                              
                                  </ul>
                            </div>
                        </div>
                    </div>

                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-md-12">
                                

                                <div class="panel">
                                   <!--  <div class="panel-heading">
                                        <div class="panel-title">
                                            <h5>Subjects List</h5>
                                        </div>
                                    </div> -->
                                    <div class="panel-body">

<?= $alert; ?>
    <!-- Loading Overlay -->
    <div class="loading-overlay" id="loading">
        <div class="spinner-border text-primary" role="status" style="width: 2rem; height: 2rem;">
            <span class="sr-only">Loading...</span>
        </div>
        <h5 class="mt-2 text-primary">Processing...</h5>
    </div>

    <div class="card">
        <div class="card-header">
            <h4><i class="fa fa-edit"></i> Manage Marks</h4>
        </div>
        <div class="card-body">
            <!-- Alert Messages -->
            <?php if ($message): ?>
                <div class="alert alert-<?php echo $message_type === 'success' ? 'success' : ($message_type === 'error' ? 'danger' : ($message_type === 'warning' ? 'warning' : 'info')); ?> alert-dismissible fade show" role="alert">
                    <?php echo htmlspecialchars($message); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <!-- Selection Form -->
            <form id="fetchForm" method="POST">
                <div class="selection-row">
                    <!-- Class -->
                    <div class="form-group">
                        <label for="class_id" class="form-label">
                            <i class="fa fa-graduation-cap"></i> Class *
                        </label>
                        <select id="class_id" name="class_id" class="form-control select2" required style="width: 100%">
                            <option value="">Select Class</option>
                            <?php foreach ($classes as $class): ?>
                                <option value="<?php echo $class['class_id']; ?>" 
                                    <?php echo $class_id == $class['class_id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($class['class']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <!-- Section -->
                    <div class="form-group">
                        <label for="section_id" class="form-label">
                            <i class="fa fa-columns"></i> Section *
                        </label>
                        <select id="section_id" name="section_id" class="form-control select2" disabled required style="width: 100%">
                            <option value="">Select Section</option>
                        </select>
                    </div>

                    <!-- Exam -->
                    <div class="form-group">
                        <label for="exam_id" class="form-label">
                            <i class="fa fa-calendar"></i> Exam *
                        </label>
                        <select id="exam_id" name="exam_id" class="form-control select2" disabled required style="width: 100%">
                            <option value="">Select Exam</option>
                        </select>
                    </div>

                    <!-- Subject -->
                    <div class="form-group">
                        <label for="subject_id" class="form-label">
                            <i class="fa fa-book"></i> Subject *
                        </label>
                        <select id="subject_id" name="subject_id" class="form-control select2" disabled required style="width: 100%">
                            <option value="">Select Subject</option>
                        </select>
                    </div>

                    <!-- Mark Type -->
                    <div class="form-group">
                        <label for="mark_type" class="form-label">
                            <i class="fa fa-tag"></i> Type *
                        </label>
                        <select id="mark_type" name="mark_type" class="form-control select2" required style="width: 100%">
                            <option value="">Select Type</option>
                            <option value="theory" <?php echo $mark_type == 'theory' ? 'selected' : ''; ?>>Theory</option>
                            <option value="practical" <?php echo $mark_type == 'practical' ? 'selected' : ''; ?>>Practical</option>
                        </select>
                    </div>
                </div>

                <div class="action-buttons">
                    <button type="submit" name="fetch_marks" class="btn btn-primary" id="fetchBtn">
                        <i class="fa fa-search"></i> Fetch Marks
                    </button>
                    <button type="button" class="btn btn-outline-secondary" id="clearBtn">
                        <i class="fa fa-times"></i> Clear
                    </button>
                    <a href="marksentry.php" class="btn btn-info">
                        <i class="fa fa-plus"></i> Add New Marks
                    </a>
                    <a href="dashboard.php" class="btn btn-outline-dark">
                        <i class="fa fa-home"></i> Dashboard
                    </a>
                </div>
            </form>

            <!-- Marks Section (hidden by default) -->
            <div id="marks-section" class="marks-section">
                <!-- Info Card -->
                <div class="info-card">
                    <div class="info-item">
                        <span class="info-label">Class / Section</span>
                        <span class="info-value" id="info-class-section">--</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">Subject</span>
                        <span class="info-value" id="info-subject">--</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">Exam</span>
                        <span class="info-value" id="info-exam">--</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">Type</span>
                        <span class="info-value" id="info-type">--</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">Students</span>
                        <span class="info-value" id="info-students">0</span>
                    </div>
                </div>

                <!-- Marks Table -->
                <div class="table-responsive">
                    <table id="marksTable" class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>S.N.</th>
                                <th>Student Name</th>
                                <th>Symbol No</th>
                                <th>Full Marks</th>
                                <th>Marks</th>
                                <!-- <th>Percentage</th> -->
                                <!-- <th>Status</th> -->
                                <th>Entered By</th>
                                <th>Updated</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="marksTableBody">
                            <!-- Data will be loaded here -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Edit Marks Modal -->
<div class="modal fade" id="editModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title">Edit Marks</h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editForm">
                <div class="modal-body">
                    <input type="hidden" id="edit_mark_id" name="mark_id">
                    <input type="hidden" id="edit_full_marks" name="full_marks">
                    <input type="hidden" id="edit_student_name" name="student_name">
                    
                    <div class="mb-2">
                        <label class="form-label small">Student</label>
                        <p class="form-control-static small fw-bold" id="display_student_name"></p>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit_marks" class="form-label">Marks</label>
                        <input type="number" class="form-control marks-input-edit" id="edit_marks" name="marks" 
                               min="0" step="0.01" required>
                        <div class="form-text small">Max: <span id="max_marks">0</span></div>
                    </div>
                    <div id="percentage_display" class="alert alert-info p-2 small"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-sm btn-primary" id="updateBtn">Update</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title">Confirm Delete</h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p class="small">Delete marks for <strong id="delete_student_name"></strong>?</p>
                <p class="small text-danger">This action cannot be undone.</p>
            </div>
            <div class="modal-footer">
                <form id="deleteForm">
                    <input type="hidden" id="delete_mark_id" name="mark_id">
                    <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-sm btn-danger">Delete</button>
                </form>
            </div>
        </div>
    </div>
 </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>


<script src="js/jquery/jquery-2.2.4.min.js"></script>
<script src="js/bootstrap/bootstrap.min.js"></script>
<script src="js/pace/pace.min.js"></script>
<script src="js/lobipanel/lobipanel.min.js"></script>
<script src="js/iscroll/iscroll.js"></script>
<script src="js/prism/prism.js"></script>
<script src="js/select2/select2.min.js"></script>
<script src="js/main.js"></script>

<script>
$(document).ready(function() {
    // Initialize Select2
    $('.select2').select2({
        width: '100%',
        placeholder: "Select",
        minimumResultsForSearch: 6
    });
    
    // Variables to store selected values
    let selectedClass = '';
    let selectedSection = '';
    let selectedExam = '';
    let selectedSubject = '';
    let selectedMarkType = '';
    
    // Class change
    $('#class_id').change(function() {
        let classId = $(this).val();
        selectedClass = classId;
        
        if (classId) {
            $('#section_id').prop('disabled', false);
            $('#exam_id, #subject_id').prop('disabled', true);
            
            // Clear dependent fields
            $('#section_id').html('<option value="">Select Section</option>').trigger('change');
            $('#exam_id').html('<option value="">Select Exam</option>').trigger('change');
            $('#subject_id').html('<option value="">Select Subject</option>').trigger('change');
            
            // Hide marks section
            $('#marks-section').hide();
            
            // Load sections
            loadSections(classId);
        } else {
            resetAllFields();
        }
    });
    
    // Section change
    $('#section_id').change(function() {
        let sectionId = $(this).val();
        selectedSection = sectionId;
        
        if (selectedClass && sectionId) {
            $('#exam_id').prop('disabled', false);
            $('#subject_id').prop('disabled', true);
            
            // Clear dependent fields
            $('#exam_id').html('<option value="">Select Exam</option>').trigger('change');
            $('#subject_id').html('<option value="">Select Subject</option>').trigger('change');
            
            // Hide marks section
            $('#marks-section').hide();
            
            // Load exams
            loadExams(selectedClass);
        }
    });
    
    // Exam change
    $('#exam_id').change(function() {
        let examId = $(this).val();
        selectedExam = examId;
        
        if (selectedClass && selectedSection && examId) {
            $('#subject_id').prop('disabled', false);
            
            // Clear subject field
            $('#subject_id').html('<option value="">Select Subject</option>').trigger('change');
            
            // Hide marks section
            $('#marks-section').hide();
            
            // Load subjects
            loadSubjects(selectedClass, selectedSection, examId);
        }
    });
    
    // Subject change
    $('#subject_id').change(function() {
        selectedSubject = $(this).val();
        if (selectedSubject) {
            $('#marks-section').hide();
        }
    });
    
    // Mark Type change
    $('#mark_type').change(function() {
        selectedMarkType = $(this).val();
        if (selectedMarkType) {
            $('#marks-section').hide();
        }
    });
    
    // Load sections
    function loadSections(classId) {
        $('#section_id').html('<option value="">Loading...</option>').trigger('change');
        
        $.ajax({
            url: 'ajax/get_sections_by_class.php',
            type: 'GET',
            data: { class_id: classId },
            dataType: 'json',
            success: function(sections) {
                let options = '<option value="">Select Section</option>';
                if (sections && sections.length > 0) {
                    sections.forEach(function(section) {
                        options += '<option value="' + section.section_id + '">' + section.section_name + '</option>';
                    });
                }
                $('#section_id').html(options).trigger('change');
            },
            error: function() {
                $('#section_id').html('<option value="">Error loading</option>').trigger('change');
            }
        });
    }
    
    // Load exams
    function loadExams(classId) {
        $('#exam_id').html('<option value="">Loading...</option>').trigger('change');
        
        $.ajax({
            url: 'ajax/get_exams_by_class.php',
            type: 'GET',
            data: { class_id: classId },
            dataType: 'json',
            success: function(exams) {
                let options = '<option value="">Select Exam</option>';
                if (exams && exams.length > 0) {
                    exams.forEach(function(exam) {
                        options += '<option value="' + exam.id + '">' + exam.exam_type + ' - ' + exam.exm_year + '</option>';
                    });
                }
                $('#exam_id').html(options).trigger('change');
            },
            error: function() {
                $('#exam_id').html('<option value="">Error loading</option>').trigger('change');
            }
        });
    }
    
   // Load subjects
    function loadSubjects(classId, sectionId) {
        $.ajax({
            url: 'ajax/get_subjects_by_class_section.php',
            type: 'GET',
            data: { class_id: classId, section_id: sectionId },
            dataType: 'json',
            success: function (data) {
                let options = '<option value="">Select</option>';
                if (data.success && data.subjects && data.subjects.length > 0) {
                    data.subjects.forEach(function (subject) {
                        options += '<option value="' + subject.subject_id + '" ' +
                                  'data-theory="' + (subject.theory_full_marks || 0) + '" ' +
                                  'data-internal="' + (subject.internal_full_marks || 0) + '">' + 
                                  subject.subject_name + '</option>';
                    });
                }
                $('#subject_id').html(options).trigger('change');
            },
            error: function () {
                $('#subject_id').html('<option value="">Error loading</option>').trigger('change');
            }
        });
    }
    
    // Reset all fields
    function resetAllFields() {
        $('#section_id').prop('disabled', true).html('<option value="">Select Section</option>').trigger('change');
        $('#exam_id').prop('disabled', true).html('<option value="">Select Exam</option>').trigger('change');
        $('#subject_id').prop('disabled', true).html('<option value="">Select Subject</option>').trigger('change');
        $('#mark_type').val('').trigger('change');
        $('#marks-section').hide();
        
        selectedClass = '';
        selectedSection = '';
        selectedExam = '';
        selectedSubject = '';
        selectedMarkType = '';
    }
    
    // Clear button
    $('#clearBtn').click(function() {
        resetAllFields();
        $('#class_id').val('').trigger('change');
    });
    
    // Fetch marks form submission
    $('#fetchForm').submit(function(e) {
        e.preventDefault();
        
        if (!validateSelection()) {
            Swal.fire({
                icon: 'warning',
                title: 'Missing Fields',
                text: 'Please select all fields to fetch marks.',
                confirmButtonColor: '#ffc107'
            });
            return false;
        }
        
        fetchMarks();
    });
    
    function validateSelection() {
        return selectedClass && selectedSection && selectedExam && selectedSubject && selectedMarkType;
    }
    
    function fetchMarks() {
        $('#loading').show();
        $('#fetchBtn').prop('disabled', true).html('<span class="loading-spinner"></span> Loading...');
        
        $.ajax({
            url: 'ajax/get_marks_for_management.php',
            type: 'POST',
            data: {
                class_id: selectedClass,
                section_id: selectedSection,
                exam_id: selectedExam,
                subject_id: selectedSubject,
                mark_type: selectedMarkType
            },
            success: function(response) {
                $('#loading').hide();
                $('#fetchBtn').prop('disabled', false).html('<i class="fa fa-search"></i> Fetch Marks');
                
                try {
                    let data = JSON.parse(response);
                    
                    if (data.success) {
                        // Update info card
                        $('#info-class-section').text(data.info.class + ' - ' + data.info.section);
                        $('#info-subject').text(data.info.subject);
                        $('#info-exam').text(data.info.exam);
                        $('#info-type').text(data.info.mark_type);
                        $('#info-students').text(data.marks.length);
                        
                        // Build table
                        let tableHtml = '';
                        if (data.marks.length > 0) {
                            data.marks.forEach(function(row, index) {
                                let percentage = row.full_marks > 0 ? ((row.marks / row.full_marks) * 100).toFixed(2) : 0;
                                let status = percentage >= 40 ? 'Pass' : 'Fail';
                                let statusClass = status === 'Pass' ? 'badge-pass' : 'badge-fail';
                                
                                tableHtml += `
                                    <tr id="row-${row.id}">
                                        <td>${index + 1}</td>
                                        <td>${row.student_name}</td>
                                        <td>${row.symbol_no || 'N/A'}</td>
                                        <td>${row.full_marks}</td>
                                        <td class="fw-bold">${row.marks}</td>
                                        <!--td class="${status === 'Pass' ? 'text-success' : 'text-danger'} fw-bold">${percentage}%</td>
                                        <td><span class="badge ${statusClass}">${status}</span></td-->
                                        <td><small>${row.entered_by_name}<br>${row.created_at}</small></td>
                                        <td><small>${row.updated_by_name || 'N/A'}<br>${row.updated_at}</small></td>
                                        <td>
                                            <div class="d-flex gap-1">
                                                <button class="btn btn-sm btn-warning edit-btn" 
                                                        data-id="${row.id}"
                                                        data-marks="${row.marks}"
                                                        data-fullmarks="${row.full_marks}"
                                                        data-student="${row.student_name}">
                                                    <i class="fa fa-edit"></i>
                                                </button>
                                                <?php if ($user_role === 'admin'): ?>
                                                <button class="btn btn-sm btn-danger delete-btn" 
                                                        data-id="${row.id}"
                                                        data-student="${row.student_name}">
                                                    <i class="fa fa-trash"></i>
                                                </button>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                `;
                            });
                        } else {
                            tableHtml = '<tr><td colspan="10" class="text-center">No marks found</td></tr>';
                        }
                        
                        $('#marksTableBody').html(tableHtml);
                        $('#marks-section').show();
                        
                        // Scroll to marks section
                        $('html, body').animate({
                            scrollTop: $('#marks-section').offset().top - 20
                        }, 500);
                        
                    } else {
                        Swal.fire({
                            icon: 'warning',
                            title: 'No Data',
                            text: data.message || 'No marks found for the selected criteria.',
                            confirmButtonColor: '#ffc107'
                        });
                        $('#marks-section').hide();
                    }
                } catch (e) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to parse response. Please try again.',
                        confirmButtonColor: '#dc3545'
                    });
                    $('#marks-section').hide();
                }
            },
            error: function() {
                $('#loading').hide();
                $('#fetchBtn').prop('disabled', false).html('<i class="fa fa-search"></i> Fetch Marks');
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Failed to fetch marks. Please try again.',
                    confirmButtonColor: '#dc3545'
                });
                $('#marks-section').hide();
            }
        });
    }
    
    // Edit button click
    $(document).on('click', '.edit-btn', function() {
        let id = $(this).data('id');
        let marks = $(this).data('marks');
        let fullMarks = $(this).data('fullmarks');
        let studentName = $(this).data('student');
        
        $('#edit_mark_id').val(id);
        $('#edit_marks').val(marks);
        $('#edit_full_marks').val(fullMarks);
        $('#edit_student_name').val(studentName);
        $('#display_student_name').text(studentName);
        $('#max_marks').text(fullMarks);
        
        updatePercentage(marks, fullMarks);
        $('#edit_marks').attr('max', fullMarks);
        
        $('#editModal').modal('show');
        setTimeout(function() {
            $('#edit_marks').focus().select();
        }, 500);
    });
    
    // Delete button click
    $(document).on('click', '.delete-btn', function() {
        let id = $(this).data('id');
        let studentName = $(this).data('student');
        
        $('#delete_mark_id').val(id);
        $('#delete_student_name').text(studentName);
        
        $('#deleteModal').modal('show');
    });
    
    // Update percentage display
    function updatePercentage(marks, fullMarks) {
        if (fullMarks > 0) {
            let percentage = ((marks / fullMarks) * 100).toFixed(2);
            let status = percentage >= 40 ? 'Pass' : 'Fail';
            let statusClass = status === 'Pass' ? 'text-success' : 'text-danger';
            
            $('#percentage_display').html(
                `<strong>Percentage:</strong> <span class="${statusClass}">${percentage}%</span><br>` +
                `<strong>Status:</strong> <span class="${statusClass}">${status}</span>`
            );
        } else {
            $('#percentage_display').html('<strong>Percentage:</strong> Cannot calculate');
        }
    }
    
    // Real-time percentage update in edit modal
    $('#edit_marks').on('input', function() {
        let marks = parseFloat($(this).val()) || 0;
        let fullMarks = parseFloat($('#edit_full_marks').val()) || 0;
        updatePercentage(marks, fullMarks);
    });
    
    // Edit form submission (AJAX)
    $('#editForm').submit(function(e) {
        e.preventDefault();
        
        let marks = parseFloat($('#edit_marks').val());
        let fullMarks = parseFloat($('#edit_full_marks').val());
        
        if (isNaN(marks) || marks < 0 || marks > fullMarks) {
            Swal.fire({
                icon: 'error',
                title: 'Invalid Marks',
                text: `Please enter marks between 0 and ${fullMarks}`,
                confirmButtonColor: '#dc3545'
            });
            $('#edit_marks').focus().select();
            return false;
        }
        
        $('#updateBtn').prop('disabled', true).html('<span class="loading-spinner"></span> Updating...');
        
        let formData = $(this).serialize();
        
        $.ajax({
            url: 'edit_marks1.php',
            type: 'POST',
            data: formData + '&update_marks=1',
            success: function(response) {
                try {
                    let data = JSON.parse(response);
                    
                    if (data.success) {
                        // Update the row in table without reloading
                        let rowId = $('#edit_mark_id').val();
                        let row = $('#row-' + rowId);
                        
                        // Update row data
                        row.find('td:nth-child(5)').text(data.data.marks);
                        row.find('td:nth-child(6)').html(`${data.data.percentage}% <small class="d-block">${data.data.status}</small>`);
                        row.find('td:nth-child(7) span').removeClass('badge-pass badge-fail')
                            .addClass(data.data.status === 'Pass' ? 'badge-pass' : 'badge-fail')
                            .text(data.data.status);
                        row.find('td:nth-child(9)').html(`<small>${data.data.updated_by_name}<br>${data.data.updated_at}</small>`);
                        
                        // Close modal
                        $('#editModal').modal('hide');
                        
                        // Show success message
                        Swal.fire({
                            icon: 'success',
                            title: 'Success',
                            text: data.message,
                            confirmButtonColor: '#28a745',
                            timer: 2000,
                            showConfirmButton: false
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: data.message,
                            confirmButtonColor: '#dc3545'
                        });
                    }
                } catch (e) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to update marks. Please try again.',
                        confirmButtonColor: '#dc3545'
                    });
                }
                
                $('#updateBtn').prop('disabled', false).html('Update');
            },
            error: function() {
                $('#updateBtn').prop('disabled', false).html('Update');
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Failed to update marks. Please try again.',
                    confirmButtonColor: '#dc3545'
                });
            }
        });
    });
    
    // Delete form submission (AJAX)
    $('#deleteForm').submit(function(e) {
        e.preventDefault();
        
        let formData = $(this).serialize();
        let rowId = $('#delete_mark_id').val();
        
        $.ajax({
            url: 'marks_management.php',
            type: 'POST',
            data: formData + '&delete_mark=1',
            success: function(response) {
                try {
                    let data = JSON.parse(response);
                    
                    if (data.success) {
                        // Remove row from table
                        $('#row-' + rowId).remove();
                        
                        // Close modal
                        $('#deleteModal').modal('hide');
                        
                        // Update student count
                        let studentCount = $('#marksTableBody tr').length;
                        $('#info-students').text(studentCount);
                        
                        // Show success message
                        Swal.fire({
                            icon: 'success',
                            title: 'Success',
                            text: data.message,
                            confirmButtonColor: '#28a745',
                            timer: 2000,
                            showConfirmButton: false
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: data.message,
                            confirmButtonColor: '#dc3545'
                        });
                    }
                } catch (e) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to delete marks. Please try again.',
                        confirmButtonColor: '#dc3545'
                    });
                }
            },
            error: function() {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Failed to delete marks. Please try again.',
                    confirmButtonColor: '#dc3545'
                });
            }
        });
    });
    
    // Reset modal when hidden
    $('#editModal').on('hidden.bs.modal', function() {
        $('#editForm')[0].reset();
        $('#percentage_display').empty();
        $('#updateBtn').prop('disabled', false).html('Update');
    });
    
    $('#deleteModal').on('hidden.bs.modal', function() {
        $('#deleteForm')[0].reset();
    });
});
</script>
</body>
</html>