<?php
/**
 * EdumacFlo Session and Term Management
 * Manage Active Academic Session (e.g. 2025/2026) and Terms (First, Second, Third Term)
 */

$date_today = date('Y-m-d');

// 1. QUICK / FORM ACTION TO SWITCH CURRENT TERM
if (isset($_POST['current_term_btn']) || isset($_GET['quick_term'])) {
    $current_term = isset($_POST['current_term']) ? inject_checker($connection, $_POST['current_term']) : inject_checker($connection, $_GET['quick_term']);

    $valid_terms = ['First Term', 'Second Term', 'Third Term'];
    if (!in_array($current_term, $valid_terms)) {
        $_SESSION['msg'] = "Please select a valid academic term (First, Second, or Third Term).";
        $_SESSION['type'] = "warning";
    } else {
        $check_q = mysqli_query($connection, "SELECT * FROM `current_season` LIMIT 1");
        if (mysqli_num_rows($check_q) == 0) {
            $query = "INSERT INTO `current_season` (`current_session`, `current_term`, `date_declared`, `time_declared`) VALUES ('2025/2026', '{$current_term}', '{$date_today}', NOW())";
        } else {
            $query = "UPDATE `current_season` SET `current_term` = '{$current_term}', `date_declared` = '{$date_today}', `time_declared` = NOW()";
        }
        $run_query = mysqli_query($connection, $query);

        if ($run_query) {
            $_SESSION['msg'] = "Active academic term successfully set to: <strong>{$current_term}</strong>";
            $_SESSION['type'] = "success";
        } else {
            $_SESSION['msg'] = "Failed to update current term.";
            $_SESSION['type'] = "error";
        }
    }
    header("Location: session_term");
    exit();
}

// 2. QUICK / FORM ACTION TO SWITCH CURRENT SESSION
if (isset($_POST['current_session_btn']) || isset($_GET['quick_session'])) {
    $current_session = isset($_POST['current_session']) ? inject_checker($connection, $_POST['current_session']) : inject_checker($connection, $_GET['quick_session']);

    if (empty($current_session) || $current_session === "Select Current Session") {
        $_SESSION['msg'] = "Please select a valid academic session.";
        $_SESSION['type'] = "warning";
    } else {
        $check_q = mysqli_query($connection, "SELECT * FROM `current_season` LIMIT 1");
        if (mysqli_num_rows($check_q) == 0) {
            $query = "INSERT INTO `current_season` (`current_session`, `current_term`, `date_declared`, `time_declared`) VALUES ('{$current_session}', 'First Term', '{$date_today}', NOW())";
        } else {
            $query = "UPDATE `current_season` SET `current_session` = '{$current_session}', `date_declared` = '{$date_today}', `time_declared` = NOW()";
        }
        $run_query = mysqli_query($connection, $query);

        if ($run_query) {
            $_SESSION['msg'] = "Active academic session successfully set to: <strong>{$current_session}</strong>";
            $_SESSION['type'] = "success";
        } else {
            $_SESSION['msg'] = "Failed to update current session.";
            $_SESSION['type'] = "error";
        }
    }
    header("Location: session_term");
    exit();
}

// 3. ACTION TO ADD NEW SESSION
if (isset($_POST['add_session_btn'])) {
    $add_session = trim(inject_checker($connection, $_POST['add_session']));

    if (empty($add_session)) {
        $_SESSION['msg'] = "Please enter the academic session (e.g. 2025/2026).";
        $_SESSION['type'] = "warning";
    } else {
        $query = "SELECT * FROM `sessions` WHERE `sessions` = '{$add_session}'";
        $run_query = mysqli_query($connection, $query);

        if (mysqli_num_rows($run_query) > 0) {
            $_SESSION['msg'] = "Session <strong>{$add_session}</strong> is already registered.";
            $_SESSION['type'] = "warning";
        } else {
            $formatted_date = date('d-M-Y');
            $query = "INSERT INTO `sessions`(`sessions`, `date_added`) VALUES('{$add_session}', '{$formatted_date}')";
            $run_query = mysqli_query($connection, $query);

            if ($run_query) {
                $_SESSION['msg'] = "New session <strong>{$add_session}</strong> added successfully.";
                $_SESSION['type'] = "success";
            } else {
                $_SESSION['msg'] = "Failed to add new session.";
                $_SESSION['type'] = "error";
            }
        }
    }
    header("Location: session_term");
    exit();
}

