<?php
session_start();
if(isset($_SESSION['username'])){
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <?php include 'includes/styles.php'; global $school_name; ?>
        <title>View Broadsheet | <?php echo $school_name; ?></title>

        <?php
        $module_name = 'Broadsheet';
        include "check-admin-privilege.php";
        ?>
    </head>
    <body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">

    <!-- Navbar -->
<?php include 'includes/notifications.php'; ?>
    <!-- /.navbar -->

    <!-- Main Sidebar Container -->
<?php include "includes/sidebar.php";?>

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0">View Student Broadsheet</h1>
                    </div><!-- /.col -->
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="<?php echo $conn->base_url();?>">Home</a></li>
                            <li class="breadcrumb-item active">View Student Broadsheet</li>
                        </ol>
                    </div><!-- /.col -->
                </div><!-- /.row -->
            </div><!-- /.container-fluid -->
        </div>
        <!-- /.content-header -->

        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">

                <div class="callout callout-success" style="margin-top: 10px;">
                    <p><i class="fas fa-info-circle"></i> Please select Class, Exam and Section to view available broadsheet.</p>
                </div>

                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title"><i class="fas fa-table"></i> Student Broadsheet</h3>
                    </div>
                    <!-- /.card-header -->
                    <!-- form start -->
                    <form class="form-horizontal" method="post" id="broadsheet-selection-form">
                        <div class="card-body">
                            <div class="form-row">
                                <div class="col-md-3">
                                    <label for="class">Class <span class="text-danger">*</span></label>
                                    <select name="class" id="classID" class="form-control select2" required style="width: 100%;">
                                        <option value="">Select Class</option>
                                        <?php
                                        //fetch all classes
                                        $sql = "SELECT * FROM classes ORDER BY name";
                                        $conn->query($sql);
                                        $rowcount = $conn->rowCount();

                                        if($rowcount > 0){
                                            $result = $conn->fetchMultiple();
                                            foreach ($result as $class) {
                                                ?>  <option value="<?php echo $class->name; ?>"><?php echo $class->name; ?></option><?php
                                            }
                                        }
                                        ?>
                                    </select>
                                </div>

                                <div class="col-md-3">
                                    <label for="term">Term <span class="text-danger">*</span></label>
                                    <select name="term" id="term" class="form-control select2" required style="width: 100%;">
                                        <option value="">Select Term</option>
                                        <?php
                                        //fetch the active term from general settings
                                        $sql = "SELECT active_term FROM general_settings";
                                        $conn->query($sql);
                                        $rowcount = $conn->rowCount();

                                        if($rowcount > 0){
                                            $active_term = $conn->fetchColumn();
                                            ?>  <option value="<?php echo $active_term; ?>" selected><?php echo $active_term; ?></option><?php
                                        }

                                        // Also fetch all available terms
                                        $sql = "SELECT * FROM terms ORDER BY name";
                                        $conn->query($sql);
                                        $terms = $conn->fetchMultiple();
                                        foreach ($terms as $termItem) {
                                            if($termItem->name != $active_term) {
                                                ?>  <option value="<?php echo $termItem->name; ?>"><?php echo $termItem->name; ?></option><?php
                                            }
                                        }
                                        ?>
                                    </select>
                                </div>

                                <div class="col-md-3">
                                    <label for="section">Section <span class="text-danger">*</span></label>
                                    <select name="section" id="section" class="form-control select2" required style="width: 100%;">
                                        <option value="">Select Section</option>
                                    </select>
                                </div>

                                <div class="col-md-3">
                                    <label for="session">School Session <span class="text-danger">*</span></label>
                                    <select name="session" id="session" class="form-control select2" required style="width: 100%;">
                                        <option value="">Select Session</option>
                                        <?php
                                        $sql = "SELECT DISTINCT current_school_session FROM student_results ORDER BY current_school_session DESC";
                                        $conn->query($sql);
                                        $result = $conn->fetchMultiple();
                                        foreach ($result as $session){
                                            $school_session = $session->current_school_session;
                                            ?>
                                            <option value="<?php echo $school_session; ?>"><?php echo $school_session; ?></option>
                                            <?php
                                        }
                                        ?>
                                    </select>
                                </div>

                                <div class="col-md-12 mt-3">
                                    <button type="submit" class="btn btn-success" id="viewStudentsBtn">
                                        <i class="fas fa-search"></i> View Students Details
                                    </button>
                                </div>
                            </div>
                        </div>
                        <!-- /.card-body -->
                    </form>
                </div>
                <!-- /.card -->

                <!-- Students Preview Section -->
                <div class="card card-info" id="students-preview-section" style="display: none;">
                    <div class="card-header">
                        <h3 class="card-title"><i class="fas fa-users"></i> Students for Broadsheet</h3>
                    </div>
                    <div class="card-body" id="students-preview-content">
                        <!-- Dynamic content will be loaded here -->
                    </div>
                </div>

            </div><!-- /.container-fluid -->
        </section>
        <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->
<?php include "includes/footer.php";?>

    <script>
        $(document).ready(function () {
            $('.select2').select2();

            // Load sections when class is selected
            $('#classID').on('change', function () {
                var className = $(this).val();
                if(className){
                    $.ajax({
                        type: 'POST',
                        url: 'fetch_section_by_class_name.php',
                        data: 'className=' + className,
                        success: function (html) {
                            $('#section').html(html);
                        }
                    });
                }else{
                    $('#section').html('<option value="">Select class first</option>');
                }
            });

            // Handle form submission
            $('#broadsheet-selection-form').on('submit', function (event) {
                event.preventDefault();

                var className = $('#classID').val();
                var term = $('#term').val();
                var section = $('#section').val();
                var session = $('#session').val();

                if(!className || !term || !section || !session) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Missing Information',
                        text: 'Please fill in all required fields.'
                    });
                    return;
                }

                loadStudentsPreview(className, term, section, session);
            });
        });

        function loadStudentsPreview(className, term, section, session) {
            $.ajax({
                url: 'fetch-broadsheet-students.php',
                method: 'POST',
                data: {
                    class: className,
                    term: term,
                    section: section,
                    session: session
                },
                beforeSend: function () {
                    $('#viewStudentsBtn').attr('disabled', 'disabled');
                    $('#viewStudentsBtn').html('<i class="fas fa-spinner fa-spin"></i> Loading...');
                },
                success: function (response) {
                    try {
                        const result = JSON.parse(response);
                        if (result.success) {
                            $('#students-preview-content').html(result.html);
                            $('#students-preview-section').show();

                            // Scroll to preview section
                            $('html, body').animate({
                                scrollTop: $("#students-preview-section").offset().top - 100
                            }, 1000);

                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: result.message
                            });
                        }
                    } catch (e) {
                        console.error('JSON Parse Error:', e);
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'An unexpected error occurred.'
                        });
                    }
                },
                error: function () {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to load students data.'
                    });
                },
                complete: function () {
                    $('#viewStudentsBtn').attr('disabled', false);
                    $('#viewStudentsBtn').html('<i class="fas fa-search"></i> View Students Details');
                }
            });
        }

        // Handle generate broadsheet button (delegated event)
        $(document).on('click', '#generateBroadsheetBtn', function() {
            var className = $('#classID').val();
            var term = $('#term').val();
            var section = $('#section').val();
            var session = $('#session').val();

            generateBroadsheet(className, term, section, session);
        });

        function generateBroadsheet(className, term, section, session) {
            // Show loading state
            $('#generateBroadsheetBtn').attr('disabled', 'disabled');
            $('#generateBroadsheetBtn').html('<i class="fas fa-spinner fa-spin"></i> Generating Broadsheet...');

            // Build URL for broadsheet generation
            var slugifyClass = className.replace(/\s+/g, '-');
            var slugifyTerm = term.replace(/\s+/g, '-');
            var slugifySection = section.replace(/\s+/g, '-');
            var slugifySession = session.replace(/\//g, '-');

            var broadsheetUrl = 'generate_broadsheet.php?class=' + slugifyClass +
                '&term=' + slugifyTerm +
                '&section=' + slugifySection +
                '&session=' + slugifySession;

            // Redirect to broadsheet generation page
            setTimeout(function() {
                window.open(broadsheetUrl, '_blank');
                $('#generateBroadsheetBtn').attr('disabled', false);
                $('#generateBroadsheetBtn').html('<i class="fas fa-file-pdf"></i> Generate Broadsheet');
            }, 1000);
        }
    </script>

    <?php
}else{
    ?>
    <!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, maximum-scale=1, shrink-to-fit=no">

        <?php include 'includes/styles.php'; global $school_name; ?>
        <title>Login to continue | <?php echo $school_name; ?></title>
    </head>
    <body>
    <div class="container" style="margin-top: 20%;">
        <div class="row">
            <div class="col-lg-12 col-md-12">
                <div class="section-title text-center">
                    <h6>You need to login to continue</h6>
                    <div class="spinner-border text-info" role="status">
                        <span class="sr-only">Loading...</span>
                        <meta http-equiv='refresh' content='3; <?php echo $conn->base_url(); ?>login'>
                    </div>
                    <p>Redirecting to the login page...</p>
                </div>
            </div>
        </div>
    </div>
    <?php
    }
?>