<?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();

error_reporting(0);

include('includes/dbconnection.php');
include('includes/flash.php');

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



// Handle adding session

if (isset($_POST['add_session'])) {

    $session_name = trim($_POST['session_name']);

    $start_date = $_POST['start_date'];

    $end_date = $_POST['end_date'];



    if ($session_name && strtotime($start_date) < strtotime($end_date)) {

        $con->begin_transaction();

        try {

            $check_stmt = $con->prepare("SELECT 1 FROM school_sessions WHERE session_name = ?");

            $check_stmt->bind_param("s", $session_name);

            $check_stmt->execute();

            $check_stmt->store_result();



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

                $insert_stmt = $con->prepare("INSERT INTO school_sessions (session_name, start_date, end_date) VALUES (?, ?, ?)");

                $insert_stmt->bind_param("sss", $session_name, $start_date, $end_date);

                $insert_stmt->execute();



                if ($insert_stmt->affected_rows > 0) {

                    $con->commit();

                    flash_alert('Session added successfully!');

                } else {

                    throw new Exception('Insertion failed.');

                }

            } else {

                throw new Exception('Session already exists.');

            }

        } catch (Exception $e) {

            $con->rollback();

            flash_alert($e->getMessage());

        }

    } else {

        flash_alert('Invalid input: Ensure all fields are filled correctly.');

    }

}



// Handle deleting session

if (isset($_GET['delete_session'])) {

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

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

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

    $stmt->execute();

}



// Handle adding term

if (isset($_POST['add_term'])) {

    $session_id = $_POST['session_id'];

    $term_name = $_POST['term_name'];

    $start_date = $_POST['start_date'];

    $end_date = $_POST['end_date'];

    if (!empty($session_id) && !empty($term_name) && strtotime($start_date) < strtotime($end_date)) {

        $check_stmt = $con->prepare("SELECT id FROM school_terms WHERE session_id = ? AND term_name = ?");

        $check_stmt->bind_param("is", $session_id, $term_name);

        $check_stmt->execute();

        $check_stmt->store_result();

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

            $stmt = $con->prepare("INSERT INTO school_terms (session_id, term_name, start_date, end_date) VALUES (?, ?, ?, ?)");

            $stmt->bind_param("isss", $session_id, $term_name, $start_date, $end_date);

            $stmt->execute();

            flash_alert('Term added successfully!');

        } else {

            flash_alert('Term already exists for this session!');

        }

    } else {

        flash_alert('Please fill all fields correctly!');

    }

    $check_stmt->close();

}



// Handle deleting term

if (isset($_GET['delete_term'])) {

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

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

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

    $stmt->execute();

}



?>

