<?php

session_name('mini_admin_session');

session_start();

error_reporting(0);

include('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'];
include('includes/flash.php');





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

    header('location:logoutmini.php');

    exit();

}



// Fetch the current session

$currentSessionQuery = "SELECT id, session_name 

                        FROM school_sessions 

                        WHERE start_date <= CURDATE() 

                          AND end_date >= CURDATE() 

                        ORDER BY start_date ASC 

                        LIMIT 1";

$currentSessionResult = $con->query($currentSessionQuery);



if ($currentSessionResult && $currentSessionResult->num_rows > 0) {

    $currentSession = $currentSessionResult->fetch_assoc();

    $currentSessionId = $currentSession['id'];

    $currentSessionName = $currentSession['session_name'];

} else {

    $currentSessionId = null;

    $currentSessionName = null;

}



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

    mysqli_begin_transaction($con);



    try {

        // ✅ Step 1: Graduate students in terminal classes

        $terminal_query = mysqli_query($con, "SELECT DISTINCT class FROM class_section WHERE terminal = 1");

        $terminal_classes = [];



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

            $terminal_class = $row['class'];

            $terminal_classes[] = $terminal_class;



            // Graduate students in terminal classes

            $graduate_sql = "UPDATE students SET status = 3, graduated_session = '$currentSessionName' WHERE class = '$terminal_class' AND status = 1";

            if (!mysqli_query($con, $graduate_sql)) {

                throw new Exception("Error graduating students from class $terminal_class.");

            }

        }



        // ✅ Step 2: Get all classes (including terminal)

        $classes_query = mysqli_query($con, "SELECT DISTINCT class FROM class_section");

        $classes = [];



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

            $classes[] = $row['class'];

        }



        // Sort all class names in natural order (e.g., Primary 1 → Primary 2, SS 1 → SS 2)

        function naturalSort($a, $b)

        {

            return strnatcasecmp($a, $b);

        }

        usort($classes, "naturalSort");



        // ✅ Build class promotion map excluding terminal classes

        $class_map = [];

        for ($i = 0; $i < count($classes) - 1; $i++) {

            $current = $classes[$i];

            $next = $classes[$i + 1];



            // Only include in promotion if current is NOT a terminal class

            if (!in_array($current, $terminal_classes)) {

                $class_map[$current] = $next;

            }

        }



        // ✅ Generate promotion CASE SQL

        $case_sql = "UPDATE students SET 

    class = CASE";

        foreach ($class_map as $current_class => $next_class) {

            $case_sql .= " WHEN class = '$current_class' THEN '$next_class'";

        }

        $case_sql .= " ELSE class END, 

    demote_status = 0 

    WHERE status = 1";

        // ✅ Execute promotion

        if (!mysqli_query($con, $case_sql)) {

            throw new Exception("Error promoting students.");

        }



        // ✅ Commit transaction

        mysqli_commit($con);

        flash_alert('Students promoted and terminal class students graduated successfully!', 'promote_students.php');
        header('Location: promote_students.php'); exit;

    } catch (Exception $e) {

        mysqli_rollback($con);

        flash_alert('Error: ' . $e->getMessage());

    }

}

?>



<!DOCTYPE html>

<html>

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



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

    <div class="wrapper">

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

        <?php @include("includes/sidebar2.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-user-graduate"></i>

                        </div>

                        <div>

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

                            Student Information Management

                                <span class="premium-subtitle text-secondary">Manage Promotion</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="dashboard1.php" class="text-primary">Home</a></li>

                            <li class="breadcrumb-item active" aria-current="page">Promote Student</li>

                        </ol>

                    </nav>

                </div>

            </div>

        </div>

    </div>

</section>  



            <section class="content">

                <div class="container-fluid">

                    <div class="row">

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

                            <div class="card card-primary">

                                <div class="card-header">

                                    <h5 class="card-title"><i class="fas fa-medal"></i> Promote Students</h5>

                                </div>

                                <form id="promotionForm" role="form" method="POST">

                                    <div class="card-body">

                                        <p style="color: red;">Click the button below to promote students automatically.</p>

                                        <p style="color: red;">N:B:- Your action cannot be undone once you click on promote students.</p>

                                    </div>

                                    <div class="card-footer">

                                        <center>

                                            <button type="button" onclick="confirmPromotion()" class="btn btn-primary">

                                                <i class="fas fa-medal"></i> Promote Students

                                            </button>

                                        </center>

                                    </div>

                                    <input type="hidden" name="confirm_promotion" value="1">

                                </form>

                            </div>

                        </div>

                    </div>

                </div>

            </section>

        </div>

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

    </div>

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



    <script>

        function confirmPromotion() {

            if (confirm('Are you sure you want to promote students? This action cannot be undone.')) {

                document.getElementById("promotionForm").submit();

            }

        }

    </script>

</body>



</html>