// 4. ACTION TO UPDATE RESUMPTION AND CLOSING DATES
if (isset($_POST['result_date_btn'])) {
    $term_end_date  = inject_checker($connection, $_POST['term_end_date']);
    $next_term_date = inject_checker($connection, $_POST['next_term_date']);

    if (empty($term_end_date) || empty($next_term_date)) {
        $_SESSION['msg']  = "Please specify both the Term Closing Date and Next Term Resumption Date.";
        $_SESSION['type'] = "warning";
    } else {
        $query = "SELECT * FROM `dates`";
        $run_query = mysqli_query($connection, $query);

        if (mysqli_num_rows($run_query) == 0) {
            $query = "INSERT INTO `dates`(`end_of_term`, `next_term_begins`, `date_declared`, `time_declared`) 
                      VALUES('$term_end_date', '$next_term_date', '$date_today', NOW())";
            $run_query = mysqli_query($connection, $query);
        } else {
            $query = "UPDATE `dates` SET 
                      `end_of_term` = '{$term_end_date}', 
                      `next_term_begins` = '{$next_term_date}', 
                      `date_declared` = '{$date_today}'";
            $run_query = mysqli_query($connection, $query);
        }

        if ($run_query) {
            $_SESSION['msg']  = "Academic term dates updated successfully.";
            $_SESSION['type'] = "success";
        } else {
            $_SESSION['msg']  = "Failed to update academic dates.";
            $_SESSION['type'] = "error";
        }
    }
    header("Location: session_term");
    exit();
}

// FETCH CURRENT VALUES
$show_current_term = 'First Term';
$show_current_session = '2025/2026';
$query_season = mysqli_query($connection, "SELECT * FROM `current_season` LIMIT 1");
if ($query_season && mysqli_num_rows($query_season) > 0) {
    $season_res = mysqli_fetch_assoc($query_season);
    $show_current_term = $season_res['current_term'] ?? 'First Term';
    $show_current_session = $season_res['current_session'] ?? '2025/2026';
}

$show_term_end = '';
$show_next_term = '';
$query_dates = mysqli_query($connection, "SELECT * FROM `dates` LIMIT 1");
if ($query_dates && mysqli_num_rows($query_dates) > 0) {
    $dates_res = mysqli_fetch_assoc($query_dates);
    $show_term_end = $dates_res['end_of_term'] ?? '';
    $show_next_term = $dates_res['next_term_begins'] ?? '';
}

// Fetch all registered sessions
$registered_sessions = [];
$sessions_q = mysqli_query($connection, "SELECT * FROM `sessions` ORDER BY `id` DESC");
if ($sessions_q) {
    while ($s_row = mysqli_fetch_assoc($sessions_q)) {
        $registered_sessions[] = $s_row;
    }
}
?>

<div class='page-title'>
    <div>
        <h1><i class='fa fa-calendar-alt'></i> Session & Term Management</h1>
        <p>Configure Active Academic Year, Terms (1st, 2nd, 3rd), and Term Calendars</p>
    </div>
</div>

<!-- Active Season KPI Banner -->
<div class="row" style="margin-bottom: 20px;">
    <div class="col-md-4 col-sm-6">
        <div class="card" style="background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%); color:#fff; border-radius:12px; padding:18px 20px; box-shadow:0 4px 15px rgba(0,0,0,0.1);">
            <div style="font-size:12px; text-transform:uppercase; letter-spacing:1px; opacity:0.85;">Current Academic Session</div>
            <div style="font-size:26px; font-weight:800; margin:6px 0;"><?= htmlspecialchars($show_current_session) ?></div>
            <div style="font-size:12px; opacity:0.9;"><i class="fa fa-check-circle"></i> Active School Year</div>
        </div>
    </div>
    <div class="col-md-4 col-sm-6">
        <div class="card" style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color:#fff; border-radius:12px; padding:18px 20px; box-shadow:0 4px 15px rgba(0,0,0,0.1);">
            <div style="font-size:12px; text-transform:uppercase; letter-spacing:1px; opacity:0.85;">Current Academic Term</div>
            <div style="font-size:26px; font-weight:800; margin:6px 0;"><?= htmlspecialchars($show_current_term) ?></div>
            <div style="font-size:12px; opacity:0.9;"><i class="fa fa-bookmark"></i> Active Semester / Term</div>
        </div>
    </div>
    <div class="col-md-4 col-sm-12">
        <div class="card" style="background: linear-gradient(135deg, #f857a6 0%, #ff5858 100%); color:#fff; border-radius:12px; padding:18px 20px; box-shadow:0 4px 15px rgba(0,0,0,0.1);">
            <div style="font-size:12px; text-transform:uppercase; letter-spacing:1px; opacity:0.85;">Term Resumption / Ending</div>
            <div style="font-size:16px; font-weight:700; margin:6px 0;">
                Ends: <?= !empty($show_term_end) ? date('M d, Y', strtotime($show_term_end)) : 'Not Set' ?><br>
                Next Resumes: <?= !empty($show_next_term) ? date('M d, Y', strtotime($show_next_term)) : 'Not Set' ?>
            </div>
            <div style="font-size:12px; opacity:0.9;"><i class="fa fa-clock"></i> Academic Calendar Dates</div>
        </div>
    </div>