<!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-calendar-alt"></i>

                                    </div>

                                    <div>

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

                                            Session Management

                                            <span class="premium-subtitle text-secondary">Manage Session</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">session</li>

                                    </ol>

                                </nav>

                            </div>

                        </div>

                    </div>

                </div>

            </section>



            <section class="content">

                <div class="container-fluid">

                    <div class="row">

                        <!-- Add Session -->

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

                            <div class="card shadow">

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

                                    <h5 class="card-title mb-0 font-weight-bold"><i class="fas fa-calendar-alt"></i> Add
                                        New Academic Session</h5>

                                </div>

                                <div class="card-body">

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

                                        <div class="mb-3">

                                            <label for="session">Academic Session (eg. 2024/2025)</label>

                                            <input type="text" class="form-control" name="session_name"
                                                placeholder="Enter session name" required>

                                        </div>

                                        <div class="mb-3">

                                            <label for="session">Start Date</label>

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

                                        </div>

                                        <div class="mb-3">

                                            <label for="session">End Date</label>

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

                                        </div>

                                        <center>

                                            <button type="submit" name="add_session" class="btn btn-primary"><i
                                                    class="fas fa-check-circle"></i> Add Session</button>

                                        </center>

                                    </form>

                                </div>

                            </div>



                            <!-- Existing Sessions -->

                            <div class="card shadow mt-3">

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

                                    <h5 class="card-title mb-0 font-weight-bold"><i class="fas fa-calendar-alt"></i>
                                        Existing Academic Sessions</h5>

                                </div>

                                <div class="card-body">

                                    <table id="example11" class="table table-bordered table-hover">

                                        <thead>

                                            <tr>

                                                <th>ID</th>

                                                <th>Session Name</th>

                                                <th>Action</th>

                                            </tr>

                                        </thead>

                                        <tbody>

                                            <?php

                                            $query = $con->query("SELECT * FROM school_sessions ORDER BY id DESC");

                                            while ($row = $query->fetch_assoc()) {

                                                echo "<tr>

                                                        <td>{$row['id']}</td>

                                                        <td>{$row['session_name']}</td>

                                                        <td>

                                                            <a href='?delete_session={$row['id']}' class='btn btn-xs btn-danger' onclick='return confirm(\"Delete this session?\")'>

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

                                                            </a>

                                                        </td>

                                                      </tr>";

                                            }

                                            ?>

                                        </tbody>

                                    </table>

                                </div>

                            </div>

                        </div>



                        <!-- Add Term -->

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

                            <div class="card shadow">

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

                                    <h5 class="card-title mb-0 font-weight-bold"><i class="fas fa-clock"></i> Add Term
                                    </h5>

                                </div>

                                <div class="card-body">

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

                                        <div class="mb-3">

                                            <label for="session">Academic Session</label>

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

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

                                                <?php

                                                $query1 = $con->query("SELECT id, session_name FROM school_sessions ORDER BY session_name DESC");

                                                while ($row1 = $query1->fetch_assoc()) {

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

                                                }

                                                ?>

                                            </select>

                                        </div>

                                        <div class="mb-3">

                                            <label for="session">Term</label>

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

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

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

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

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

                                            </select>

                                        </div>

                                        <div class="mb-3">

                                            <label for="session">Start Date</label>

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

                                        </div>

                                        <div class="mb-3">

                                            <label for="session">End Date</label>

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

                                        </div>

                                        <center>

                                            <button type="submit" name="add_term" class="btn btn-primary"><i
                                                    class="fas fa-check-circle"></i> Add Term</button>

                                        </center>

                                    </form>

                                </div>

                            </div>



                            <!-- Existing Terms -->

                            <div class="card shadow mt-3">

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

                                    <h5 class="card-title mb-0 font-weight-bold"><i class="fas fa-clock"></i> Existing
                                        Terms</h5>

                                </div>

                                <div class="card-body">

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

                                        <thead>

                                            <tr>

                                                <th>ID</th>

                                                <th>Session</th>

                                                <th>Term</th>

                                                <th>Start Date</th>

                                                <th>End Date</th>

                                                <th>Action</th>

                                            </tr>

                                        </thead>

                                        <tbody>

                                            <?php

                                            $query2 = $con->query("SELECT t.id, s.session_name, t.term_name, t.start_date, t.end_date 

                                                                  FROM school_terms t JOIN school_sessions s ON t.session_id = s.id 

                                                                  ORDER BY t.id DESC");

                                            while ($row2 = $query2->fetch_assoc()) {

                                                echo "<tr>

                                                        <td>{$row2['id']}</td>

                                                        <td>{$row2['session_name']}</td>

                                                        <td>{$row2['term_name']}</td>

                                                        <td>{$row2['start_date']}</td>

                                                        <td>{$row2['end_date']}</td>

                                                        <td>

                                                            <button class='btn btn-primary btn-xs edit_data' data-id='{$row2['id']}'><i class='fa fa-edit'></i> Edit</button>



                                                            <a href='?delete_term={$row2['id']}' class='btn btn-xs btn-danger' onclick='return confirm(\"Delete this term?\")'>

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

                                                            </a>

                                                        </td>

                                                      </tr>";

                                            }

                                            ?>

                                        </tbody>

                                    </table>

                                </div>

                            </div>

                            <!-- Edit Session and Term Modal -->

                            <div id="editData" class="modal fade">

                                <div class="modal-dialog">

                                    <div class="modal-content">

                                        <div class="modal-header">

                                            <h5 class="modal-title">Edit Session and Term</h5>

                                            <button type="button" class="close" data-dismiss="modal">

                                                <span>&times;</span>

                                            </button>

                                        </div>

                                        <div class="modal-body" id="info_update"></div>

                                    </div>

                                </div>

                            </div>







                        </div>

                    </div>

                </div>

            </section>

        </div>



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

    </div>

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

    <script src="dist/js/select2.min.js"></script>

    <script>

        // In your Javascript (external .js resource or <script> tag)

        $(document).ready(function () {

            $('#session').select2();

            $('#term').select2();



            $(document).on('click', '.edit_data', function () {

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

                $.ajax({

                    url: "edit_term_session.php",

                    type: "POST",

                    data: {

                        edit_id: edit_id

                    },

                    success: function (response) {

                        $("#info_update").html(response);

                        $("#editData").modal('show');

                    }

                });

            });

            // Handle Update Form Submission

            $(document).on('submit', '#updateEventForm', function (e) {

                e.preventDefault();

                $.ajax({

                    url: "update_term_session.php",

                    type: "POST",

                    data: $(this).serialize(),

                    success: function (response) {

                        response = response.trim();

                        if (response === "success") {

                            alert("Term and session updated successfully!");

                            location.reload();

                        } else {

                            alert("Something went wrong. Try again.");

                        }

                    }

                });

            });



        });

    </script>

</body>



</html>