<?php

session_name('super_admin_session');

if (!is_dir(dirname(__DIR__) . '/session_data/super')) { mkdir(dirname(__DIR__) . '/session_data/super', 0700, true); } session_save_path(dirname(__DIR__) . '/session_data/super');

session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);

session_start();

include('includes/dbconnection.php');
require_once 'includes/session_term_helper.php';
$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName    = $stResult['term_name'];

include('includes/flash.php');



if (!isset($_SESSION['sid'])) {

    header('location:logout.php');

    exit();

}



// CSRF

if (empty($_SESSION['csrf_token'])) {

    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));

}



$success = $error = "";



// Add new schedule

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['publish'])) {

    $termId = intval($_POST['term']);

    $sessionId = intval($_POST['session']);

    $datetime = $_POST['publish_datetime'];

    $result_type = $_POST['result_type']; 



    $vacating_date   = ($result_type === 'Endterm' && !empty($_POST['vacating_date'])) ? $_POST['vacating_date'] : null;

    $resumption_date = ($result_type === 'Endterm' && !empty($_POST['resumption_date'])) ? $_POST['resumption_date'] : null;



    if ($termId && $sessionId && $datetime && $result_type) {



        // ✅ Check academic calendar first

        $calendarCheck = $con->prepare("SELECT id FROM school_calendar WHERE session_id=? AND term_id=? LIMIT 1");

        $calendarCheck->bind_param("ii", $sessionId, $termId);

        $calendarCheck->execute();

        $calendarResult = $calendarCheck->get_result();



        if ($calendarResult->num_rows === 0) {

            $error = "You must set the Academic Calendar for this Session & Term before publishing results.";

            flash_alert($error, 'publish_result.php');
        header('Location: publish_result.php'); exit;

            exit();

        }



        // If calendar exists → continue with publication

        $stmt = $con->prepare("

            INSERT INTO result_publish_schedule 

                (session_id, term_id, result_type, publish_datetime, vacating_date, resumption_date)

            VALUES (?, ?, ?, ?, ?, ?)

            ON DUPLICATE KEY UPDATE 

                publish_datetime = VALUES(publish_datetime),

                vacating_date = VALUES(vacating_date),

                resumption_date = VALUES(resumption_date)

        ");

        $stmt->bind_param("iissss", $sessionId, $termId, $result_type, $datetime, $vacating_date, $resumption_date);



        if ($stmt->execute()) {

            $success = "Result publication scheduled successfully.";

        } else {

            $error = "Failed to schedule result publication.";

        }

    } else {

        $error = "All fields are required.";

    }

    flash_alert(($success ?: $error), 'publish_result.php');
        header('Location: publish_result.php'); exit;

}





// Update existing schedule

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update'])) {

    $id = intval($_POST['id']);

    $sessionId = intval($_POST['session_id']);

    $termId = intval($_POST['term_id']);

    $result_type = $_POST['result_type'];

    $datetime = $_POST['publish_datetime'];



    // Handle Endterm fields

    $vacating_date   = ($result_type === 'Endterm' && !empty($_POST['vacating_date'])) ? $_POST['vacating_date'] : null;

    $resumption_date = ($result_type === 'Endterm' && !empty($_POST['resumption_date'])) ? $_POST['resumption_date'] : null;



    if ($id && $sessionId && $termId && $result_type && $datetime) {

        $stmt = $con->prepare("UPDATE result_publish_schedule 

                               SET session_id=?, term_id=?, result_type=?, publish_datetime=?, 

                                   vacating_date=?, resumption_date=? 

                               WHERE id=?");

        $stmt->bind_param("iissssi", $sessionId, $termId, $result_type, $datetime, $vacating_date, $resumption_date, $id);

        if ($stmt->execute()) {

            flash_alert('Publication updated successfully.', 'publish_result.php');
        header('Location: publish_result.php'); exit;

        } else {

            flash_alert('Failed to update record.');

        }

    }

}



// Delete schedule

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete'])) {

    $id = intval($_POST['id']);

    if ($id) {

        $stmt = $con->prepare("DELETE FROM result_publish_schedule WHERE id=?");

        $stmt->bind_param("i", $id);

        if ($stmt->execute()) {

            flash_alert('Publication deleted successfully.', 'publish_result.php');
        header('Location: publish_result.php'); exit;

        } else {

            flash_alert('Failed to delete record.');

        }

    }

}



