<?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');
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 (!isset($_SESSION['sid'])) {

    header('location:logout.php');

    exit();

}

// Fetch all classes + arms

$classes = [];

$classRes = $con->query("SELECT class, section FROM class_section ORDER BY class, section");

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

    $classes[] = $row;

}



// For each class/arm, check approval statuses & counts

$approvalData = [];

foreach ($classes as $c) {

    $class = $c['class'];

    $section = $c['section'];



    // ---- MIDTERM ----

    $midExpectedQuery = "

        SELECT COUNT(*) AS expected_rows

        FROM result2

        WHERE class=? AND section=? AND session_id=? AND term_id=?";

    $midExpStmt = $con->prepare($midExpectedQuery);

    $midExpStmt->bind_param("ssii", $class, $section, $currentSessionId, $currentTermId);

    $midExpStmt->execute();

    $midExpected = $midExpStmt->get_result()->fetch_assoc()['expected_rows'] ?? 0;



    // Midterm Approved

    $midApprovedQuery = "

        SELECT COUNT(*) AS approved_rows

        FROM result2

        WHERE class=? AND section=? AND session_id=? AND term_id=? AND status_test='Approved'";

    $midAppStmt = $con->prepare($midApprovedQuery);

    $midAppStmt->bind_param("ssii", $class, $section, $currentSessionId, $currentTermId);

    $midAppStmt->execute();

    $midApproved = $midAppStmt->get_result()->fetch_assoc()['approved_rows'] ?? 0;



    // Midterm Submitted to Admin

    $midSubmittedQuery = "

        SELECT COUNT(*) AS submitted_rows

        FROM result2

        WHERE class=? AND section=? AND session_id=? AND term_id=? AND status_test IN ('Submitted to Admin', 'Approved')";

    $midSubStmt = $con->prepare($midSubmittedQuery);

    $midSubStmt->bind_param("ssii", $class, $section, $currentSessionId, $currentTermId);

    $midSubStmt->execute();

    $midSubmitted = $midSubStmt->get_result()->fetch_assoc()['submitted_rows'] ?? 0;



    // ---- ENDTERM ----

    $endExpectedQuery = "

        SELECT COUNT(*) AS expected_rows

        FROM results

        WHERE class=? AND section=? AND session_id=? AND term_id=?";

    $endExpStmt = $con->prepare($endExpectedQuery);

    $endExpStmt->bind_param("ssii", $class, $section, $currentSessionId, $currentTermId);

    $endExpStmt->execute();

    $endExpected = $endExpStmt->get_result()->fetch_assoc()['expected_rows'] ?? 0;



    // Endterm Approved

    $endApprovedQuery = "

        SELECT COUNT(*) AS approved_rows

        FROM results

        WHERE class=? AND section=? AND session_id=? AND term_id=? AND status='Approved'";

    $endAppStmt = $con->prepare($endApprovedQuery);

    $endAppStmt->bind_param("ssii", $class, $section, $currentSessionId, $currentTermId);

    $endAppStmt->execute();

    $endApproved = $endAppStmt->get_result()->fetch_assoc()['approved_rows'] ?? 0;



    // Endterm Submitted to Admin

    $endSubmittedQuery = "

        SELECT COUNT(*) AS submitted_rows

        FROM results

        WHERE class=? AND section=? AND session_id=? AND term_id=? AND status IN ('Submitted to Admin', 'Approved')";

    $endSubStmt = $con->prepare($endSubmittedQuery);

    $endSubStmt->bind_param("ssii", $class, $section, $currentSessionId, $currentTermId);

    $endSubStmt->execute();

    $endSubmitted = $endSubStmt->get_result()->fetch_assoc()['submitted_rows'] ?? 0;



    $approvalData[] = [

        'class' => $class,

        'section' => $section,

        'mid_expected' => $midExpected,

        'mid_approved' => $midApproved,

        'mid_submitted' => $midSubmitted,

        'end_expected' => $endExpected,

        'end_approved' => $endApproved,

        'end_submitted' => $endSubmitted,

    ];

}

