<?php

session_name('mini_admin_session');

session_start();

error_reporting(0);

include('includes/dbconnection.php');

require_once __DIR__ . '/includes/session_term_helper.php';

$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName = $stResult['term_name'];

if (strlen($_SESSION['sid'] == 0)) {

    header('location:logoutmini.php');

}



function fetchCurrentSessionTerm($con)
{

    $st = resolveCurrentSessionTerm($con);

    return [$st['session_id'], $st['term_id']];

}



function getAllTeachersWithSubmissionStatus($con, $class, $section, $session_id, $term_id, $result_type)
{

    // Choose table depending on result_type

    $results_table = ($result_type === 'mid_term') ? 'result2' : 'results';



    // Build conditions

    $conditions = "

        ((r.test_score IS NOT NULL AND (r.test_score != '' OR r.test_score = 0)) OR r.test_absent = 1) 

        AND ((r.class_performance IS NOT NULL AND (r.class_performance != '' OR r.class_performance = 0)) OR r.class_performance_absent = 1) 

        AND ((r.weekly_assessment IS NOT NULL AND (r.weekly_assessment != '' OR r.weekly_assessment = 0)) OR r.weekly_assessment_absent = 1)

    ";



    // Always sanitize $result_type if it comes from user input

    $result_type = trim($result_type);



    // Mid-term condition (test2 must be recorded OR student absent)

    if ($result_type === 'mid_term') {

        // Use IS NOT NULL and != '' consistently

        $conditions .= "

            AND (

                (r.test_score2 IS NOT NULL AND (r.test_score2 != '' OR r.test_score2 = 0))

                OR r.test2_absent = 1

            )

        ";



    }



    // Full-term or any non-mid-term condition (exam must be recorded OR student absent)
    else {

        $conditions .= "

        AND (

            (r.exam_score IS NOT NULL AND r.exam_score != '' OR r.exam_score = 0)

            OR r.exam_absent = 1

        )

    ";

    }





    $query = "

        SELECT 

            ta.teacher_id, 

            CONCAT(t.name, ' ', t.lastname) AS teacher_name, 

            sub.subject_name,

            (

                SELECT COUNT(*) 

                FROM subject_allocations sa 

                INNER JOIN students s ON s.id = sa.student_id

                WHERE sa.class = '$class' 

                  AND sa.section = '$section'

                  AND sa.subject_name = sub.subject_name

                  AND s.status < 3

            ) AS total_offering,

            (

                SELECT COUNT(*) 

                FROM $results_table r

                WHERE r.class = '$class' 

                  AND r.section = '$section' 

                  AND r.session_id = $session_id 

                  AND r.term_id = $term_id 

                  AND r.teacher_id = ta.teacher_id 

                  AND r.subject = sub.subject_name

                  AND $conditions

            ) AS submitted_count

        FROM teacher_assignments ta

        JOIN tblusers t ON ta.teacher_id = t.id

        JOIN subjectcombination sub ON ta.subject_id = sub.id

        JOIN class_section cs ON sub.class = cs.class AND sub.section = cs.section

        WHERE cs.class = '$class' 

          AND cs.section = '$section'

          AND ta.subject_id IS NOT NULL

    ";



    $result = mysqli_query($con, $query);

    $all = [];



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

        $row['remaining'] = $row['total_offering'] - $row['submitted_count'];



        if ((int) $row['submitted_count'] === 0) {

            $row['status'] = 'not_submitted';

        } elseif ((int) $row['submitted_count'] === (int) $row['total_offering']) {

            $row['status'] = 'submitted';

        } else {

            $row['status'] = 'pending';

        }



        $all[] = $row;

    }



    return $all;

}







// Handle form selection

$selected_class = $_GET['class'] ?? '';

$selected_section = $_GET['section'] ?? '';

$result_type = $_GET['result_type'] ?? '';

$teachers = [];



if ($selected_class && $selected_section && $result_type) {

    list($session_id, $term_id) = fetchCurrentSessionTerm($con);

    $teachers = getAllTeachersWithSubmissionStatus($con, $selected_class, $selected_section, $session_id, $term_id, $result_type);

}