// Fetch sessions and terms

$sessions = mysqli_query($con, "SELECT id, session_name FROM school_sessions ORDER BY id DESC");

$terms = mysqli_query($con, "SELECT id, term_name FROM school_terms ORDER BY id DESC");



// Fetch existing schedules

$existing = [];

$res = mysqli_query($con, "

    SELECT r.id, r.session_id, r.term_id, 

           s.session_name, t.term_name, 

           r.result_type, r.publish_datetime,

           r.vacating_date, r.resumption_date

    FROM result_publish_schedule r

    JOIN school_sessions s ON s.id = r.session_id

    JOIN school_terms t ON t.id = r.term_id

    ORDER BY r.publish_datetime DESC

");

while ($row = mysqli_fetch_assoc($res)) {

    $existing[] = $row;

}

?>

<!DOCTYPE html>

<html>

<?php @include("includes/head.php"); ?>

<body class="hold-transition sidebar-mini layout-fixed">

<div class="wrapper">

    <?php @include("includes/header.php"); ?>

    <?php @include("includes/sidebar.php"); ?>



    <div class="content-wrapper">

             <section class="content-header premium-header">

    <div class="container-fluid">

        <div class="header-glass-card">

            <div class="row align-items-center">

                <div class="col-md-8">

                    <div class="title-section">

                        <div class="icon-box bg-primary-gradient shadow-sm">

                            <i class="fas fa-clipboard-list"></i>

                        </div>

                        <div>

                            <h1 class="premium-title text-primary">

                            Result Management

                                <span class="premium-subtitle text-secondary">Manage Result Publication</span>

                            </h1>
                            <div class="mt-1">
                              <?php if ($currentSessionName): ?>
                                <span class="badge badge-primary mr-1">
                                  <i class="fas fa-calendar-alt"></i>
                                  <?= htmlspecialchars($currentSessionName) ?>
                                </span>
                              <?php endif; ?>
                              <?php if ($currentTermName): ?>
                                <span class="badge badge-success">
                                  <i class="fas fa-bookmark"></i>
                                  <?= htmlspecialchars($currentTermName) ?>
                                </span>
                              <?php else: ?>
                                <span class="badge badge-warning">
                                  <i class="fas fa-exclamation-triangle"></i> No active term
                                </span>
                              <?php endif; ?>
                            </div>

                        </div>

                    </div>

                </div>

                <div class="col-md-4">

                    <nav aria-label="breadcrumb">

                        <ol class="breadcrumb premium-breadcrumb">

                            <li class="breadcrumb-item"><a href="dashboard.php" class="text-primary">Home</a></li>

                            <li class="breadcrumb-item active" aria-current="page">Publish Result</li>

                        </ol>

                    </nav>

                </div>

            </div>

        </div>

    </div>

</section>  



    <section class="content">

        <div class="container-fluid">

            <!-- Schedule Form -->

            <div class="card shadow-sm border-0">

                <div class="card-header bg-primary text-white">

                    <h3 class="card-title"><i class="fas fa-calendar-plus"></i> Set Result Publication Date & Time</h3>

                </div>

                <div class="card-body">

                    <form method="POST">

                        <div class="row">

                            <div class="form-group col-md-6">

                                <label>Academic Session:</label>

                                <select id="session" name="session" class="form-control select2" required>

                                    <option value="">Select Session</option>

                                    <?php while ($row = mysqli_fetch_assoc($sessions)) {

                                        echo "<option value='{$row['id']}'>{$row['session_name']}</option>";

                                    } ?>

                                </select>

                            </div>

                            <div class="form-group col-md-6">

                                <label>Term:</label>

                                <select id="term" name="term" class="form-control select2" required>

                                    <option value="">Select Term</option>

                                </select>

                            </div>

                            <div class="form-group col-md-6">

                                <label>Result Type:</label>

                                <select name="result_type" id="result_type" class="form-control select2" required>

                                    <option value="">Select Result Type</option>

                                    <option value="Midterm">Mid Term</option>

                                    <option value="Endterm">End of Term</option>

                                </select>

                            </div>                                

                            <div class="form-group col-md-6">

                                <label>Publication Date & Time:</label>

                                <input type="datetime-local" name="publish_datetime" class="form-control" required>

                            </div>



                            <!-- Endterm extra fields -->

                            <div class="form-group col-md-6 endterm-fields" style="display:none;">

                                <label>Next Resumption Date:</label>

                                <input type="date" name="resumption_date" class="form-control">

                            </div>

                            <div class="form-group col-md-6 endterm-fields" style="display:none;">

                                <label>Next Vacating Date:</label>

                                <input type="date" name="vacating_date" class="form-control">

                            </div>





                        </div>

                        <div class="text-center">

                            <button type="submit" name="publish" class="btn btn-primary">

                                <i class="fas fa-check-circle"></i> Schedule Publication

                            </button>

                        </div>

                    </form>

                </div>

            </div>



            <!-- Existing Schedules -->

            <?php if (!empty($existing)): ?>

            <div class="card mt-4 shadow-sm border-0">

                <div class="card-header bg-info text-white">

                    <h3 class="card-title"><i class="fas fa-history"></i> Scheduled Publications</h3>

                </div>

                <div class="card-body">

                    <table id="example1" class="table table-bordered table-striped">

                        <thead>

                            <tr>

                                <th>#</th>

                                <th>Session</th>

                                <th>Term</th>

                                <th>Result Type</th>

                                <th>Scheduled Date & Time</th>

                                <th>Next Resumption Date</th>

                                <th>Next Vacation Date</th>

                                <th>Action</th>

                            </tr>

                        </thead>

                        <tbody>

                            <?php $sn = 1; foreach ($existing as $pub): ?>

                            <tr>

                                <td><?= $sn++; ?></td>

                                <td><?= htmlspecialchars($pub['session_name']); ?></td>

                                <td><?= htmlspecialchars($pub['term_name']); ?></td>

                                <td>

                                    <?= ($pub['result_type'] === 'Midterm') ? 'Mid Term' : (($pub['result_type'] === 'Endterm') ? 'End of Term' : htmlspecialchars($pub['result_type'])); ?>

                                </td>

                                <td><?= date("F j, Y - g:i A", strtotime($pub['publish_datetime'])); ?></td>

                                <td><?= $pub['resumption_date'] ? date("F j, Y", strtotime($pub['resumption_date'])) : '-'; ?></td>

                                <td><?= $pub['vacating_date'] ? date("F j, Y", strtotime($pub['vacating_date'])) : '-'; ?></td>

                                <td>

                                    <button type="button" 

                                        class="btn btn-xs btn-warning editBtn" 

                                        data-id="<?= $pub['id']; ?>"

                                        data-session="<?= $pub['session_id']; ?>"  

                                        data-term="<?= $pub['term_id']; ?>"       

                                        data-type="<?= htmlspecialchars($pub['result_type']); ?>"

                                        data-datetime="<?= date("Y-m-d\TH:i", strtotime($pub['publish_datetime'])); ?>"

                                        data-vacating="<?= $pub['vacating_date']; ?>"

                                        data-resumption="<?= $pub['resumption_date']; ?>">

                                        <i class="fas fa-edit"></i> Edit

                                    </button>



                                    <button type="button" 

                                            class="btn btn-xs btn-danger deleteBtn"

                                            data-id="<?= $pub['id']; ?>">

                                        <i class="fas fa-trash"></i> Delete

                                    </button>

                                </td>

                            </tr>

                            <?php endforeach; ?>

                        </tbody>

                    </table>

                </div>

            </div>

            <?php endif; ?>

        </div>

    </section>

    </div>



    <?php @include("includes/foot.php"); ?>

    <?php @include("includes/footer.php"); ?>

</div>



<!-- Edit Modal -->

<div class="modal fade" id="editModal" tabindex="-1" role="dialog">

  <div class="modal-dialog modal-lg" role="document">

    <div class="modal-content">

      <form method="POST" action="">

        <div class="modal-header bg-primary text-white">

          <h5 class="modal-title"><i class="fas fa-edit"></i> Edit Scheduled Publication</h5>

          <button type="button" class="close" data-dismiss="modal">&times;</button>

        </div>

        <div class="modal-body">

            <div class= "row">

            <input type="hidden" name="id" id="edit_id">

            <div class="form-group col-md-6">

                <label>Academic Session:</label>

                <select name="session_id" id="edit_session" class="form-control" required>

                    <option value="">Select Session</option>

                    <?php

                        $sessions2 = mysqli_query($con, "SELECT id, session_name FROM school_sessions ORDER BY id DESC");

                        while ($row = mysqli_fetch_assoc($sessions2)) {

                            echo "<option value='{$row['id']}'>{$row['session_name']}</option>";

                        }

                    ?>

                </select>

            </div>

            <div class="form-group col-md-6">

                <label>Term:</label>

                <select name="term_id" id="edit_term" class="form-control" required>

                    <option value="">Select Term</option>

                    <?php

                        $terms2 = mysqli_query($con, "SELECT id, term_name FROM school_terms ORDER BY id DESC");

                        while ($row = mysqli_fetch_assoc($terms2)) {

                            echo "<option value='{$row['id']}'>{$row['term_name']}</option>";

                        }

                    ?>

                </select>

            </div>

            <div class="form-group col-md-6">

                <label>Result Type:</label>

                <select name="result_type" id="edit_type" class="form-control" required>

                    <option value="Midterm">Mid Term</option>

                    <option value="Endterm">End of Term</option>

                </select>

            </div>

            <div class="form-group col-md-6">

                <label>Publication Date & Time:</label>

                <input type="datetime-local" name="publish_datetime" id="edit_datetime" class="form-control" required>

            </div>



            <!-- Endterm extra fields -->

                         <div class="form-group col-md-6 endterm-fields" style="display:none;">

                <label>Next Resumption Date:</label>

                <input type="date" name="resumption_date" id="edit_resumption_date" class="form-control">

            </div>

            <div class="form-group col-md-6 endterm-fields" style="display:none;">

                <label>Next Vacating Date:</label>

                <input type="date" name="vacating_date" id="edit_vacating_date" class="form-control">

            </div>





            </div>

        </div>

        <div class="modal-footer">

          <button type="submit" name="update" class="btn btn-success"><i class="fas fa-save"></i> Update</button>

          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>

        </div>

      </form>

    </div>

  </div>

</div>



<!-- Delete Modal -->

<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog">

  <div class="modal-dialog" role="document">

    <div class="modal-content">

      <form method="POST" action="">

        <div class="modal-header bg-danger text-white">

          <h5 class="modal-title"><i class="fas fa-trash"></i> Confirm Delete</h5>

          <button type="button" class="close" data-dismiss="modal">&times;</button>

        </div>

        <div class="modal-body">

          <input type="hidden" name="id" id="delete_id">

          <p>Are you sure you want to delete this scheduled publication?</p>

        </div>

        <div class="modal-footer">

          <button type="submit" name="delete" class="btn btn-danger">Yes, Delete</button>

          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>

        </div>

      </form>

    </div>

  </div>

</div>



<script>

$(document).ready(function() {

    $('.select2').select2();



    // Populate terms on session select

    $('#session').change(function() {

        var selectedClass = $(this).val();

        if (selectedClass) {

            $.ajax({

                url: 'fetch_session.php',

                type: 'POST',

                data: { class_name: selectedClass },

                success: function(response) {

                    $('#term').html(response);

                }

            });

        } else {

            $('#term').html('<option value="">Select Term</option>');

        }

    });



    // Show/hide Endterm fields

    $('#result_type').change(function() {

        if ($(this).val() === 'Endterm') {

            $('.endterm-fields').show();

        } else {

            $('.endterm-fields').hide();

        }

    });



    // Edit button

    $(document).on("click", ".editBtn", function() {

        var id       = $(this).data("id");

        var session  = $(this).data("session");

        var term     = $(this).data("term");

        var type     = $(this).data("type");

        var datetime = $(this).data("datetime");

        var vacating = $(this).data("vacating");

        var resumption = $(this).data("resumption");



        $("#edit_id").val(id);

        $("#edit_session").val(session).trigger("change");

        $("#edit_term").val(term).trigger("change");

        $("#edit_type").val(type);

        $("#edit_datetime").val(datetime);

        $("#edit_vacating_date").val(vacating);

        $("#edit_resumption_date").val(resumption);



        if (type === 'Endterm') {

            $("#editModal .endterm-fields").show();

        } else {

            $("#editModal .endterm-fields").hide();

        }



        $("#editModal").modal("show");

    });



    // Delete button

    $('.deleteBtn').on('click', function() {

        var id = $(this).data('id');

        $('#delete_id').val(id);

        $('#deleteModal').modal('show');

    });

});

</script>



</body>

</html>

