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


    <?php include '../admin/includes/styles.php'; ?>
    <title> Add a mark |  <?php echo $school_name; ?> </title>

    <style>
        .fa-edit{
            background-color: transparent;
        }
    </style>

</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";
    $sql = "SELECT * FROM teachers WHERE username =:username";
    $conn->query($sql);
    $conn->bind(":username", $username);

    $result = $conn->fetchSingle();
    $teacher_name = $result->name;
    ?>

    <!-- 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">Add a mark</h1>
                    </div><!-- /.col -->
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="<?php echo $conn->teacher_url(); ?>">Home</a></li>
                            <li class="breadcrumb-item active">Add a mark</li>
                        </ol>
                    </div><!-- /.col -->
                </div><!-- /.row -->
            </div><!-- /.container-fluid -->
        </div>
        <!-- /.content-header -->

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

                <div class="row">
                    <div class="col-md-12">
                        <div class="callout callout-success" style="margin-top: 30px;">
                            <p>Note: You can only add marks for the subject and classes you are teaching</p>
                        </div>
                        <div class="card card-info">
                            <div class="card-header">
                                <h3 class="card-title"><i class="fa fa-flask"></i> Mark</h3>
                            </div>
                            <!-- /.card-header -->
                            <!-- form start -->
                            <form class="form-horizontal" method="post" id="mark-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="subject">Subject <span class="text-danger">*</span></label>
                                            <select name="subject" id="subject" class="form-control select2" required style="width: 100%;">
                                                <option value="">Select Subject</option>
                                            </select>
                                        </div>

                                        <input type="hidden" name="exam_year" value="<?php echo date('Y'); ?>">
                                        <input type="hidden" name="teacher_name" value="<?php echo $teacher_name; ?>">

                                        <div class="col-md-12 mt-3">
                                            <input type="submit" value="Load Students & Assessment Template" class="btn btn-primary" id="loadStudents">
                                        </div>

                                    </div>


                                </div>
                                <div id="success-msg">
                                </div>
                                <!-- /.card-body -->

                                <!-- /.card-footer -->
                            </form>
                        </div>
                        <!-- /.card -->
                    </div>

                    <div class="col-md-12">
                        <!-- Display mark entry form -->
                        <div class="card card-success" id="mark-entry-section" style="display: none;">
                            <div class="card-header">
                                <h3 class="card-title"><i class="fas fa-edit"></i> Mark Entry Form</h3>
                            </div>
                            <div class="card-body" id="mark-entry-content">
                                <!-- Dynamic content will be loaded here -->
                            </div>
                        </div>
                    </div>


                    <!-- /.row (main row) -->
                </div><!-- /.container-fluid -->
        </section>
        <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->
    <?php include "../admin/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>');
                }
            });

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

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

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

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

                loadFlexibleMarkEntry(className, term, section, subject);
            });
        });

        function loadFlexibleMarkEntry(className, term, section, subject) {
            $.ajax({
                url: 'fetch-marks-details.php',
                method: 'POST',
                data: {
                    class: className,
                    term: term,
                    section: section,
                    subject: subject,
                    exam_year: <?php echo date('Y'); ?>
                },
                beforeSend: function () {
                    $('#loadStudents').attr('disabled', 'disabled');
                    $('#loadStudents').val('Loading...');
                },
                success: function (response) {
                    try {
                        const result = JSON.parse(response);
                        if (result.success) {
                            $('#mark-entry-content').html(result.html);
                            $('#mark-entry-section').show();

                            // Scroll to the mark entry section
                            $('html, body').animate({
                                scrollTop: $("#mark-entry-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 mark entry form.'
                    });
                },
                complete: function () {
                    $('#loadStudents').attr('disabled', false);
                    $('#loadStudents').val('Load Students & Assessment Template');
                }
            });
        }

        // Handle flexible mark form submission (delegated event)
        $(document).on('submit', '#flexible-mark-form', function(e) {
            e.preventDefault();

            // Validate total marks for each student
            var isValid = true;
            var errorMessages = [];

            $('.student-row').each(function() {
                var studentName = $(this).find('.student-name').text();
                var totalScore = 0;
                var maxTotalScore = parseInt($(this).find('.max-total-score').val());

                $(this).find('.component-score').each(function() {
                    var score = parseFloat($(this).val()) || 0;
                    var maxScore = parseFloat($(this).attr('max'));

                    if (score > maxScore) {
                        isValid = false;
                        errorMessages.push(`${studentName}: Score ${score} exceeds maximum ${maxScore}`);
                        $(this).addClass('is-invalid');
                    } else {
                        $(this).removeClass('is-invalid');
                    }

                    totalScore += score;
                });

                // Update total display
                $(this).find('.total-score-display').text(totalScore.toFixed(1));
            });

            if (!isValid) {
                Swal.fire({
                    icon: 'error',
                    title: 'Validation Error',
                    html: errorMessages.join('<br>')
                });
                return;
            }

            // Submit the form
            saveFlexibleMarks();
        });

        function saveFlexibleMarks() {
            var formData = new FormData($('#flexible-mark-form')[0]);

            $.ajax({
                url: 'save-flexible-marks.php',
                method: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                beforeSend: function () {
                    $('#save-marks-btn').attr('disabled', 'disabled');
                    $('#save-marks-btn').html('<i class="fas fa-spinner fa-spin"></i> Saving...');
                },
                success: function (response) {
                    try {
                        const result = JSON.parse(response);
                        if (result.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Success',
                                text: 'Marks saved successfully!'
                            }).then(() => {
                                // Reload the mark entry form to show updated data
                                const className = $('#classID').val();
                                const term = $('#term').val();
                                const section = $('#section').val();
                                const subject = $('#subject').val();
                                loadFlexibleMarkEntry(className, term, section, subject);
                            });
                        } 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 while saving marks.'
                        });
                    }
                },
                error: function () {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to save marks. Please try again.'
                    });
                },
                complete: function () {
                    $('#save-marks-btn').attr('disabled', false);
                    $('#save-marks-btn').html('<i class="fas fa-save"></i> Save All Marks');
                }
            });
        }

        // Auto-calculate totals when component scores change
        $(document).on('input', '.component-score', function() {
            var row = $(this).closest('.student-row');
            var total = 0;

            row.find('.component-score').each(function() {
                total += parseFloat($(this).val()) || 0;
            });

            row.find('.total-score-display').text(total.toFixed(1));

            // Update percentage if needed
            var maxTotal = parseFloat(row.find('.max-total-score').val());
            var percentage = maxTotal > 0 ? (total / maxTotal * 100).toFixed(1) : 0;
            row.find('.percentage-display').text(percentage + '%');
        });
    </script>

    <style>
        /* media query */
        @media only screen and (max-width: 680px){
            /* display table data as block level element */
            table tr td, th {
                display: block !important;
                width: 100%;
            }
        }

    </style>

    <script>
        $(function () {
            $("#teacher").DataTable({
                "responsive": true, "lengthChange": false, "autoWidth": false,
                "buttons": ["copy", "csv", "pdf", "print", "colvis"]
            }).buttons().container().appendTo('#teacher_wrapper .col-md-6:eq(0)');
            $('#example2').DataTable({
                "paging": true,
                "lengthChange": false,
                "searching": true,
                "ordering": true,
                "info": true,
                "autoWidth": false,
                "responsive": true
            });
        });
    </script>


    <script>
        if ( window.history.replaceState ) {
            window.history.replaceState( null, null, window.location.href );
        }
    </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 '../admin/includes/styles.php'; ?>
        <title> Login to continue |  <?php echo $school_name; ?> </title>

        <!-- END PAGE LEVEL PLUGINS/CUSTOM STYLES -->

    </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 $teacher_login_link; ?>'>
                    </div>
                    <p>Redirecting to the login  page...</p>
                </div>
            </div>
        </div>
    </div>

    <?php
    }

    ?>
