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

// Retrieve exam types from the database
$query_exam_types = "SELECT id, exm_year, exam_type FROM examination_type";
$result_exam_types = $conn->query($query_exam_types);

// Retrieve classes and sections from the database
$query_classes = "
    SELECT 
        cs.id as class_section_id,
        c.class,
        s.section_name
    FROM class_section cs
    INNER JOIN classes c ON cs.class_id = c.class_id
    INNER JOIN sections s ON cs.section_id = s.section_id
    WHERE cs.status = 1 AND c.status = 1 AND s.status = 1
    ORDER BY c.class_numeric, s.section_name
";
$result_classes = $conn->query($query_classes);

// Initialize variables
$assignedData = [];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $examId = $conn->real_escape_string($_POST['exam_id']);
    $resultDate = $conn->real_escape_string($_POST['result_date']);
    $selectedClasses = $_POST['class_section_ids']; // Array of selected class-section IDs

    foreach ($selectedClasses as $classSectionId) {
        $classSectionId = $conn->real_escape_string($classSectionId);
        
        // Get class_id from class_section table
        $getClassQuery = "SELECT class_id FROM class_section WHERE id = '$classSectionId'";
        $classResult = $conn->query($getClassQuery);
        if ($classRow = $classResult->fetch_assoc()) {
            $classId = $classRow['class_id'];
            
            $insertQuery = "
                INSERT INTO result_publication (exam_id, class_id, result_date)
                VALUES ('$examId', '$classId', '$resultDate')
                ON DUPLICATE KEY UPDATE result_date = '$resultDate'
            ";
            $conn->query($insertQuery);
        }
    }

    $message = "Result publication date successfully assigned.";
}

