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

// Check if ID parameter exists
if (!isset($_GET['id']) || empty($_GET['id'])) {
    header('Location: add_exam_type.php');
    exit();
}

$exam_id = intval($_GET['id']);

// Fetch exam type details
$stmt = $conn->prepare("
    SELECT id, exm_year, exm_year_ad, exam_type, assigned_class, assigned_sections, created_at 
    FROM examination_type 
    WHERE id = ?
");
$stmt->bind_param("i", $exam_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    header('Location: add_exam_type.php');
    exit();
}

$exam = $result->fetch_assoc();
$stmt->close();

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

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

    // Check for duplicate (excluding current record)
    $checkDuplicateQuery = $conn->prepare("
        SELECT COUNT(*) FROM examination_type 
        WHERE exm_year = ? AND exam_type = ? AND assigned_class = ? AND id != ?
    ");
    $checkDuplicateQuery->bind_param("sssi", $exm_year, $exam_type, $class_id, $exam_id);
    $checkDuplicateQuery->execute();
    $checkDuplicateQuery->bind_result($count);
    $checkDuplicateQuery->fetch();
    $checkDuplicateQuery->close();

    if ($count > 0) {
        $error_message = "Duplicate entry for Exam Year and Exam Type in this class.";
    } else {
        // Update exam type
        $updateQuery = $conn->prepare("
            UPDATE examination_type 
            SET exm_year = ?, exm_year_ad = ?, exam_type = ?, assigned_class = ?, assigned_sections = ? 
            WHERE id = ?
        ");
        $updateQuery->bind_param("sssssi", $exm_year, $exam_year_ad, $exam_type, $class_id, $assigned_sections, $exam_id);

        if ($updateQuery->execute()) {
            $success_message = "Exam type updated successfully!";
            
            // Update the $exam array with new values
            $exam['exm_year'] = $exm_year;
            $exam['exm_year_ad'] = $exam_year_ad;
            $exam['exam_type'] = $exam_type;
            $exam['assigned_class'] = $class_id;
            $exam['assigned_sections'] = $assigned_sections;
        } else {
            $error_message = "Error updating exam type. Please try again.";
        }
        $updateQuery->close();
    }
}

// Fetch all classes for dropdown
$classes = $conn->query("SELECT class_id, class FROM classes WHERE status=1 ORDER BY class_numeric");
?>
<!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 - Edit Exam Type</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>
        <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);
            }
            .badge-section {
                background: #e3f2fd;
                color: #1976d2;
                font-size: 11px;
                padding: 3px 8px;
                border-radius: 10px;
                margin-right: 5px;
                margin-bottom: 5px;
                display: inline-block;
            }
            .back-btn {
                background: linear-gradient(135deg, #6c757d, #495057);
                border: none;
                padding: 8px 20px;
                font-weight: 600;
                border-radius: 5px;
                color: white;
            }
            .back-btn:hover {
                background: linear-gradient(135deg, #495057, #343a40);
                color: white;
                text-decoration: none;
                transform: translateY(-1px);
            }
            .exam-info-badge {
                background: #e8f5e9;
                border: 1px solid #c8e6c9;
                color: #2e7d32;
                padding: 8px 15px;
                border-radius: 20px;
                font-size: 14px;
            }
        </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-edit mr-2"></i>Edit Exam Type</h2>
                                </div>
                                <div class="col-md-6 text-right">
                                    <a href="add_exam_type.php" class="btn back-btn">
                                        <i class="fa fa-arrow-left mr-1"></i> Back to Exam List
                                    </a>
                                </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="add_exam_type.php"><i class="fa fa-graduation-cap"></i> Examination</a></li>
                                        <li class="active"><i class="fa fa-edit"></i> Edit Exam Type</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        
                        <div class="container-fluid">
                            <div class="row">
                                <div class="col-md-8 offset-md-2">
                                    <div class="panel">
                                        <div class="panel-heading">
                                            <div class="panel-title">
                                                <h5><i class="fa fa-edit mr-2"></i>Edit Exam Type: <span class="text-primary"><?php echo htmlspecialchars($exam['exam_type']); ?></span></h5>
                                            </div>
                                        </div>
                                        <div class="panel-body">
                                            <?php if (isset($success_message)): ?>
                                                <div class="alert alert-success alert-dismissible fade show" role="alert">
                                                    <i class="fa fa-check-circle mr-2"></i>
                                                    <strong>Success!</strong> <?php echo $success_message; ?>
                                                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                                        <span aria-hidden="true">&times;</span>
                                                    </button>
                                                </div>
                                            <?php endif; ?>
                                            
                                            <?php if (isset($error_message)): ?>
                                                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                                    <i class="fa fa-exclamation-triangle mr-2"></i>
                                                    <strong>Error!</strong> <?php echo $error_message; ?>
                                                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                                        <span aria-hidden="true">&times;</span>
                                                    </button>
                                                </div>
                                            <?php endif; ?>
                                            
                                            <!-- Exam Info Summary -->
                                            <div class="section-container mb-4">
                                                <h6 class="section-title"><i class="fa fa-info-circle mr-2"></i>Exam Information</h6>
                                                <div class="row">
                                                    <div class="col-md-12">
                                                        <div class="exam-info-badge d-inline-block mr-3 mb-2">
                                                            <i class="fa fa-hashtag mr-1"></i> ID: <strong>#<?php echo $exam['id']; ?></strong>
                                                        </div>
                                                        <div class="exam-info-badge d-inline-block mr-3 mb-2">
                                                            <i class="fa fa-calendar mr-1"></i> BS: <strong><?php echo $exam['exm_year']; ?></strong>
                                                        </div>
                                                        <div class="exam-info-badge d-inline-block mr-3 mb-2">
                                                            <i class="fa fa-calendar mr-1"></i> AD: <strong><?php echo $exam['exm_year_ad']; ?></strong>
                                                        </div>
                                                        <div class="exam-info-badge d-inline-block mb-2">
                                                            <i class="fa fa-clock-o mr-1"></i> Created: <strong><?php echo date('Y-m-d', strtotime($exam['created_at'])); ?></strong>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <!-- Edit Form -->
                                            <div class="section-container">
                                                <h6 class="section-title"><i class="fa fa-edit mr-2"></i>Edit Examination Type Information</h6>
                                                <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"] . "?id=" . $exam_id); ?>" id="editExamForm" class="compact-form">
                                                    <input type="hidden" name="exam_id" value="<?php echo $exam_id; ?>">
                                                    
                                                    <div class="row">
                                                        <div class="form-group col-md-4">
                                                            <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 = ($exam['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-4">
                                                            <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 = ($exam['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-4">
                                                            <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 htmlspecialchars($exam['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
                                                                while ($class = $classes->fetch_assoc()) {
                                                                    $selected = ($exam['assigned_class'] == $class['class_id']) ? 'selected' : '';
                                                                    echo '<option value="' . $class['class_id'] . '" ' . $selected . '>' . $class['class'] . '</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>
                                                                <option value="">Loading sections...</option>
                                                            </select>
                                                            <div class="help-text" id="sectionCountInfo">
                                                                Select sections or leave empty for all sections
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <div class="form-actions text-center mt-4">
                                                        <button type="submit" name="update" class="btn btn-primary" id="updateBtn">
                                                            <i class="fa fa-save mr-1"></i> Update Exam Type
                                                        </button>
                                                        <button type="button" class="btn btn-secondary" id="resetBtn">
                                                            <i class="fa fa-refresh mr-1"></i> Reset Changes
                                                        </button>
                                                        <a href="add_exam_section.php" class="btn btn-outline-secondary">
                                                            <i class="fa fa-times mr-1"></i> Cancel
                                                        </a>
                                                    </div>
                                                </form>
                                            </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
                });
                
                // Parse current sections
                let currentSections = [];
                <?php if (!empty($exam['assigned_sections'])): ?>
                    currentSections = '<?php echo $exam['assigned_sections']; ?>'.split(',');
                <?php endif; ?>
                
                // Initially load sections for the current class
                loadSectionsForClass('<?php echo $exam['assigned_class']; ?>', currentSections);
                
                // When class is changed, load sections
                $('#class_id').change(function() {
                    var classId = $(this).val();
                    loadSectionsForClass(classId, []);
                });
                
                // Function to load sections for a class
                function loadSectionsForClass(classId, selectedSections) {
                    var $sectionSelect = $('#assigned_sections');
                    
                    if (classId) {
                        $sectionSelect.prop('disabled', true);
                        $sectionSelect.html('<option value="">Loading sections...</option>');
                        
                        $.ajax({
                            url: 'ajax/get_sections_by_class.php',
                            type: 'GET',
                            dataType: 'json',
                            data: { class_id: classId },
                            success: function(sections) {
                                let options = '';
                                
                                if (Array.isArray(sections) && sections.length > 0) {
                                    sections.forEach(section => {
                                        const isSelected = selectedSections.includes(section.section_id.toString());
                                        options += `<option value="${section.section_id}" ${isSelected ? 'selected' : ''}>${section.section_name}</option>`;
                                    });
                                    
                                    $sectionSelect.html(options).prop('disabled', false);
                                    $sectionSelect.trigger('change.select2');
                                    
                                    // Update section count info
                                    const selectedCount = $sectionSelect.find('option:selected').length;
                                    if (selectedCount > 0) {
                                        $('#sectionCountInfo').text(selectedCount + ' section(s) selected');
                                    } else {
                                        $('#sectionCountInfo').text('No sections selected (All sections)');
                                    }
                                } else {
                                    $sectionSelect.html('<option value="">No sections found</option>');
                                    $('#sectionCountInfo').text('No sections available for this class');
                                }
                            },
                            error: function(xhr) {
                                console.error('AJAX error:', xhr.responseText);
                                $sectionSelect.html('<option value="">Error loading sections</option>');
                                $('#sectionCountInfo').text('Error loading sections');
                            }
                        });
                    } else {
                        $sectionSelect.prop('disabled', true);
                        $sectionSelect.html('<option value="">Select class first</option>');
                        $('#sectionCountInfo').text('Select class first');
                    }
                }
                
                // Update section count when sections are changed
                $('#assigned_sections').on('change', function() {
                    const selectedCount = $(this).find('option:selected').length;
                    if (selectedCount > 0) {
                        $('#sectionCountInfo').text(selectedCount + ' section(s) selected');
                    } else {
                        $('#sectionCountInfo').text('No sections selected (All sections)');
                    }
                });
                
                // Form submission handling
                $('#editExamForm').on('submit', function(e) {
                    e.preventDefault();
                    
                    const formData = $(this).serialize();
                    
                    $('#loadingOverlay').show();
                    $('#updateBtn')
                        .prop('disabled', true)
                        .html('<i class="fa fa-spinner fa-spin mr-1"></i> Updating...');
                    
                    $.ajax({
                        url: 'ajax/update_exam_type.php',
                        type: 'POST',
                        data: formData,
                        dataType: 'json',
                        success: function(res) {
                            $('#loadingOverlay').hide();
                            $('#updateBtn')
                                .prop('disabled', false)
                                .html('<i class="fa fa-save mr-1"></i> Update Exam Type');
                            
                            if (res.status === 'success') {
                                showToast('success', 'Success', res.message);
                                
                                // Update page content after successful update
                                setTimeout(function() {
                                    window.location.reload();
                                }, 1500);
                            } else {
                                showToast('error', 'Error', res.message);
                            }
                        },
                        error: function(xhr) {
                            $('#loadingOverlay').hide();
                            $('#updateBtn')
                                .prop('disabled', false)
                                .html('<i class="fa fa-save mr-1"></i> Update Exam Type');
                            
                            console.error(xhr.responseText);
                            showToast('error', 'Server Error', 'Something went wrong');
                        }
                    });
                });
                
                // Reset button
                $('#resetBtn').click(function() {
                    // Reset form to original values
                    $('#exm_year').val('<?php echo $exam['exm_year']; ?>').trigger('change');
                    $('#exm_year_ad').val('<?php echo $exam['exm_year_ad']; ?>').trigger('change');
                    $('#exam_type').val('<?php echo addslashes($exam['exam_type']); ?>');
                    $('#class_id').val('<?php echo $exam['assigned_class']; ?>').trigger('change');
                    
                    // Reload sections with current selections
                    setTimeout(function() {
                        loadSectionsForClass('<?php echo $exam['assigned_class']; ?>', currentSections);
                    }, 100);
                    
                    showToast('info', 'Form Reset', 'Form has been reset to original values');
                });
                
                // Auto-dismiss alerts
                setTimeout(function() {
                    $('.alert').alert('close');
                }, 5000);
                
                // Show toast notification function
                function showToast(type, title, message) {
                    const backgroundColor = type === 'success' ? '#06d6a0' : 
                                           type === 'error' ? '#ef233c' : 
                                           type === 'info' ? '#3498db' : '#f39c12';
                    const icon = type === 'success' ? '✓' : 
                                type === 'error' ? '✗' : 
                                type === 'info' ? 'ℹ' : '⚠';
                    
                    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();
                    }, 500);
                });
            });
        </script>
    </body>
</html>