<?php
include('session_validator.php');
include("includes/db.php");

// Fetch classes for the dropdown
$classQuery = "SELECT class_id, class, class_numeric FROM classes WHERE status = 1 ORDER BY class_numeric";
$classResult = $conn->query($classQuery);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>SRMS Admin - Change Student Subjects</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/font-awesome.min.css">
    <link rel="stylesheet" href="css/animate-css/animate.min.css">
    <link rel="stylesheet" href="css/lobipanel/lobipanel.min.css">
    <link rel="stylesheet" href="css/select2/select2.min.css">
    <link rel="stylesheet" href="css/main.css">
    <script src="js/modernizr/modernizr.min.js"></script>
    <style>
        .academic-year-badge {
            background-color: #17a2b8;
            color: white;
            padding: 3px 8px;
            border-radius: 3px;
            font-size: 0.8em;
        }
        .subject-select {
            min-width: 180px;
        }
        .modal-lg {
            max-width: 900px;
        }
        .section-info {
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 15px;
        }
        .empty-subject {
            color: #6c757d;
            font-style: italic;
        }
        .subject-row {
            margin-bottom: 10px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }
        .subject-row:last-child {
            border-bottom: none;
        }
    </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">Change Student Subjects</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>Subjects</li>
                                <li class="active">Change Student Subjects</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><i class="fa fa-exchange"></i> Change Subjects for Student</h5>
                                    </div>
                                </div>
                                <div class="panel-body">
                                    <form id="selectClassStudentForm">
                                        <div class="row">
                                               <div class="col-md-4">
                                                <div class="form-group">
                                                    <label for="academic_year">Academic Year *</label>
                                                    <select id="academic_year" name="academic_year" class="form-control select2" required>
                                                        <option value="">-- Select Academic Year --</option>
                                                        <?php
                                                        $academic_years_query = "SELECT * FROM academic_years ORDER BY start_date DESC";
                                                        $academic_years_result = $conn->query($academic_years_query);
                                                        if ($academic_years_result->num_rows > 0) {
                                                            while ($year = $academic_years_result->fetch_assoc()) {
                                                                $display_text = $year['ay_ad'] . ' (' . $year['ay_bs'] . ')';
                                                                if ($year['status'] == 'active') {
                                                                    $display_text .= ' (Active)';
                                                                }
                                                                echo '<option value="' . $year['ay_ad'] . '">' . $display_text . '</option>';
                                                            }
                                                        }
                                                        ?>
                                                    </select>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label for="class_id">Select Class *</label>
                                                    <select id="class_id" name="class_id" class="form-control select2" required>
                                                        <option value="">-- Select Class --</option>
                                                        <?php while ($row = $classResult->fetch_assoc()) { ?>
                                                            <option value="<?= $row['class_id'] ?>">
                                                                Class <?= htmlspecialchars($row['class']) ?> (Grade <?= $row['class_numeric'] ?>)
                                                            </option>
                                                        <?php } ?>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label for="student_id">Select Student *</label>
                                                    <select id="student_id" name="student_id" class="form-control select2" required>
                                                        <option value="">-- Select Class First --</option>
                                                    </select>
                                                </div>
                                            </div>

                                         
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-12">
                                                <button type="button" id="proceedBtn" class="btn btn-primary">
                                                    <i class="fa fa-search"></i> Load Student Subjects
                                                </button>
                                                <button type="reset" class="btn btn-secondary">
                                                    <i class="fa fa-refresh"></i> Reset
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Modal for editing subjects -->
                <div id="subjectModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="subjectModalLabel" aria-hidden="true">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header bg-primary text-white">
                                <h5 class="modal-title" id="subjectModalLabel">
                                    <i class="fa fa-edit"></i> Edit Assigned Subjects
                                </h5>
                                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <div class="modal-body" id="modalBodyContent">
                                <!-- Subject form content will be populated by AJAX -->
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">
                                    <i class="fa fa-times"></i> Close
                                </button>
                                <button type="button" id="saveSubjectsBtn" class="btn btn-success">
                                    <i class="fa fa-save"></i> Save Changes
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- End Modal -->
            </div>
        </div>
    </div>
</div>

<!-- JavaScript Files -->
<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 src="js/sweetalert2.all.min.js"></script>

