<?php

$pageTitle = "Monthly Clearance";

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

require_login();

$user = current_user();

/*
|--------------------------------------------------------------------------
| GET LOGGED-IN USER ID
|--------------------------------------------------------------------------
|
| Your existing system may store the logged-in user in either:
|
| $_SESSION['user']['id']
|
| OR
|
| $_SESSION['user_id']
|
| Since your current_user() function already returns the logged-in user,
| we use $user['id'] first.
|
*/

$userId = $user['id'] ?? $_SESSION['user_id'] ?? null;

if (!$userId) {
    header("Location: ../login.php");
    exit;
}


/*
|--------------------------------------------------------------------------
| GET LOGGED-IN CORPS MEMBER
|--------------------------------------------------------------------------
|
| users.id is connected to corps_members.user_id
|
*/

$corpsMemberStmt = $db->prepare("
    SELECT
        cm.*
    FROM corps_members cm
    WHERE cm.user_id = ?
    LIMIT 1
");

$corpsMemberStmt->execute([$userId]);

$corpsMember = $corpsMemberStmt->fetch(PDO::FETCH_ASSOC);


/*
|--------------------------------------------------------------------------
| CURRENT MONTH AND YEAR
|--------------------------------------------------------------------------
*/

$currentMonth = (int) date('n');
$currentYear  = (int) date('Y');

$currentMonthName = date('F');


/*
|--------------------------------------------------------------------------
| DEFAULT VALUES
|--------------------------------------------------------------------------
*/

$currentClearance = null;

$cdsStats = [
    'total' => 0,
    'present' => 0,
    'absent' => 0,
    'excused' => 0,
    'attendance_rate' => 0
];

$cdsAttendanceVerified = 'No';

$clearanceHistory = [];


/*
|--------------------------------------------------------------------------
| ONLY CONTINUE IF CORPS MEMBER PROFILE EXISTS
|--------------------------------------------------------------------------
*/

if ($corpsMember) {

    $corpsMemberId = $corpsMember['id'];


    /*
    |--------------------------------------------------------------------------
    | CHECK CURRENT MONTH CLEARANCE
    |--------------------------------------------------------------------------
    */

    $clearanceStmt = $db->prepare("
        SELECT
            mc.*,
            u.firstname AS approver_firstname,
            u.lastname AS approver_lastname
        FROM monthly_clearance mc
        LEFT JOIN users u
            ON u.id = mc.approved_by
        WHERE mc.corps_member_id = ?
        AND mc.clearance_month = ?
        AND mc.clearance_year = ?
        LIMIT 1
    ");

    $clearanceStmt->execute([
        $corpsMemberId,
        $currentMonth,
        $currentYear
    ]);

    $currentClearance = $clearanceStmt->fetch(PDO::FETCH_ASSOC);


    /*
    |--------------------------------------------------------------------------
    | GET CDS ATTENDANCE STATISTICS FOR CURRENT MONTH
    |--------------------------------------------------------------------------
    */

    $attendanceStmt = $db->prepare("
        SELECT
            attendance_status,
            COUNT(*) AS total
        FROM cds_attendance
        WHERE corps_member_id = ?
        AND MONTH(attendance_date) = ?
        AND YEAR(attendance_date) = ?
        GROUP BY attendance_status
    ");

    $attendanceStmt->execute([
        $corpsMemberId,
        $currentMonth,
        $currentYear
    ]);

    while ($row = $attendanceStmt->fetch(PDO::FETCH_ASSOC)) {

        $count = (int) $row['total'];

        $cdsStats['total'] += $count;

        switch ($row['attendance_status']) {

            case 'Present':
                $cdsStats['present'] = $count;
                break;

            case 'Absent':
                $cdsStats['absent'] = $count;
                break;

            case 'Excused':
                $cdsStats['excused'] = $count;
                break;
        }
    }


    /*
    |--------------------------------------------------------------------------
    | CALCULATE ATTENDANCE RATE
    |--------------------------------------------------------------------------
    |
    | Excused attendance is not counted as absent here.
    |
    | Attendance Rate =
    | Present / (Present + Absent) * 100
    |
    */

    $attendanceCountForRate =
        $cdsStats['present'] + $cdsStats['absent'];

    if ($attendanceCountForRate > 0) {

        $cdsStats['attendance_rate'] = round(
            ($cdsStats['present'] / $attendanceCountForRate) * 100,
            1
        );
    }


    /*
    |--------------------------------------------------------------------------
    | CDS ATTENDANCE VERIFICATION
    |--------------------------------------------------------------------------
    |
    | For now we require:
    |
    | 1. At least one CDS attendance record.
    | 2. Attendance rate of at least 75%.
    |
    | You can change 75 to another percentage later.
    |
    */

    if (
        $cdsStats['total'] > 0 &&
        $cdsStats['attendance_rate'] >= 75
    ) {

        $cdsAttendanceVerified = 'Yes';

    }


    /*
    |--------------------------------------------------------------------------
    | GET CLEARANCE HISTORY
    |--------------------------------------------------------------------------
    */

    $historyStmt = $db->prepare("
        SELECT
            mc.*,
            u.firstname AS approver_firstname,
            u.lastname AS approver_lastname
        FROM monthly_clearance mc
        LEFT JOIN users u
            ON u.id = mc.approved_by
        WHERE mc.corps_member_id = ?
        ORDER BY
            mc.clearance_year DESC,
            mc.clearance_month DESC
    ");

    $historyStmt->execute([$corpsMemberId]);

    $clearanceHistory = $historyStmt->fetchAll(PDO::FETCH_ASSOC);
}


/*
|--------------------------------------------------------------------------
| LOAD HEADER AND SIDEBAR
|--------------------------------------------------------------------------
*/

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 ?> > Monthly Clearance
                </p>

            </div>

        </div>


        <?php
        /*
        |--------------------------------------------------------------------------
        | DISPLAY FLASH MESSAGES
        |--------------------------------------------------------------------------
        */
        ?>

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

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

            <i class="ri-checkbox-circle-line me-2"></i>

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

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

        </div>

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

        <?php endif; ?>


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

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

            <i class="ri-error-warning-line me-2"></i>

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

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

        </div>

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

        <?php endif; ?>



        <?php if (!$corpsMember): ?>

        <!-- =========================================================
                 NO CORPS MEMBER PROFILE
            ========================================================== -->

        <div class="card">

            <div class="card-body p-40 text-center">

                <div class="mb-20">

                    <iconify-icon icon="mdi:account-alert-outline" width="80" class="text-danger">
                    </iconify-icon>

                </div>

                <h4 class="mb-8">
                    Corps Member Profile Not Found
                </h4>

                <p class="text-secondary-light mb-0">

                    Your user account is not linked to a corps member profile.

                </p>

            </div>

        </div>


        <?php else: ?>


        <!-- =========================================================
                 CLEARANCE SUMMARY CARDS
            ========================================================== -->

        <div class="row gy-4 mb-24">


            <!-- Current Month -->
            <div class="col-xxl-3 col-sm-6">

                <div class="card p-3 shadow-2 radius-8 border h-100">

                    <div class="card-body p-0">

                        <div class="d-flex align-items-center justify-content-between">

                            <div>

                                <span class="text-secondary-light">
                                    Clearance Month
                                </span>

                                <h6 class="fw-semibold mt-4 mb-0">

                                    <?= htmlspecialchars($currentMonthName) ?>

                                    <?= $currentYear ?>

                                </h6>

                            </div>

                            <div
                                class="w-48-px h-48-px bg-primary-100 text-primary-600 rounded-circle d-flex align-items-center justify-content-center">

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

                            </div>

                        </div>

                    </div>

                </div>

            </div>



            <!-- CDS Attendance -->
            <div class="col-xxl-3 col-sm-6">

                <div class="card p-3 shadow-2 radius-8 border h-100">

                    <div class="card-body p-0">

                        <div class="d-flex align-items-center justify-content-between">

                            <div>

                                <span class="text-secondary-light">
                                    CDS Attendance
                                </span>

                                <h6 class="fw-semibold mt-4 mb-0">

                                    <?= $cdsStats['attendance_rate'] ?>%

                                </h6>

                            </div>

                            <div
                                class="w-48-px h-48-px bg-success-100 text-success-600 rounded-circle d-flex align-items-center justify-content-center">

                                <i class="ri-calendar-check-line text-xl"></i>

                            </div>

                        </div>

                    </div>

                </div>

            </div>



            <!-- CDS Verification -->
            <div class="col-xxl-3 col-sm-6">

                <div class="card p-3 shadow-2 radius-8 border h-100">

                    <div class="card-body p-0">

                        <div class="d-flex align-items-center justify-content-between">

                            <div>

                                <span class="text-secondary-light">
                                    CDS Verification
                                </span>

                                <?php if ($cdsAttendanceVerified === 'Yes'): ?>

                                <h6 class="fw-semibold mt-4 mb-0 text-success-600">

                                    Verified

                                </h6>

                                <?php else: ?>

                                <h6 class="fw-semibold mt-4 mb-0 text-danger-600">

                                    Not Verified

                                </h6>

                                <?php endif; ?>

                            </div>

                            <div
                                class="w-48-px h-48-px bg-info-100 text-info-600 rounded-circle d-flex align-items-center justify-content-center">

                                <i class="ri-shield-check-line text-xl"></i>

                            </div>

                        </div>

                    </div>

                </div>

            </div>



            <!-- Clearance Status -->
            <div class="col-xxl-3 col-sm-6">

                <div class="card p-3 shadow-2 radius-8 border h-100">

                    <div class="card-body p-0">

                        <div class="d-flex align-items-center justify-content-between">

                            <div>

                                <span class="text-secondary-light">
                                    Clearance Status
                                </span>

                                <?php if (!$currentClearance): ?>

                                <h6 class="fw-semibold mt-4 mb-0 text-secondary-light">

                                    Not Submitted

                                </h6>

                                <?php elseif ($currentClearance['status'] === 'Approved'): ?>

                                <h6 class="fw-semibold mt-4 mb-0 text-success-600">

                                    Approved

                                </h6>

                                <?php elseif ($currentClearance['status'] === 'Rejected'): ?>

                                <h6 class="fw-semibold mt-4 mb-0 text-danger-600">

                                    Rejected

                                </h6>

                                <?php else: ?>

                                <h6 class="fw-semibold mt-4 mb-0 text-warning-600">

                                    Pending

                                </h6>

                                <?php endif; ?>

                            </div>

                            <div
                                class="w-48-px h-48-px bg-warning-100 text-warning-600 rounded-circle d-flex align-items-center justify-content-center">

                                <i class="ri-file-list-3-line text-xl"></i>

                            </div>

                        </div>

                    </div>

                </div>

            </div>

        </div>



        <!-- =========================================================
                 SUBMIT MONTHLY CLEARANCE
            ========================================================== -->

        <div class="card mb-24">

            <div class="card-header border-bottom bg-base py-16 px-24">

                <h6 class="text-lg fw-semibold mb-0">

                    <?= htmlspecialchars($currentMonthName) ?>

                    <?= $currentYear ?>

                    Monthly Clearance

                </h6>

            </div>


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


                <div class="row gy-4">


                    <!-- CORPS MEMBER INFORMATION -->

                    <div class="col-lg-6">

                        <h6 class="mb-16">
                            Corps Member Information
                        </h6>


                        <div class="d-flex flex-column gap-12">


                            <div class="d-flex gap-4">

                                <span class="fw-semibold text-sm text-primary-light w-150-px">
                                    Full Name
                                </span>

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

                                    :
                                    <?= htmlspecialchars(
                                            $corpsMember['firstname'] . ' ' .
                                            $corpsMember['lastname']
                                        ) ?>

                                </span>

                            </div>


                            <div class="d-flex gap-4">

                                <span class="fw-semibold text-sm text-primary-light w-150-px">
                                    State Code
                                </span>

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

                                    :
                                    <?= htmlspecialchars(
                                            $corpsMember['state_code']
                                        ) ?>

                                </span>

                            </div>


                            <div class="d-flex gap-4">

                                <span class="fw-semibold text-sm text-primary-light w-150-px">
                                    Batch
                                </span>

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

                                    :
                                    <?= htmlspecialchars(
                                            $corpsMember['batch'] ?? 'Not Set'
                                        ) ?>

                                </span>

                            </div>


                            <div class="d-flex gap-4">

                                <span class="fw-semibold text-sm text-primary-light w-150-px">
                                    Stream
                                </span>

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

                                    :
                                    <?= htmlspecialchars(
                                            $corpsMember['stream'] ?? 'Not Set'
                                        ) ?>

                                </span>

                            </div>

                        </div>

                    </div>



                    <!-- ATTENDANCE INFORMATION -->

                    <div class="col-lg-6">

                        <h6 class="mb-16">
                            CDS Attendance Verification
                        </h6>


                        <div class="d-flex flex-column gap-12">


                            <div class="d-flex justify-content-between">

                                <span>Total Meetings</span>

                                <strong>
                                    <?= $cdsStats['total'] ?>
                                </strong>

                            </div>


                            <div class="d-flex justify-content-between">

                                <span>Present</span>

                                <strong class="text-success-600">
                                    <?= $cdsStats['present'] ?>
                                </strong>

                            </div>


                            <div class="d-flex justify-content-between">

                                <span>Absent</span>

                                <strong class="text-danger-600">
                                    <?= $cdsStats['absent'] ?>
                                </strong>

                            </div>


                            <div class="d-flex justify-content-between">

                                <span>Excused</span>

                                <strong class="text-warning-600">
                                    <?= $cdsStats['excused'] ?>
                                </strong>

                            </div>


                            <div class="d-flex justify-content-between">

                                <span>Attendance Rate</span>

                                <strong>
                                    <?= $cdsStats['attendance_rate'] ?>%
                                </strong>

                            </div>


                            <div class="d-flex justify-content-between">

                                <span>Verification</span>


                                <?php if ($cdsAttendanceVerified === 'Yes'): ?>

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

                                    Verified

                                </span>

                                <?php else: ?>

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

                                    Not Verified

                                </span>

                                <?php endif; ?>

                            </div>

                        </div>

                    </div>

                </div>



                <hr class="my-24">



                <!-- =====================================================
                         CLEARANCE ACTION AREA
                    ====================================================== -->


                <?php if (!$currentClearance): ?>


                <?php if ($cdsAttendanceVerified === 'Yes'): ?>


                <div class="alert alert-success">

                    <div class="d-flex align-items-start gap-12">

                        <i class="ri-checkbox-circle-line text-xl"></i>

                        <div>

                            <h6 class="mb-4">
                                Eligible for Monthly Clearance
                            </h6>

                            <p class="mb-0">

                                Your CDS attendance requirement has been verified.

                                You can submit your

                                <?= htmlspecialchars($currentMonthName) ?>

                                monthly clearance.

                            </p>

                        </div>

                    </div>

                </div>


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

                    <input type="hidden" name="clearance_month" value="<?= $currentMonth ?>">

                    <input type="hidden" name="clearance_year" value="<?= $currentYear ?>">


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

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

                        Submit Monthly Clearance

                    </button>

                </form>


                <?php else: ?>


                <div class="alert alert-warning">

                    <div class="d-flex align-items-start gap-12">

                        <i class="ri-error-warning-line text-xl"></i>

                        <div>

                            <h6 class="mb-4">
                                Not Eligible for Clearance
                            </h6>

                            <p class="mb-0">

                                You currently do not meet the CDS attendance requirement.

                                Your attendance rate must be at least 75% before submitting
                                monthly clearance.

                            </p>

                        </div>

                    </div>

                </div>


                <?php endif; ?>


                <?php else: ?>


                <?php if ($currentClearance['status'] === 'Pending'): ?>


                <div class="alert alert-warning">

                    <h6 class="mb-4">

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

                        Clearance Pending Review

                    </h6>

                    <p class="mb-0">

                        Your monthly clearance was submitted on

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

                        It is currently awaiting review.

                    </p>

                </div>


                <?php elseif ($currentClearance['status'] === 'Approved'): ?>


                <div class="alert alert-success">

                    <h6 class="mb-4">

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

                        Clearance Approved

                    </h6>

                    <p class="mb-0">

                        Your monthly clearance has been approved successfully.

                    </p>

                </div>


                <?php elseif ($currentClearance['status'] === 'Rejected'): ?>


                <div class="alert alert-danger">

                    <h6 class="mb-4">

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

                        Clearance Rejected

                    </h6>


                    <p class="mb-0">

                        <?= htmlspecialchars(
                                        $currentClearance['remarks']
                                        ?? 'Your clearance application was rejected.'
                                    ) ?>

                    </p>

                </div>


                <?php endif; ?>


                <?php endif; ?>


            </div>

        </div>



        <!-- =========================================================
                 CLEARANCE HISTORY
            ========================================================== -->

        <div class="card">

            <div class="card-header border-bottom bg-base py-16 px-24">

                <h6 class="text-lg fw-semibold mb-0">
                    Clearance History
                </h6>

            </div>


            <div class="card-body p-0">


                <div class="table-responsive">

                    <table class="table mb-0">


                        <thead>

                            <tr>

                                <th>Month</th>

                                <th>Year</th>

                                <th>CDS Verified</th>

                                <th>Submitted Date</th>

                                <th>Status</th>

                                <th>Approval Date</th>

                                <th>Remarks</th>

                            </tr>

                        </thead>


                        <tbody>


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


                            <?php foreach ($clearanceHistory as $history): ?>


                            <tr>


                                <td>

                                    <?= date(
                                                    'F',
                                                    mktime(
                                                        0,
                                                        0,
                                                        0,
                                                        $history['clearance_month'],
                                                        1
                                                    )
                                                ) ?>

                                </td>


                                <td>

                                    <?= htmlspecialchars(
                                                    $history['clearance_year']
                                                ) ?>

                                </td>


                                <td>

                                    <?php if ($history['cds_attendance_verified'] === 'Yes'): ?>

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

                                        Yes

                                    </span>

                                    <?php else: ?>

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

                                        No

                                    </span>

                                    <?php endif; ?>

                                </td>


                                <td>

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

                                </td>


                                <td>


                                    <?php if ($history['status'] === 'Approved'): ?>

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

                                        Approved

                                    </span>


                                    <?php elseif ($history['status'] === 'Rejected'): ?>

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

                                        Rejected

                                    </span>


                                    <?php else: ?>

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

                                        Pending

                                    </span>

                                    <?php endif; ?>


                                </td>


                                <td>

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

                                </td>


                                <td>

                                    <?= htmlspecialchars(
                                                    $history['remarks'] ?? '-'
                                                ) ?>

                                </td>


                            </tr>


                            <?php endforeach; ?>


                            <?php else: ?>


                            <tr>

                                <td colspan="7" class="text-center py-40">

                                    <i class="ri-file-list-3-line text-xxl text-secondary-light"></i>

                                    <p class="mt-8 mb-0 text-secondary-light">

                                        No monthly clearance records found.

                                    </p>

                                </td>

                            </tr>


                            <?php endif; ?>


                        </tbody>


                    </table>

                </div>

            </div>

        </div>


        <?php endif; ?>


    </div>

</main>


<?php

require_once "../includes/footer.php";

?>