?>



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

                                    </div>

                                    <div>

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

                                            Approval Tracking

                                            <span class="premium-subtitle text-secondary">Track Approval Status -
                                                <?= htmlspecialchars($currentTermName) ?>
                                                (<?= htmlspecialchars($currentSessionName) ?>)</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">Approval Tracking</li>

                                    </ol>

                                </nav>

                            </div>

                        </div>

                    </div>

                </div>

            </section>



            <section class="content">

                <div class="container-fluid">

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

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

                            <h3 class="card-title font-weight-bold"><i class="fas fa-clipboard-check"></i> Class
                                Approval Status</h3>

                        </div>

                        <div class="card-body">

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

                                <thead>

                                    <tr>

                                        <th>#</th>

                                        <th>Class - Arm</th>

                                        <th>Midterm (Submitted)</th>

                                        <th>Midterm (Approved)</th>

                                        <th>Midterm %</th>

                                        <th>Endterm (Submitted)</th>

                                        <th>Endterm (Approved)</th>

                                        <th>Endterm %</th>

                                    </tr>

                                </thead>

                                <tbody>

                                    <?php $sn = 1;
                                    foreach ($approvalData as $row): ?>

                                        <tr>

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

                                            <td><b><?= htmlspecialchars($row['class']) ?> -
                                                    <?= htmlspecialchars($row['section']) ?></b></td>



                                            <!-- Midterm Submitted -->

                                            <td>

                                                <?php if ($row['mid_submitted'] == 0): ?>

                                                    <span class="badge badge-secondary">Not Submitted</span>

                                                <?php else: ?>

                                                    <span class="badge badge-info">

                                                        Submitted (<?= $row['mid_submitted'] ?>/<?= $row['mid_expected'] ?>)

                                                    </span>

                                                <?php endif; ?>

                                            </td>

                                            <!-- Midterm Approved -->

                                            <!-- Midterm -->

                                            <td>

                                                <?php if ($row['mid_expected'] == 0): ?>

                                                    <span class="badge badge-secondary">Not Submitted</span>

                                                <?php elseif ($row['mid_approved'] == $row['mid_expected']): ?>

                                                    <span class="badge badge-success">

                                                        Approved (<?= $row['mid_approved'] ?>/<?= $row['mid_expected'] ?>)

                                                    </span>

                                                <?php else: ?>

                                                    <span class="badge badge-warning">

                                                        Pending (<?= $row['mid_approved'] ?>/<?= $row['mid_expected'] ?>)

                                                    </span>

                                                <?php endif; ?>

                                            </td>

                                            <td>

                                                <?php

                                                $midPercent = $row['mid_expected'] > 0

                                                    ? round(($row['mid_approved'] / $row['mid_expected']) * 100, 1)

                                                    : 0;

                                                echo $midPercent . '%';

                                                ?>

                                            </td>







                                            <!-- Endterm Submitted -->

                                            <td>

                                                <?php if ($row['end_submitted'] == 0): ?>

                                                    <span class="badge badge-secondary">Not Submitted</span>

                                                <?php else: ?>

                                                    <span class="badge badge-info">

                                                        Submitted (<?= $row['end_submitted'] ?>/<?= $row['end_expected'] ?>)

                                                    </span>

                                                <?php endif; ?>

                                            </td>

                                            <!-- Endterm Approved -->

                                            <!-- Endterm -->

                                            <td>

                                                <?php if ($row['end_expected'] == 0): ?>

                                                    <span class="badge badge-secondary">Not Submitted</span>

                                                <?php elseif ($row['end_approved'] == $row['end_expected']): ?>

                                                    <span class="badge badge-success">

                                                        Approved (<?= $row['end_approved'] ?>/<?= $row['end_expected'] ?>)

                                                    </span>

                                                <?php else: ?>

                                                    <span class="badge badge-warning">

                                                        Pending (<?= $row['end_approved'] ?>/<?= $row['end_expected'] ?>)

                                                    </span>

                                                <?php endif; ?>

                                            </td>

                                            <td>

                                                <?php

                                                $endPercent = $row['end_expected'] > 0

                                                    ? round(($row['end_approved'] / $row['end_expected']) * 100, 1)

                                                    : 0;

                                                echo $endPercent . '%';

                                                ?>

                                            </td>

                                        </tr>

                                    <?php endforeach; ?>

                                </tbody>

                            </table>



                            <?php if (empty($approvalData)): ?>

                                <p class="text-muted">No classes found.</p>

                            <?php endif; ?>

                        </div>

                    </div>

                </div>

            </section>

        </div>



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

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

    </div>

</body>

</html>