<?php

$pageTitle = "CDS Attendance Management";

require_once '../includes/auth.php';

require_login();

$user = current_user();

/*
|--------------------------------------------------------------------------
| Allow only Administrator and LGI
|--------------------------------------------------------------------------
*/

if (!isset($user['role']) || !in_array($user['role'], ['Administrator', 'LGI'])) {
    $_SESSION['error'] = "You are not authorized to access CDS Attendance Management.";
    header("Location: index.php");
    exit;
}

/*
|--------------------------------------------------------------------------
| Get all active CDS groups
|--------------------------------------------------------------------------
*/

$groupStmt = $db->prepare("
    SELECT
        cg.id,
        cg.group_name,
        cg.group_code,
        cg.meeting_day,
        cg.meeting_time,
        cg.meeting_venue,
        cg.status,

        COUNT(DISTINCT CASE
            WHEN cgm.status = 'Active' THEN cgm.corps_member_id
        END) AS total_members

    FROM cds_groups cg

    LEFT JOIN cds_group_members cgm
        ON cgm.cds_group_id = cg.id

    WHERE cg.status = 'Active'

    GROUP BY
        cg.id,
        cg.group_name,
        cg.group_code,
        cg.meeting_day,
        cg.meeting_time,
        cg.meeting_venue,
        cg.status

    ORDER BY cg.group_name ASC
");

$groupStmt->execute();

$cdsGroups = $groupStmt->fetchAll(PDO::FETCH_ASSOC);


/*
|--------------------------------------------------------------------------
| Get attendance sessions
|--------------------------------------------------------------------------
*/

$sessionStmt = $db->prepare("
    SELECT
        qas.id,
        qas.cds_group_id,
        qas.session_token,
        qas.session_date,
        qas.valid_from,
        qas.valid_until,
        qas.status,
        qas.generated_by,
        qas.created_at,

        cg.group_name,
        cg.group_code,
        cg.meeting_day,
        cg.meeting_time,
        cg.meeting_venue,

        u.firstname AS creator_firstname,
        u.lastname AS creator_lastname,

        (
            SELECT COUNT(*)
            FROM cds_attendance ca
            WHERE ca.cds_group_id = qas.cds_group_id
            AND ca.attendance_date = qas.session_date
            AND ca.attendance_status = 'Present'
        ) AS total_present

    FROM qr_attendance_sessions qas

    INNER JOIN cds_groups cg
        ON cg.id = qas.cds_group_id

    LEFT JOIN users u
        ON u.id = qas.generated_by

    ORDER BY
        qas.session_date DESC,
        qas.created_at DESC
");

$sessionStmt->execute();

$attendanceSessions = $sessionStmt->fetchAll(PDO::FETCH_ASSOC);


require_once '../includes/header.php';
require_once '../includes/sidebar.php';

?>

<div class="overlay bg-black bg-opacity-50 w-100 h-100 position-fixed z-9 visibility-hidden opacity-0 duration-300">
</div>

<main class="dashboard-main">

    <?php require_once '../includes/topbar.php'; ?>

    <div class="dashboard-main-body">

        <!-- Breadcrumb -->
        <div class="breadcrumb d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">

            <div>
                <h6 class="fw-semibold mb-0">
                    <?= htmlspecialchars($pageTitle) ?>
                </h6>

                <p class="text-neutral-600 mt-4 mb-0">
                    <?= APP_SHORT_NAME ?> > <?= htmlspecialchars($pageTitle) ?>
                </p>
            </div>

            <button type="button" class="btn btn-primary-600 radius-8 px-20 py-11" data-bs-toggle="modal"
                data-bs-target="#createAttendanceSessionModal">

                <i class="ri-add-line me-1"></i>

                Create Attendance Session

            </button>

        </div>


        <!-- Success Message -->

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

        <div class="alert alert-success alert-dismissible fade show">

            <?= htmlspecialchars($_SESSION['success']) ?>

            <button type="button" class="btn-close" data-bs-dismiss="alert">
            </button>

        </div>

        <?php unset($_SESSION['success']); ?>

        <?php endif; ?>


        <!-- Error Message -->

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

        <div class="alert alert-danger alert-dismissible fade show">

            <?= htmlspecialchars($_SESSION['error']) ?>

            <button type="button" class="btn-close" data-bs-dismiss="alert">
            </button>

        </div>

        <?php unset($_SESSION['error']); ?>

        <?php endif; ?>


        <!-- Attendance Sessions Card -->

        <div class="card basic-data-table">

            <div class="card-header">

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

                    CDS Attendance Sessions

                </h5>

            </div>


            <div class="card-body">

                <div class="table-responsive">

                    <table class="table bordered-table mb-0">

                        <thead>

                            <tr>

                                <th>S/N</th>

                                <th>CDS Group</th>

                                <th>Group Code</th>

                                <th>Date</th>

                                <th>Valid From</th>

                                <th>Valid Until</th>

                                <th>Present</th>

                                <th>Status</th>

                                <th>Action</th>

                            </tr>

                        </thead>


                        <tbody>

                            <?php if (!empty($attendanceSessions)): ?>

                            <?php foreach ($attendanceSessions as $index => $session): ?>

                            <?php

                                /*
                                |--------------------------------------------------------------------------
                                | Calculate the real display status
                                |--------------------------------------------------------------------------
                                */

                                $now = time();

                                $validFrom = strtotime($session['valid_from']);

                                $validUntil = strtotime($session['valid_until']);

                                $displayStatus = $session['status'];

                                if (
                                    $session['status'] === 'Active'
                                    && $now > $validUntil
                                ) {
                                    $displayStatus = 'Expired';
                                }

                                ?>

                            <tr>

                                <td>
                                    <?= $index + 1 ?>
                                </td>


                                <td>

                                    <strong>

                                        <?= htmlspecialchars($session['group_name']) ?>

                                    </strong>

                                </td>


                                <td>

                                    <?= htmlspecialchars($session['group_code']) ?>

                                </td>


                                <td>

                                    <?= date(
                                            'd M Y',
                                            strtotime($session['session_date'])
                                        ) ?>

                                </td>


                                <td>

                                    <?= date(
                                            'd M Y h:i A',
                                            strtotime($session['valid_from'])
                                        ) ?>

                                </td>


                                <td>

                                    <?= date(
                                            'd M Y h:i A',
                                            strtotime($session['valid_until'])
                                        ) ?>

                                </td>


                                <td>

                                    <span class="badge bg-success-100 text-success-600">

                                        <?= (int) $session['total_present'] ?>

                                    </span>

                                </td>


                                <td>

                                    <?php if ($displayStatus === 'Active'): ?>

                                    <span class="badge bg-success-100 text-success-600">

                                        Active

                                    </span>


                                    <?php elseif ($displayStatus === 'Closed'): ?>

                                    <span class="badge bg-danger-100 text-danger-600">

                                        Closed

                                    </span>


                                    <?php else: ?>

                                    <span class="badge bg-neutral-200 text-neutral-600">

                                        Expired

                                    </span>

                                    <?php endif; ?>

                                </td>


                                <td>

                                    <?php if (
                                            $session['status'] === 'Active'
                                            && $now <= $validUntil
                                        ): ?>
                                    <form method="POST" action="../actions/close_cds_attendance_session.php"
                                        class="d-inline" onsubmit="return confirmCloseAttendanceSession();">

                                        <input type="hidden" name="session_id" value="<?= (int) $session['id'] ?>">

                                        <button type="submit" class="btn btn-danger-600 btn-sm">

                                            Close Session

                                        </button>

                                    </form>

                                    <?php else: ?>

                                    <span class="text-secondary-light">

                                        No Action

                                    </span>

                                    <?php endif; ?>

                                </td>

                            </tr>

                            <?php endforeach; ?>


                            <?php else: ?>

                            <tr>

                                <td colspan="9" class="text-center py-5">

                                    <i class="ri-calendar-close-line text-xxl"></i>

                                    <p class="mt-2 mb-0">

                                        No attendance sessions have been created.

                                    </p>

                                </td>

                            </tr>

                            <?php endif; ?>

                        </tbody>

                    </table>
                    <script>
                    function confirmCloseAttendanceSession() {

                        return confirm(
                            'Are you sure you want to close this attendance session?\n\n' +
                            'All active corps members in this CDS group who did not mark attendance will automatically be recorded as Absent.\n\n' +
                            'This action cannot be undone automatically.'
                        );

                    }
                    </script>

                </div>

            </div>

        </div>

    </div>

</main>


<!-- =========================================================
CREATE ATTENDANCE SESSION MODAL
========================================================= -->

<div class="modal fade" id="createAttendanceSessionModal" tabindex="-1" aria-hidden="true">

    <div class="modal-dialog modal-dialog-centered">

        <div class="modal-content radius-16 bg-base">


            <div class="modal-header py-16 px-24 border-bottom">

                <h5 class="modal-title">

                    Create CDS Attendance Session

                </h5>

                <button type="button" class="btn-close" data-bs-dismiss="modal">
                </button>

            </div>


            <form method="POST" action="../actions/create_cds_attendance_session.php">


                <div class="modal-body p-24">


                    <!-- CDS GROUP -->

                    <div class="mb-20">

                        <label class="form-label fw-semibold">

                            CDS Group

                        </label>

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

                            <option value="">

                                Select CDS Group

                            </option>


                            <?php foreach ($cdsGroups as $group): ?>

                            <option value="<?= (int) $group['id'] ?>">

                                <?= htmlspecialchars($group['group_name']) ?>

                                (<?= htmlspecialchars($group['group_code']) ?>)

                            </option>

                            <?php endforeach; ?>

                        </select>

                    </div>


                    <!-- SESSION DATE -->

                    <div class="mb-20">

                        <label class="form-label fw-semibold">

                            Session Date

                        </label>

                        <input type="date" name="session_date" class="form-control" value="<?= date('Y-m-d') ?>"
                            required>

                    </div>


                    <!-- START TIME -->

                    <div class="mb-20">

                        <label class="form-label fw-semibold">

                            Attendance Opening Time

                        </label>

                        <input type="time" name="start_time" class="form-control" required>

                    </div>


                    <!-- END TIME -->

                    <div class="mb-20">

                        <label class="form-label fw-semibold">

                            Attendance Closing Time

                        </label>

                        <input type="time" name="end_time" class="form-control" required>

                    </div>


                    <div class="alert alert-info">

                        Corps members will only be able to mark attendance
                        between the opening and closing time.

                    </div>

                </div>


                <div class="modal-footer">

                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">

                        Cancel

                    </button>


                    <button type="submit" class="btn btn-primary-600">

                        Create Session

                    </button>

                </div>


            </form>

        </div>

    </div>

</div>


<?php require_once '../includes/footer.php'; ?>