<script>
$(document).ready(function () {
    // Initialize Select2
    $('.select2').select2({
        width: '100%'
    });

    // Load students based on selected class
    $('#class_id').change(function () {
        var classId = $(this).val();
        var academicYear = $('#academic_year').val();
        
        if (classId && academicYear) {
            loadStudentsForClass(classId, academicYear);
        } else if (classId) {
            $('#student_id').html('<option value="">-- Select Academic Year First --</option>').prop('disabled', false);
        } else {
            $('#student_id').html('<option value="">-- Select Class First --</option>').prop('disabled', true);
        }
    });

    // Load students when academic year changes
    $('#academic_year').change(function () {
        var classId = $('#class_id').val();
        var academicYear = $(this).val();
        
        if (classId && academicYear) {
            loadStudentsForClass(classId, academicYear);
        }
    });

    // Function to load students for class and academic year
    function loadStudentsForClass(classId, academicYear) {
        $.ajax({
            type: 'POST',
            url: 'ajax/get_students_for_class_year.php',
            data: { 
                classId: classId,
                academicYear: academicYear
            },
            success: function (response) {
                try {
                    const students = JSON.parse(response);
                    let options = '<option value="">-- Select Student --</option>';
                    
                    if (students.length > 0) {
                        students.forEach(function(student) {
                            let sectionInfo = student.section_name ? ' (' + student.section_name + ')' : '';
                            options += '<option value="' + student.student_id + '">' + 
                                       student.regd_id + ' - ' + student.name + sectionInfo + '</option>';
                        });
                        $('#student_id').html(options).prop('disabled', false);
                    } else {
                        options += '<option value="">No students found for this class and academic year</option>';
                        $('#student_id').html(options).prop('disabled', false);
                    }
                } catch(e) {
                    console.error('Error parsing response:', e);
                    Swal.fire('Error', 'Failed to load students. Please try again.', 'error');
                    $('#student_id').html('<option value="">Error loading students</option>').prop('disabled', false);
                }
            },
            error: function () {
                Swal.fire('Error', 'Failed to load students for the selected class.', 'error');
                $('#student_id').html('<option value="">Error loading students</option>').prop('disabled', false);
            }
        });
    }

    // Load assigned subjects when Proceed button is clicked
    $('#proceedBtn').click(function () {
        var classId = $('#class_id').val();
        var studentId = $('#student_id').val();
        var academicYear = $('#academic_year').val();

        if (classId && studentId && academicYear) {
            $.ajax({
                type: 'POST',
                url: 'ajax/get_assigned_subjects.php',
                data: { 
                    classId: classId, 
                    studentId: studentId,
                    academicYear: academicYear
                },
                success: function (response) {
                    $('#modalBodyContent').html(response);
                    
                    // Initialize select2 in modal
                    $('.subject-select').select2({
                        width: '100%',
                        placeholder: '-- Select Subject --'
                    });
                    
                    $('#subjectModal').modal('show');
                },
                error: function () {
                    Swal.fire('Error', 'Failed to load assigned subjects.', 'error');
                }
            });
        } else {
            Swal.fire('Warning', 'Please select class, student, and academic year.', 'warning');
        }
    });

   // Save changed subjects when Save button is clicked
$('#saveSubjectsBtn').click(function () {
    // Collect ALL subject data from the form
    let formData = $('#subjectForm').serializeArray();
    let subjectsData = {};
    
    // Convert form data to object
    $.each(formData, function() {
        subjectsData[this.name] = this.value;
    });
    
    // Also collect changed subjects for tracking (optional)
    let changedSubjects = [];
    $('.subject-row').each(function() {
        let subjectId = $(this).data('subject-id');
        let originalCode = $(this).data('original-code');
        let newCode = $(this).find('.subject-select').val();
        
        if (newCode !== originalCode) {
            changedSubjects.push({
                subject_id: subjectId,
                original_code: originalCode,
                new_code: newCode
            });
        }
    });

    // Show confirmation
    Swal.fire({
        title: 'Confirm Changes',
        text: 'Are you sure you want to update student subjects?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, update them!',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            // Send ALL form data to server
            $.ajax({
                type: 'POST',
                url: 'ajax/update_student_subjects.php',
                data: subjectsData, // Send all form data
                success: function (response) {
                    try {
                        var res = JSON.parse(response);
                        if (res.status === 'success') {
                            Swal.fire({
                                title: 'Success!',
                                text: res.message,
                                icon: 'success',
                                confirmButtonText: 'OK'
                            }).then(() => {
                                $('#subjectModal').modal('hide');
                                // Refresh the student list to reflect changes
                                var classId = $('#class_id').val();
                                var academicYear = $('#academic_year').val();
                                if (classId && academicYear) {
                                    loadStudentsForClass(classId, academicYear);
                                }
                            });
                        } else {
                            Swal.fire('Error', res.message, 'error');
                        }
                    } catch(e) {
                        Swal.fire('Error', 'Failed to process server response.', 'error');
                    }
                },
                error: function () {
                    Swal.fire('Error', 'Failed to save changes. Please try again.', 'error');
                }
            });
        }
    });
});
    // Clear form on reset
    $('button[type="reset"]').click(function() {
        $('#student_id').html('<option value="">-- Select Class First --</option>').prop('disabled', true);
    });
});
</script>
</body>
</html>