</div>

<!-- Term Quick Switcher Banner -->
<div class="card" style="border-radius:12px; margin-bottom:25px; padding:20px; box-shadow:0 2px 10px rgba(0,0,0,0.05);">
    <h4 style="margin-top:0; font-weight:700; color:#2c3e50;"><i class="fa fa-toggle-on text-success"></i> 1-Click Term Switcher (Session: <?= htmlspecialchars($show_current_session) ?>)</h4>
    <p class="text-muted" style="font-size:13px;">Click any button below to instantly switch the active term for the whole school:</p>
    <div class="btn-group btn-group-justified" role="group" style="margin-top:10px;">
        <a href="session_term?quick_term=First+Term" class="btn btn-lg <?= ($show_current_term === 'First Term') ? 'btn-success' : 'btn-default' ?>" style="font-weight:700; border-radius:8px 0 0 8px;">
            <i class="fa <?= ($show_current_term === 'First Term') ? 'fa-check-circle' : 'fa-circle' ?>"></i> First Term
            <?= ($show_current_term === 'First Term') ? ' <span class="badge" style="background:#fff; color:#27ae60; margin-left:5px;">ACTIVE</span>' : '' ?>
        </a>
        <a href="session_term?quick_term=Second+Term" class="btn btn-lg <?= ($show_current_term === 'Second Term') ? 'btn-success' : 'btn-default' ?>" style="font-weight:700;">
            <i class="fa <?= ($show_current_term === 'Second Term') ? 'fa-check-circle' : 'fa-circle' ?>"></i> Second Term
            <?= ($show_current_term === 'Second Term') ? ' <span class="badge" style="background:#fff; color:#27ae60; margin-left:5px;">ACTIVE</span>' : '' ?>
        </a>
        <a href="session_term?quick_term=Third+Term" class="btn btn-lg <?= ($show_current_term === 'Third Term') ? 'btn-success' : 'btn-default' ?>" style="font-weight:700; border-radius:0 8px 8px 0;">
            <i class="fa <?= ($show_current_term === 'Third Term') ? 'fa-check-circle' : 'fa-circle' ?>"></i> Third Term
            <?= ($show_current_term === 'Third Term') ? ' <span class="badge" style="background:#fff; color:#27ae60; margin-left:5px;">ACTIVE</span>' : '' ?>
        </a>
    </div>
</div>