// Fetch assigned data for AJAX requests
if (isset($_GET['exam_id'])) {
    $examId = $conn->real_escape_string($_GET['exam_id']);
    $assignedQuery = "
        SELECT 
            rp.result_date,
            c.class,
            GROUP_CONCAT(DISTINCT s.section_name ORDER BY s.section_name SEPARATOR ', ') as sections
        FROM result_publication rp
        INNER JOIN classes c ON rp.class_id = c.class_id
        INNER JOIN class_section cs ON c.class_id = cs.class_id
        INNER JOIN sections s ON cs.section_id = s.section_id
        WHERE rp.exam_id = '$examId'
        GROUP BY rp.class_id, rp.result_date
        ORDER BY c.class_numeric
    ";
    $assignedResult = $conn->query($assignedQuery);
    $assignedData = [];
    while ($row = $assignedResult->fetch_assoc()) {
        $assignedData[] = $row;
    }
    echo json_encode($assignedData);
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Assign Result Date</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="nepali.datepicker.v4.0.1\css\main.css" media="screen">
    <script src="js/multiselect-dropdown.js"></script>
    <script src="js/modernizr/modernizr.min.js"></script>
</head>

<body>
    <?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="panel">
                        <div class="panel-heading">
                            <div class="panel-title">
                                <h5>Assign Result Date</h5>
                            </div>
                        </div>
                        <div class="panel-body">
                            <form id="assignResultForm" method="post">
                                <div class="form-row">
                                    <!-- Select Exam Type -->
                                    <div class="form-group col-md-4">
                                        <label for="exam_id">Select Exam Type:</label>
                                        <select id="exam_id" name="exam_id" class="form-control" required>
                                            <option value="">Select Exam Type</option>
                                            <?php
                                            while ($row = $result_exam_types->fetch_assoc()) {
                                                echo "<option value='" . $row['id'] . "'>" . $row['exm_year'] . " - " . $row['exam_type'] . "</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>
                                    
                                    <!-- Select Class and Sections -->
                                    <div class="form-group col-md-4">
                                        <label for="class_section_ids">Select Classes & Sections:</label>
                                        <select id="class_section_ids" name="class_section_ids[]" class="form-control" multiple required>
                                            <?php
                                            while ($row = $result_classes->fetch_assoc()) {
                                                echo "<option value='" . $row['class_section_id'] . "'>" 
                                                    . htmlspecialchars($row['class']) 
                                                    . " - " 
                                                    . htmlspecialchars($row['section_name']) 
                                                    . "</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>

                                    <!-- Result Date -->
                                    <div class="form-group col-md-4">
                                        <label for="result_date">Result Publication Date:</label>
                                        <input type="text" id="result_date" name="result_date" class="form-control" required>
                                    </div>
                                </div>

                                <!-- Display Selected Classes -->
                                <div id="selectedClasses" class="form-group col-md-8">
                                    <label>Selected Classes & Sections:</label>
                                    <ul id="selectedClassesList"></ul>
                                </div>

                                <!-- Submit Button -->
                                <div class="form-group">
                                    <button type="submit" class="btn btn-primary">Assign Result Date</button>
                                </div>
                            </form>

                            <!-- Display Assigned Data -->
                            <h5>Assigned Result Dates</h5>
                            <table class="table table-bordered" id="assignedTable">
                                <thead>
                                    <tr>
                                        <th>Class</th>
                                        <th>Sections</th>
                                        <th>Result Date</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Data will be populated by AJAX -->
                                </tbody>
                            </table>
                        </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/main.js"></script>
    <script src="js/modernizr/modernizr.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
    <link href="nepali.datepicker.v4.0.1/css/nepali.datepicker.v4.0.1.min.css" rel="stylesheet" type="text/css" />
    <script src="nepali.datepicker.v4.0.1/js/nepali.datepicker.v4.0.1.min.js"></script>
    
    <script>
    // Initialize Nepali Date Picker
    document.getElementById("result_date").nepaliDatePicker({
        ndpYear: true,
        ndpMonth: true,
        ndpYearCount: 100,
    });

    // Toastr Configuration
    toastr.options = {
        "closeButton": true,
        "debug": false,
        "newestOnTop": true,
        "progressBar": true,
        "positionClass": "toast-top-right",
        "preventDuplicates": true,
        "onclick": null,
        "showDuration": "300",
        "hideDuration": "1000",
        "timeOut": "5000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    };

    // Fetch and display assigned data when exam type is changed
    $('#exam_id').change(function () {
        var examId = $(this).val();
        if (examId) {
            $.ajax({
                url: "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>",
                type: "GET",
                data: { exam_id: examId },
                success: function (response) {
                    var data = JSON.parse(response);
                    var tableBody = $('#assignedTable tbody');
                    tableBody.empty();
                    if (data.length > 0) {
                        data.forEach(function (row) {
                            tableBody.append(
                                `<tr>
                                    <td>${row.class}</td>
                                    <td>${row.sections}</td>
                                    <td>${row.result_date}</td>
                                </tr>`
                            );
                        });
                    } else {
                        tableBody.append(
                            `<tr>
                                <td colspan="3" class="text-center">No result dates assigned for this exam</td>
                            </tr>`
                        );
                    }
                },
                error: function () {
                    toastr.error('Failed to fetch assigned data.');
                }
            });
        } else {
            $('#assignedTable tbody').empty();
        }
    });

    // Display selected classes and sections
    $('#class_section_ids').change(function () {
        var selectedOptions = $(this).find('option:selected');
        var list = $('#selectedClassesList');
        list.empty();
        selectedOptions.each(function () {
            list.append('<li>' + $(this).text() + '</li>');
        });
    });

    // Handle form submission with Toastr notifications
    $('#assignResultForm').submit(function (e) {
        e.preventDefault();
        var formData = $(this).serialize();
        $.post("<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>", formData)
            .done(function () {
                toastr.success('Result date successfully assigned!');
                $('#exam_id').trigger('change');
                // Clear the selected classes list
                $('#selectedClassesList').empty();
                // Reset the multiselect
                $('#class_section_ids').val([]).trigger('change');
            })
            .fail(function () {
                toastr.error('An error occurred while assigning the result date.');
            });
    });
    
    // Initialize multiselect dropdown
    $(document).ready(function() {
        new MultiSelectTag('class_section_ids', {
            rounded: true,
            placeholder: 'Search Classes & Sections...',
            onChange: function(values) {
                // Update the selected classes list
                var list = $('#selectedClassesList');
                list.empty();
                values.forEach(function(value) {
                    var optionText = $('#class_section_ids option[value="' + value + '"]').text();
                    list.append('<li>' + optionText + '</li>');
                });
            }
        });
    });
</script>

</body>
</html>