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

require_once('includes/dbconnection.php');

require_once __DIR__ . '/includes/session_term_helper.php';
// Fetch current session and term (with gap/fallback support)
$stResult = resolveCurrentSessionTerm($con);
$currentSessionId   = $stResult['session_id'];
$currentSessionName = $stResult['session_name'];
$currentTermId      = $stResult['term_id'];
$currentTermName    = $stResult['term_name'];
require_once __DIR__ . '/includes/session_term_helper.php';
// Fetch current session and term (with gap/fallback support)
$stResult = resolveCurrentSessionTerm($con);
$currentSessionId   = $stResult['session_id'];
$currentSessionName = $stResult['session_name'];
$currentTermId      = $stResult['term_id'];
$currentTermName    = $stResult['term_name'];


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

    header("Location: logout.php");

    exit();

}



/* ======================================================

   ADD ANNOUNCEMENT

====================================================== */

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

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

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

    $days = intval($_POST['days_to_display']);



    $stmt = $con->prepare("INSERT INTO announcements (title, message, days_to_display) VALUES (?, ?, ?)");

    $stmt->bind_param("ssi", $title, $message, $days);



    if ($stmt->execute()) {

        $alert = "Announcement Added Successfully!";

    } else {

        $alert = "Error occurred while adding. Try again.";

    }

}



/* ======================================================

   DELETE ANNOUNCEMENT

====================================================== */

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

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

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

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

    $stmt->execute();



    $alert = "Announcement Deleted.";

}



/* ======================================================

   FETCH SINGLE RECORD FOR EDIT

====================================================== */

$editData = null;



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

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



    $stmt = $con->prepare("SELECT * FROM announcements WHERE id=? LIMIT 1");

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

    $stmt->execute();

    $editData = $stmt->get_result()->fetch_assoc();

}



/* ======================================================

   UPDATE ANNOUNCEMENT

====================================================== */

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

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

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

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

    $days = intval($_POST['days_to_display']);



    $stmt = $con->prepare("UPDATE announcements SET title=?, message=?, days_to_display=? WHERE id=?");

    $stmt->bind_param("ssii", $title, $message, $days, $id);



    if ($stmt->execute()) {

        $alert = "Announcement Updated Successfully!";

    } else {

        $alert = "Update Failed!";

    }



    $editData = null; // close modal after update

}

?>



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

                        </div>

                        <div>

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

                                Announcement Management

                                <span class="premium-subtitle text-secondary">Manage Announcements</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">Add Announcement</li>

                        </ol>

                    </nav>

                </div>

            </div>

        </div>

    </div>

</section> 





<section class="content">

<div class="container-fluid">



<?php if (!empty($alert)) { ?>

    <div class="alert alert-info"><?= $alert ?></div>

<?php } ?>



<div class="row">



<!-- ADD FORM -->

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

<div class="card shadow">

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

        <h5 class="font-weight-bold"><i class="fas fa-plus-circle"></i> Add Announcement</h5>

    </div>



    <div class="card-body">

        <form method="POST">



            <div class="row">

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

                    <label>Announcement Title</label>

                    <input type="text" name="title" class="form-control" required>

                </div>



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

                    <label>Days to Display</label>

                    <input type="number" name="days_to_display" min="1" class="form-control" required>

                </div>

            </div>



            <div class="form-group">

                <label>Announcement Message</label>

                <textarea name="message" class="form-control" rows="3" required></textarea>

            </div>



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

                <i class="fa fa-check-circle"></i> Add Announcement

            </button>



        </form>

    </div>

</div>

</div>





<!-- TABLE OF ANNOUNCEMENTS -->

<div class="col-md-12 mt-3">

<div class="card shadow">

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

        <h5 class="font-weight-bold"><i class="fas fa-list"></i> Existing Announcements</h5>

    </div>



    <div class="card-body">

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

            <thead>

                <tr>

                    <th>#</th>

                    <th>Title</th>

                    <th>Message</th>

                    <th>Days</th>

                    <th>Created</th>

                    <th>Expires</th>

                    <th>Action</th>

                </tr>

            </thead>

            <tbody>



            <?php

            $result = $con->query("

                SELECT *,

                DATE_ADD(created_at, INTERVAL days_to_display DAY) AS expiry_date

                FROM announcements ORDER BY id DESC

            ");



            $count = 1;

            while ($row = $result->fetch_assoc()) { ?>

                <tr>

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

                    <td><?= htmlentities($row['title']); ?></td>

                    <td><?= htmlentities($row['message']); ?></td>

                    <td><?= $row['days_to_display']; ?></td>

                    <td><?= $row['created_at']; ?></td>

                    <td><?= $row['expiry_date']; ?></td>



                    <td>

                        <a href="?edit=<?= $row['id']; ?>" class="btn btn-success btn-xs">

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

                        </a>



                        <a href="?delete=<?= $row['id']; ?>"

                           onclick="return confirm('Delete this announcement?')"

                           class="btn btn-danger btn-xs">

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

                        </a>

                    </td>

                </tr>

            <?php } ?>



            </tbody>

        </table>

    </div>

</div>

</div>





<!-- EDIT MODAL -->

<?php if ($editData) { ?>

<div class="modal fade show" id="editModal" style="display:block; background:rgba(0,0,0,.6);">

<div class="modal-dialog">

<div class="modal-content">



    <div class="modal-header">

        <h5>Edit Announcement</h5>

        <a href="announcement.php" class="close">&times;</a>

    </div>



    <div class="modal-body">

        <form method="POST">



            <input type="hidden" name="id" value="<?= $editData['id']; ?>">



            <div class="form-group">

                <label>Announcement Title</label>

                <input type="text" name="title" class="form-control"

                       value="<?= htmlentities($editData['title']); ?>" required>

            </div>



            <div class="form-group">

                <label>Days to Display</label>

                <input type="number" name="days_to_display" min="1" class="form-control"

                       value="<?= $editData['days_to_display']; ?>" required>

            </div>



            <div class="form-group">

                <label>Announcement Message</label>

                <textarea name="message" class="form-control" rows="4" required><?= htmlentities($editData['message']); ?></textarea>

            </div>



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

                Update Announcement

            </button>



        </form>

    </div>



</div>

</div>

</div>

<?php } ?>



</div>

</div>

</section>



</div>



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

</div>



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



</body>

</html>