?>

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

                                    </div>

                                    <div>

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

                                            Result Submission Monitoring

                                            <span class="premium-subtitle text-secondary">Track Submission Status</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">Result Status</li>

                                    </ol>

                                </nav>

                            </div>

                        </div>

                    </div>

                </div>

            </section>



            <section class="content">

                <div class="card card-primary card-outline">

                    <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">

                        <h5 class="card-title m-0">

                            <i class="fas fa-file-signature"></i> Result Submission Status - <?= date('l, F j, Y'); ?>

                            <?php if ($teachers): ?>

                                <span class="badge badge-secondary ml-2"><?= count($teachers) ?> Teachers</span>

                            <?php endif; ?>

                        </h5>

                    </div>

                    <div class="card-body">



                        <?php if (isset($_SESSION['msg'])): ?>

                            <div id="sessionAlert"
                                class="alert <?= $_SESSION['msg_type'] ?? 'alert-info' ?> alert-dismissible fade show"
                                role="alert">

                                <?= $_SESSION['msg'];

                                unset($_SESSION['msg']); ?>

                                <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
                                        aria-hidden="true">&times;</span></button>

                            </div>

                        <?php endif; ?>



                        <form method="GET">

                            <div class="row p-0 m-0">

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

                                    <label for="class">Class</label>

                                    <select name="class" class="form-control select2" required>

                                        <option value="">Select Class</option>

                                        <?php

                                        $res = mysqli_query($con, "SELECT DISTINCT class FROM class_section ORDER BY class");

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

                                            $selected = ($row['class'] == $selected_class) ? 'selected' : '';

                                            echo "<option $selected>{$row['class']}</option>";

                                        }

                                        ?>

                                    </select>

                                </div>

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

                                    <label for="section">Arm</label>

                                    <select name="section" class="form-control select2" required>

                                        <option value="">Select Arm</option>

                                        <?php

                                        $res = mysqli_query($con, "SELECT DISTINCT section FROM class_section ORDER BY section");

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

                                            $selected = ($row['section'] == $selected_section) ? 'selected' : '';

                                            echo "<option $selected>{$row['section']}</option>";

                                        }

                                        ?>

                                    </select>

                                </div>

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

                                    <label for="result_type">Result Type</label>

                                    <select name="result_type" class="form-control select2" required>

                                        <option value="">Select Type</option>

                                        <option value="mid_term" <?= $result_type == 'mid_term' ? 'selected' : '' ?>>Mid

                                            Term</option>

                                        <option value="end_term" <?= $result_type == 'end_term' ? 'selected' : '' ?>>End of

                                            Term</option>

                                    </select>

                                </div>

                                <div class="form-group col-md-12 text-center">

                                    <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i>

                                        Check</button>

                                </div>

                            </div>

                        </form>



                        <?php if ($teachers): ?>

                            <div class="table-responsive">

                                <form method="POST" action="send_bulk_notifications.php">

                                    <input type="hidden" name="class" value="<?= htmlspecialchars($selected_class) ?>">

                                    <input type="hidden" name="section" value="<?= htmlspecialchars($selected_section) ?>">

                                    <input type="hidden" name="triggered_by" value="admin">



                                    <table class="table table-bordered">

                                        <thead class="thead-light">

                                            <tr>

                                                <th>Teacher</th>

                                                <th>Subject</th>

                                                <th>Total Offering</th>

                                                <th>Submitted</th>

                                                <th>Remaining</th>

                                                <th>Status</th>

                                                <!-- <th>Action</th> -->

                                            </tr>

                                        </thead>

                                        <tbody>

                                            <?php foreach ($teachers as $teacher): ?>

                                                <tr>

                                                    <td><?= $teacher['teacher_name'] ?></td>

                                                    <td><?= $teacher['subject_name'] ?></td>

                                                    <td><?= $teacher['total_offering'] ?></td>

                                                    <td><?= $teacher['submitted_count'] ?></td>

                                                    <td><?= $teacher['remaining'] ?></td>

                                                    <td>

                                                        <?php if ($teacher['status'] === 'submitted'): ?>

                                                            <span class="badge badge-success">Submitted</span>

                                                        <?php elseif ($teacher['status'] === 'pending'): ?>

                                                            <span class="badge badge-warning">Pending</span>

                                                        <?php else: ?>

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

                                                        <?php endif; ?>

                                                    </td>

                                                    <!-- <td>

                    <?php if ($teacher['status'] !== 'submitted'): ?>

                        <form method="POST" action="send_bulk_notifications.php" class="d-inline">

                            <input type="hidden" name="class" value="<?= htmlspecialchars($selected_class) ?>">

                            <input type="hidden" name="section" value="<?= htmlspecialchars($selected_section) ?>">

                            <input type="hidden" name="teachers[]" value="<?= $teacher['teacher_id'] ?>">

                            <input type="hidden" name="triggered_by" value="admin">

                            <button type="submit" class="btn btn-warning btn-sm" title="Send Reminder">

                                <i class="fas fa-bell"></i> Remind

                            </button>

                        </form>

                    <?php else: ?>

                        <i class="text-muted">—</i>

                    <?php endif; ?>

                </td> -->

                                                </tr>

                                            <?php endforeach; ?>

                                        </tbody>

                                    </table>



                                    <?php

                                    $unsubmitted = array_filter($teachers, fn($t) => $t['status'] !== 'submitted');

                                    if (count($unsubmitted) > 0):

                                        ?>

                                        <?php foreach ($unsubmitted as $u): ?>

                                            <input type="hidden" name="teachers[]" value="<?= $u['teacher_id'] ?>">

                                        <?php endforeach; ?>

                                        <!-- <div class="text-center">

            <button type="submit" class="btn btn-danger mt-3">

                <i class="fas fa-paper-plane"></i> Send Bulk Reminder to  //count($unsubmitted) Teacher(s)

            </button>

        </div> -->

                                    <?php endif; ?>

                                </form>

                            </div>

                        <?php elseif ($selected_class && $selected_section && $result_type): ?>

                            <div class="alert alert-info mt-3">

                                <i class="fas fa-info-circle"></i>

                                No teachers found for this class/arm.

                            </div>

                        <?php endif; ?>

                    </div>

                </div>

            </section>

        </div>

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



    </div>



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

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

    <script>

        $(document).ready(function () {

            $('.select2').select2();

            setTimeout(function () {

                $("#sessionAlert").fadeTo(500, 0).slideUp(500, function () {

                    $(this).remove();

                });

            }, 5000);

        });

    </script>

</body>



</html>