<div class="row">
    <!-- Left Column: Term & Session Selection -->
    <div class="col-md-6">
        <div class="panel panel-default" style="border-radius:10px; box-shadow:0 2px 8px rgba(0,0,0,0.05);">
            <div class="panel-heading" style="background:#f8f9fa; font-weight:700;">
                <i class="fa fa-cog text-primary"></i> Academic Year & Term Settings
            </div>
            <div class="panel-body" style="padding:20px;">
                <!-- Change Term Form -->
                <form method="POST" action="">
                    <div class="form-group">
                        <label><b>Select Academic Term:</b></label>
                        <div class="input-group">
                            <select name="current_term" class="form-control" style="border-radius:6px 0 0 6px;" required>
                                <option value="First Term" <?= ($show_current_term === 'First Term') ? 'selected' : '' ?>>First Term</option>
                                <option value="Second Term" <?= ($show_current_term === 'Second Term') ? 'selected' : '' ?>>Second Term</option>
                                <option value="Third Term" <?= ($show_current_term === 'Third Term') ? 'selected' : '' ?>>Third Term</option>
                            </select>
                            <span class="input-group-btn">
                                <button name="current_term_btn" type="submit" class="btn btn-primary" style="font-weight:600; border-radius:0 6px 6px 0;">
                                    <i class="fa fa-save"></i> Save Term
                                </button>
                            </span>
                        </div>
                    </div>
                </form>

                <hr style="margin:20px 0;">

                <!-- Change Session Form -->
                <form method="POST" action="">
                    <div class="form-group">
                        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:5px;">
                            <label style="margin:0;"><b>Select Academic Session:</b></label>
                            <button type="button" class="btn btn-xs btn-success" data-toggle="modal" data-target="#addSessionModal">
                                <i class="fa fa-plus"></i> Add New Session
                            </button>
                        </div>
                        <div class="input-group">
                            <select name="current_session" class="form-control" style="border-radius:6px 0 0 6px;" required>
                                <?php foreach ($registered_sessions as $s): ?>
                                    <option value="<?= htmlspecialchars($s['sessions']) ?>" <?= ($show_current_session === $s['sessions']) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($s['sessions']) ?> <?= ($show_current_session === $s['sessions']) ? ' (Active)' : '' ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <span class="input-group-btn">
                                <button name="current_session_btn" type="submit" class="btn btn-primary" style="font-weight:600; border-radius:0 6px 6px 0;">
                                    <i class="fa fa-save"></i> Save Session
                                </button>
                            </span>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Right Column: Resumption and Closing Dates -->
    <div class="col-md-6">
        <div class="panel panel-default" style="border-radius:10px; box-shadow:0 2px 8px rgba(0,0,0,0.05);">
            <div class="panel-heading" style="background:#f8f9fa; font-weight:700;">
                <i class="fa fa-calendar-check text-danger"></i> Term Resumption & Closing Calendar
            </div>
            <div class="panel-body" style="padding:20px;">
                <form method="POST" action="">
                    <div class="form-group">
                        <label><b>Current Term Closing Date:</b></label>
                        <input name="term_end_date" type="date" class="form-control" value="<?= htmlspecialchars($show_term_end) ?>" required>
                        <p class="help-block small text-muted">The official date when the current term vacates.</p>
                    </div>

                    <div class="form-group">
                        <label><b>Next Term Resumption Date:</b></label>
                        <input name="next_term_date" type="date" class="form-control" value="<?= htmlspecialchars($show_next_term) ?>" required>
                        <p class="help-block small text-muted">Printed on student report cards and invoices as the resumption date.</p>
                    </div>

                    <button name="result_date_btn" type="submit" class="btn btn-primary btn-block" style="font-weight:700; border-radius:6px; margin-top:15px;">
                        <i class="fa fa-calendar-alt"></i> Save Term Dates
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Registered Sessions Table -->
<div class="panel panel-default" style="border-radius:10px; margin-top:10px; box-shadow:0 2px 8px rgba(0,0,0,0.05);">
    <div class="panel-heading" style="background:#f8f9fa; display:flex; justify-content:space-between; align-items:center;">
        <span style="font-weight:700;"><i class="fa fa-list text-info"></i> Registered Academic Sessions</span>
        <button type="button" class="btn btn-sm btn-success" data-toggle="modal" data-target="#addSessionModal">
            <i class="fa fa-plus-circle"></i> Add New Session
        </button>
    </div>
    <div class="panel-body" style="padding:0;">
        <div class="table-responsive">
            <table class="table table-hover table-striped" style="margin-bottom:0;">
                <thead>
                    <tr style="background:#f1f5f9;">
                        <th style="width:60px;">#</th>
                        <th>Academic Session</th>
                        <th>Date Registered</th>
                        <th>Status</th>
                        <th class="text-right">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($registered_sessions)): ?>
                        <?php foreach ($registered_sessions as $idx => $s): ?>
                            <tr>
                                <td><?= $idx + 1 ?></td>
                                <td><b><?= htmlspecialchars($s['sessions']) ?></b></td>
                                <td><?= htmlspecialchars($s['date_added'] ?? 'N/A') ?></td>
                                <td>
                                    <?php if ($show_current_session === $s['sessions']): ?>
                                        <span class="badge" style="background:#10b981; padding:5px 10px; font-size:11px;">Active Session</span>
                                    <?php else: ?>
                                        <span class="badge" style="background:#94a3b8; padding:5px 10px; font-size:11px;">Inactive</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-right">
                                    <?php if ($show_current_session !== $s['sessions']): ?>
                                        <a href="session_term?quick_session=<?= urlencode($s['sessions']) ?>" class="btn btn-xs btn-primary" style="border-radius:4px;" onclick="return confirm('Switch active session to <?= htmlspecialchars($s['sessions']) ?>?')">
                                            <i class="fa fa-check"></i> Make Active
                                        </a>
                                    <?php else: ?>
                                        <span class="text-success small"><i class="fa fa-check-circle"></i> Currently Active</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="5" class="text-center text-muted">No academic sessions found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add Session Modal -->
<div class="modal fade" id="addSessionModal" tabindex="-1" role="dialog" aria-labelledby="addSessionModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <form method="POST" action="">
            <div class="modal-content" style="border-radius:10px;">
                <div class="modal-header" style="background:#1e3c72; color:#fff; border-radius:10px 10px 0 0;">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close" style="color:#fff;">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title" id="addSessionModalLabel"><i class="fa fa-plus-circle"></i> Add New Academic Session</h4>
                </div>
                <div class="modal-body" style="padding:20px;">
                    <div class="form-group">
                        <label for="add_session"><b>Enter Academic Session:</b></label>
                        <input type="text" name="add_session" class="form-control input-lg" id="add_session" required placeholder="e.g. 2025/2026, 2026/2027">
                        <p class="help-block small text-muted">Follow standard academic year format (e.g. <code>2025/2026</code>).</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button type="submit" name="add_session_btn" class="btn btn-primary" style="font-weight:700;"><i class="fa fa-save"></i> Save Session</button>
                </div>
            </div>
        </form>
    </div>
</div>
