<?php
include('session_validator.php'); ?>
<!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 - Add Exam with Sections</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" >
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
        <script src="js/modernizr/modernizr.min.js"></script>
        <!-- <script src="js/multiselect-dropdown.js"></script> -->
        <style>
            .compact-form .form-group {
                margin-bottom: 10px;
            }
            .compact-form label {
                font-size: 13px;
                font-weight: 600;
                margin-bottom: 5px;
                color: #495057;
            }
            .compact-form .form-control, .compact-form .select2-container--default .select2-selection--single {
                height: 40px;
                font-size: 13px;
                padding: 6px 10px;
                border-radius: 3px;
            }
            .compact-form .select2-container--default .select2-selection--multiple {
                min-height: 40px;
                font-size: 13px;
            }
            .section-container {
                background: #f8f9fa;
                border: 1px solid #e9ecef;
                border-radius: 4px;
                padding: 15px;
                margin-bottom: 15px;
            }
            .section-title {
                color: #2c3e50;
                border-bottom: 2px solid #3498db;
                padding-bottom: 8px;
                margin-bottom: 15px;
                font-size: 16px;
                font-weight: 600;
            }
            .btn-primary {
                background: linear-gradient(135deg, #3498db, #2980b9);
                border: none;
                padding: 10px 25px;
                font-weight: 600;
                border-radius: 5px;
            }
            .btn-primary:hover {
                background: linear-gradient(135deg, #2980b9, #21618c);
                transform: translateY(-1px);
            }
            .help-text {
                font-size: 11px;
                color: #6c757d;
                margin-top: 3px;
            }
            .required-field:after {
                content: " *";
                color: #e74c3c;
            }
            .loading-overlay {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(255,255,255,0.8);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 9999;
                display: none;
            }
            .spinner {
                width: 40px;
                height: 40px;
                border: 4px solid #f3f3f3;
                border-top: 4px solid #3498db;
                border-radius: 50%;
                animation: spin 1s linear infinite;
            }
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
            .toastify {
                border-radius: 4px;
                font-family: inherit;
                font-size: 13px;
                padding: 12px 20px;
                box-shadow: 0 3px 15px rgba(0,0,0,0.1);
            }
            .exam-row {
                transition: all 0.3s ease;
            }
            .exam-row:hover {
                background-color: #f8f9fa;
            }
            .badge-section {
                background: #e3f2fd;
                color: #1976d2;
                font-size: 11px;
                padding: 3px 8px;
                border-radius: 10px;
                margin-right: 5px;
                margin-bottom: 5px;
                display: inline-block;
            }
            .form-section {
                margin-bottom: 20px;
            }
        </style>
    </head>
    <body class="top-navbar-fixed">
        <!-- Loading Overlay -->
        <div class="loading-overlay" id="loadingOverlay">
            <div class="spinner"></div>
        </div>
        
        <div class="main-wrapper">
            <!-- ========== TOP NAVBAR ========== -->
            <?php include('includes/topbar.php'); ?> 
            <!-- ========== WRAPPER FOR BOTH SIDEBARS & MAIN CONTENT ========== -->
            <div class="content-wrapper">
                <div class="content-container">
                    <!-- ========== LEFT SIDEBAR ========== -->
                    <?php include('includes/leftbar.php'); ?>  
                    <!-- /.left-sidebar -->

                    <div class="main-page">
                        <div class="container-fluid">
                            <div class="row page-title-div">
                                <div class="col-md-6">
                                    <h2 class="title"><i class="fa fa-graduation-cap mr-2"></i>Add Exam Type with Sections</h2>
                                </div>
                                <div class="col-md-6 text-right">
                                    <div class="stats-badge" style="background: #e3f2fd; border: 1px solid #bbdefb; color: #1976d2; padding: 5px 15px; border-radius: 20px; font-size: 13px;">
                                        <i class="fa fa-info-circle mr-1"></i>Create exams with specific sections
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row breadcrumb-div">
                                <div class="col-md-12">
                                    <ul class="breadcrumb">
                                        <li><a href="dashboard.php"><i class="fa fa-home"></i> Home</a></li>
                                        <li><a href="#"><i class="fa fa-graduation-cap"></i> Examination</a></li>
                                        <li class="active"><i class="fa fa-plus-circle"></i> Add Exam Type</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-plus-circle mr-2"></i>Create New Exam with Sections</h5>
                                            </div>
                                        </div>
                                        <div class="panel-body">
                                            <?php
                                            include("includes/db.php");

                                            // Function to sanitize user inputs
                                            function sanitizeInput($input) {
                                                return htmlspecialchars(stripslashes(trim($input)));
                                            }

                                            // Handle form submission
                                            if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
                                                $exm_year = sanitizeInput($_POST['exm_year']);
                                                $exam_type = sanitizeInput($_POST['exam_type']);
                                                $exam_year_ad = sanitizeInput($_POST['exm_year_ad']);
                                                $class_id = isset($_POST['class_id']) ? sanitizeInput($_POST['class_id']) : "";
                                                $assigned_sections = isset($_POST['assigned_sections']) ? implode(",", $_POST['assigned_sections']) : "";

                                                // Check for duplicate exam
                                                $checkDuplicateQuery = $conn->prepare("SELECT COUNT(*) FROM examination_type WHERE exm_year = ? AND exam_type = ?");
                                                $checkDuplicateQuery->bind_param("ss", $exm_year, $exam_type);
                                                $checkDuplicateQuery->execute();
                                                $checkDuplicateQuery->bind_result($count);
                                                $checkDuplicateQuery->fetch();
                                                $checkDuplicateQuery->close();

                                                if ($count > 0) {
                                                    echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">
                                                            <i class="fa fa-exclamation-triangle mr-2"></i>
                                                            <strong>Error!</strong> Duplicate entry for Exam Year and Exam Type.
                                                            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                                                <span aria-hidden="true">&times;</span>
                                                            </button>
                                                        </div>';
                                                } else {
                                                    // Insert exam with sections
                                                    $insertQuery = $conn->prepare("INSERT INTO examination_type (exm_year, exm_year_ad, exam_type, assigned_class, assigned_sections) VALUES (?, ?, ?, ?, ?)");
                                                    $insertQuery->bind_param("sssss", $exm_year, $exam_year_ad, $exam_type, $class_id, $assigned_sections);

                                                    if ($insertQuery->execute()) {
                                                        echo '<div class="alert alert-success alert-dismissible fade show" role="alert">
                                                                <i class="fa fa-check-circle mr-2"></i>
                                                                <strong>Success!</strong> Examination type with sections added successfully!
                                                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                                                    <span aria-hidden="true">&times;</span>
                                                                </button>
                                                            </div>';
                                                            
                                                        // Clear form data
                                                        unset($_POST);
                                                    } else {
                                                        echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">
                                                                <i class="fa fa-exclamation-triangle mr-2"></i>
                                                                <strong>Error!</strong> Error adding examination type. Please try again.
                                                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                                                    <span aria-hidden="true">&times;</span>
                                                                </button>
                                                            </div>';
                                                    }
                                                    $insertQuery->close();
                                                }
                                            }
                                            ?>

                                            <!-- Exam Creation Form -->
                                            <div class="section-container">
                                                <h6 class="section-title"><i class="fa fa-edit mr-2"></i>Enter Examination Type Information</h6>
                                                <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" id="examForm" class="compact-form">
                                                    <div class="row">
                                                        <div class="form-group col-md-3">
                                                            <label for="exm_year" class="required-field">
                                                                <i class="fa fa-calendar mr-1"></i>Exam Year (BS):
                                                            </label>
                                                            <select id="exm_year" name="exm_year" class="form-control select2" required>
                                                                <option value="">Select Year (BS)</option>
                                                                <?php
                                                                for ($year = 2081; $year <= 2084; $year++) {
                                                                    $selected = (isset($_POST['exm_year']) && $_POST['exm_year'] == $year) ? 'selected' : '';
                                                                    echo '<option value="' . $year . '" ' . $selected . '>' . $year . '</option>';
                                                                }
                                                                ?>
                                                            </select>
                                                            <div class="help-text">Select exam year in Bikram Sambat</div>
                                                        </div>
                                                        
                                                        <div class="form-group col-md-3">
                                                            <label for="exm_year_ad" class="required-field">
                                                                <i class="fa fa-calendar mr-1"></i>Exam Year (AD):
                                                            </label>
                                                            <select id="exm_year_ad" name="exm_year_ad" class="form-control select2" required>
                                                                <option value="">Select Year (AD)</option>
                                                                <?php
                                                                $currentYear = date('Y');
                                                                for ($year = $currentYear - 1; $year <= $currentYear + 2; $year++) {
                                                                    $selected = (isset($_POST['exm_year_ad']) && $_POST['exm_year_ad'] == $year) ? 'selected' : '';
                                                                    echo '<option value="' . $year . '" ' . $selected . '>' . $year . '</option>';
                                                                }
                                                                ?>
                                                            </select>
                                                            <div class="help-text">Select exam year in Gregorian calendar</div>
                                                        </div>

                                                        <div class="form-group col-md-3">
                                                            <label for="exam_type" class="required-field">
                                                                <i class="fa fa-tag mr-1"></i>Exam Type:
                                                            </label>
                                                            <input type="text" id="exam_type" name="exam_type" class="form-control" 
                                                                   placeholder="e.g., First Terminal, Pre-Board, Final" 
                                                                   value="<?php echo isset($_POST['exam_type']) ? htmlspecialchars($_POST['exam_type']) : ''; ?>" required>
                                                            <div class="help-text">Enter the name of the examination</div>
                                                        </div>
                                                    </div>

                                                    <div class="row">
                                                        <div class="form-group col-md-6">
                                                            <label for="class_id" class="required-field">
                                                                <i class="fa fa-graduation-cap mr-1"></i>Select Class:
                                                            </label>
                                                            <select id="class_id" name="class_id" class="form-control" required>
                                                                <option value="">-- Select Class --</option>
                                                                <?php
                                                                $classQuery = $conn->query("SELECT class_id, class FROM classes WHERE status=1 ORDER BY class_numeric");
                                                                while ($classRow = $classQuery->fetch_assoc()) {
                                                                    $value = $classRow['class_id'];
                                                                    $label = $classRow['class'];
                                                                    $selected = (isset($_POST['class_id']) && $_POST['class_id'] == $value) ? 'selected' : '';
                                                                    echo '<option value="' . $value . '" ' . $selected . '>' . $label . '</option>';
                                                                }
                                                                ?>
                                                            </select>
                                                            <div class="help-text">Select class for this examination</div>
                                                        </div>

                                                        <div class="form-group col-md-6">
    <label for="assigned_sections">
        <i class="fa fa-columns mr-1"></i>Select Sections (Multiple):
    </label>

    <select id="assigned_sections" name="assigned_sections[]" class="form-control select2" multiple disabled>
        <option value="">Select class first</option>
    </select>

    <div class="help-text" id="sectionCountInfo">
        No sections selected (All sections)
    </div>
</div>

                                                    </div>

                                                    <div class="form-actions text-center mt-4">
                                                        <button type="submit" name="submit" class="btn btn-primary" id="submitBtn">
                                                            <i class="fa fa-save mr-1"></i> Save Exam Type with Sections
                                                        </button>
                                                        <button type="reset" class="btn btn-secondary" id="resetBtn">
                                                            <i class="fa fa-refresh mr-1"></i> Reset Form
                                                        </button>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Exam Types List -->
                            <div class="row mt-4">
                                <div class="col-md-12">
                                    <div class="panel">
                                        <div class="panel-heading">
                                            <div class="panel-title">
                                                <h5><i class="fa fa-list mr-2"></i>Existing Exam Types</h5>
                                            </div>
                                        </div>
                                        <div class="panel-body">
                                            <div class="table-responsive">
                                                <table class="table table-hover">
    <thead class="thead-light">
        <tr>
            <th>ID</th>
            <th>Exam Type</th>
            <th>Year (BS)</th>
            <th>Year (AD)</th>
            <th>Class</th>
            <th>Sections</th>
            <th>Created At</th>
            <th>Action</th>
        </tr>
    </thead>

    <tbody id="examTypeTableBody">
        <!-- AJAX CONTENT LOADS HERE -->
    </tbody>
</table>

                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>


                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Scripts -->
        <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="https://cdn.jsdelivr.net/npm/toastify-js"></script>
        <script src="js/main.js"></script>
        
        <script>

            $(document).ready(function() {
                // Initialize Select2
                $('.select2').select2({
                    width: '100%',
                    placeholder: "Select options",
                    allowClear: true
                });
                

                loadExamTypes();

                // When class is selected, load sections for that class
                $('#class_id').change(function() {
                    var classId = $(this).val();
                    var $sectionSelect = $('#assigned_sections');
                    
                    /*console.log('Class selected:', classId);*/
                    
                    if (classId) {
                        $sectionSelect.prop('disabled', false);
                        $sectionSelect.html('<option value="">Loading sections...</option>');
                        
                     $.ajax({
    url: 'ajax/get_sections_by_class.php',
    type: 'GET',
    dataType: 'json',   // ⭐ IMPORTANT
    data: { class_id: classId },

    success: function(sections) {
        let options = '';

        if (Array.isArray(sections) && sections.length > 0) {
            sections.forEach(section => {
                options += `
                    <option value="${section.section_id}">
                        ${section.section_name} 
                    </option>`;
            });

            $sectionSelect.html(options).prop('disabled', false);
            $sectionSelect.trigger('change.select2'); // ⭐ refresh select2
        } else {
            $sectionSelect.html('<option value="">No sections found</option>');
        }
    },

    error: function(xhr) {
        console.error('AJAX error:', xhr.responseText);
        $sectionSelect.html('<option value="">Error loading sections</option>');
    }
});

                    } else {
                        $sectionSelect.prop('disabled', true);
                        $sectionSelect.html('<option value="">Select class first</option>');
                    }
                });
                
                // Form submission handling
       $('#examForm').on('submit', function(e) {
    e.preventDefault();

    const formData = $(this).serialize();

    $('#loadingOverlay').show();
    $('#submitBtn')
        .prop('disabled', true)
        .html('<i class="fa fa-spinner fa-spin mr-1"></i> Saving...');

    $.ajax({
        url: 'ajax/save_exam_type.php',
        type: 'POST',
        data: formData,
        dataType: 'json',

        success: function(res) {
            $('#loadingOverlay').hide();
            $('#submitBtn')
                .prop('disabled', false)
                .html('<i class="fa fa-save mr-1"></i> Save Exam Type with Sections');

       if (res.status === 'success') {
    showToast('success', 'Success', res.message);

    // Reset form
    $('#examForm')[0].reset();
    $('.select2').val(null).trigger('change');
    $('#assigned_sections')
        .html('<option value="">Select class first</option>')
        .prop('disabled', true);

    $('#sectionCountInfo').text('No sections selected (All sections)');


    loadExamTypes();



            } else {
                showToast('error', 'Error', res.message);
            }
        },

        error: function(xhr) {
            $('#loadingOverlay').hide();
            $('#submitBtn')
                .prop('disabled', false)
                .html('<i class="fa fa-save mr-1"></i> Save Exam Type with Sections');

            console.error(xhr.responseText);
            showToast('error', 'Server Error', 'Something went wrong');
        }
    });
});

function loadExamTypes() {
    $('#examTypeTableBody').html(
        '<tr><td colspan="8" class="text-center">Loading...</td></tr>'
    );

    $.get('ajax/load_exam_types.php', function(data) {
        $('#examTypeTableBody').html(data);
    });
}


                
                // Reset form
                $('#resetBtn').click(function() {
                    $('#examForm')[0].reset();
                    $('#assigned_sections').html('<option value="">Select class first</option>').prop('disabled', true);
                    $('.select2').trigger('change');
                });
                
                // Auto-dismiss alerts
                setTimeout(function() {
                    $('.alert').alert('close');
                }, 5000);
                
                // Show toast notification function
                function showToast(type, title, message) {
                    const backgroundColor = type === 'success' ? '#06d6a0' : '#ef233c';
                    const icon = type === 'success' ? '✓' : '✗';
                    
                    Toastify({
                        text: `<strong>${title}</strong><br>${message}`,
                        duration: 5000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: backgroundColor,
                        stopOnFocus: true,
                        escapeMarkup: false
                    }).showToast();
                }
                
                // Hide loading overlay on page load
                window.addEventListener('load', function() {
                    setTimeout(function() {
                        $('#loadingOverlay').hide();
                        $('#submitBtn').prop('disabled', false).html('<i class="fa fa-save mr-1"></i> Save Exam Type with Sections');
                    }, 1000);
                });
                
                // If class is already selected (form submission error), load its sections
                <?php if (isset($_POST['class_id']) && $_POST['class_id']): ?>
                $('#class_id').trigger('change');
                <?php endif; ?>
            });
        </script>
    </body>
</html>