<?php

$pageTitle = "Clearance History";

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

require_login();

$user = current_user();

$successMessage = '';
$errorMessage = '';

/*
|--------------------------------------------------------------------------
| USER ROLE
|--------------------------------------------------------------------------
*/

$isCorpsMember = false;

if (
    isset($user['role']) &&
    strtolower($user['role']) == 'corps member'
) {

    $isCorpsMember = true;

}

/*
|--------------------------------------------------------------------------
| FLASH MESSAGES
|--------------------------------------------------------------------------
*/

if (!empty($_SESSION['success_message'])) {

    $successMessage = $_SESSION['success_message'];

    unset($_SESSION['success_message']);

}

if (!empty($_SESSION['error_message'])) {

    $errorMessage = $_SESSION['error_message'];

    unset($_SESSION['error_message']);

}

/*
|--------------------------------------------------------------------------
| FETCH CLEARANCE HISTORY
|--------------------------------------------------------------------------
*/

if ($isCorpsMember) {

    $stmt = $db->prepare("

        SELECT

        mc.*,

        cm.state_code,

        cm.call_up_number,

        cg.group_name,

        CONCAT(co.firstname,' ',co.lastname) AS approved_by_name

        FROM monthly_clearance mc

        INNER JOIN corps_members cm

        ON cm.id=mc.corps_member_id

        LEFT JOIN cds_group_members cgm

        ON cgm.corps_member_id=cm.id

        LEFT JOIN cds_groups cg

        ON cg.id=cgm.cds_group_id

        LEFT JOIN camp_officials co

        ON co.id=mc.approved_by

        WHERE cm.user_id=?

        ORDER BY

        mc.clearance_year DESC,

        mc.clearance_month DESC

    ");

    $stmt->execute([

        $user['id']

    ]);

}
else{

    $stmt = $db->query("

        SELECT

        mc.*,

        cm.firstname,

        cm.lastname,

        cm.state_code,

        cm.call_up_number,

        cg.group_name,

        CONCAT(co.firstname,' ',co.lastname) AS approved_by_name

        FROM monthly_clearance mc

        INNER JOIN corps_members cm

        ON cm.id=mc.corps_member_id

        LEFT JOIN cds_group_members cgm

        ON cgm.corps_member_id=cm.id

        LEFT JOIN cds_groups cg

        ON cg.id=cgm.cds_group_id

        LEFT JOIN camp_officials co

        ON co.id=mc.approved_by

        ORDER BY

        mc.clearance_year DESC,

        mc.clearance_month DESC,

        cm.firstname

    ");

}

$history = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

?>

<main class="dashboard-main">

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

    <div class="dashboard-main-body">
        <!-- ================= PAGE HEADER ================= -->

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

            <div>

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

                    <?= $pageTitle ?>

                </h6>

                <p class="text-neutral-500">

                    <?= APP_SHORT_NAME ?>

                    >

                    Monthly Clearance

                    >

                    Clearance History

                </p>

            </div>

        </div>

        <!-- ================= FLASH MESSAGES ================= -->

        <?php if($successMessage): ?>

        <div class="alert alert-success">

            <?= $successMessage ?>

        </div>

        <?php endif; ?>

        <?php if($errorMessage): ?>

        <div class="alert alert-danger">

            <?= $errorMessage ?>

        </div>

        <?php endif; ?>

        <!-- ================= SUMMARY ================= -->

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

        <?php

$pending = 0;
$approved = 0;
$rejected = 0;

foreach($history as $row){

if($row['status']=="Pending"){

    $pending++;

}
elseif($row['status']=="Approved"){

    $approved++;

}
else{

    $rejected++;

}

}

?>

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

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

                <div class="card">

                    <div class="card-body">

                        <h6>

                            Pending

                        </h6>

                        <h2 class="fw-bold text-warning">

                            <?= $pending ?>

                        </h2>

                    </div>

                </div>

            </div>

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

                <div class="card">

                    <div class="card-body">

                        <h6>

                            Approved

                        </h6>

                        <h2 class="fw-bold text-success">

                            <?= $approved ?>

                        </h2>

                    </div>

                </div>

            </div>

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

                <div class="card">

                    <div class="card-body">

                        <h6>

                            Rejected

                        </h6>

                        <h2 class="fw-bold text-danger">

                            <?= $rejected ?>

                        </h2>

                    </div>

                </div>

            </div>

        </div>

        <?php endif; ?>

        <!-- ================= HISTORY TABLE ================= -->

        <div class="card">

            <div class="card-header">

                <h6 class="mb-0">

                    Monthly Clearance History

                </h6>

            </div>

            <div class="card-body">

                <table class="table bordered-table data-table" id="dataTable">

                    <thead>

                        <tr>

                            <th>#</th>

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

                            <th>State Code</th>

                            <th>Corps Member</th>

                            <?php endif; ?>

                            <th>Month</th>

                            <th>Year</th>

                            <th>Submitted</th>

                            <th>Approved</th>

                            <th>Status</th>

                            <th>Action</th>

                        </tr>

                    </thead>

                    <tbody>

                        <?php

        $count=1;

        foreach($history as $record):

        ?>

                        <tr>

                            <td>

                                <?= $count++ ?>

                            </td>

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

                            <td>

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

                            </td>

                            <td>

                                <?= htmlspecialchars(

                $record['firstname']." ".$record['lastname']

                ) ?>

                            </td>

                            <?php endif; ?>

                            <td>

                                <?= date(

                'F',

                mktime(

                0,

                0,

                0,

                $record['clearance_month'],

                1

                )

                ) ?>

                            </td>

                            <td>

                                <?= $record['clearance_year'] ?>

                            </td>

                            <td>

                                <?= date(

                'd M Y',

                strtotime($record['submitted_date'])

                ) ?>

                            </td>

                            <td>

                                <?php

                if(!empty($record['approval_date'])){

                    echo date(

                    'd M Y',

                    strtotime($record['approval_date'])

                    );

                }else{

                    echo "-";

                }

                ?>

                            </td>

                            <td>

                                <?php

                if($record['status']=="Pending"){

                ?>

                                <span class="badge bg-warning">

                                    Pending

                                </span>

                                <?php

                }

                elseif($record['status']=="Approved"){

                ?>

                                <span class="badge bg-success">

                                    Approved

                                </span>

                                <?php

                }

                else{

                ?>

                                <span class="badge bg-danger">

                                    Rejected

                                </span>

                                <?php

                }

                ?>

                            </td>

                            <td>

                                <div class="dropdown">

                                    <button class="btn btn-light" data-bs-toggle="dropdown">

                                        <i class="ri-more-2-fill"></i>

                                    </button>

                                    <ul class="dropdown-menu">

                                        <li>

                                            <button class="dropdown-item view-history-btn"
                                                data-name="<?= htmlspecialchars(($record['firstname'] ?? '').' '.($record['lastname'] ?? '')) ?>"
                                                data-state="<?= htmlspecialchars($record['state_code']) ?>"
                                                data-callup="<?= htmlspecialchars($record['call_up_number']) ?>"
                                                data-group="<?= htmlspecialchars($record['group_name']) ?>"
                                                data-month="<?= date('F',mktime(0,0,0,$record['clearance_month'],1)) ?>"
                                                data-year="<?= $record['clearance_year'] ?>"
                                                data-cds="<?= $record['cds_attendance_verified'] ?>"
                                                data-camp="<?= $record['camp_activity_verified'] ?>"
                                                data-biometric="<?= $record['biometric_verified'] ?>"
                                                data-submitted="<?= $record['submitted_date'] ?>"
                                                data-approved="<?= $record['approval_date'] ?>"
                                                data-approvedby="<?= htmlspecialchars($record['approved_by_name']) ?>"
                                                data-status="<?= $record['status'] ?>"
                                                data-remarks="<?= htmlspecialchars($record['remarks']) ?>"
                                                data-bs-toggle="modal" data-bs-target="#viewHistoryModal">

                                                <i class="ri-eye-line"></i>

                                                View

                                            </button>

                                        </li>

                                        <li>

                                            <a href="print-clearance.php?id=<?= $record['id'] ?>" target="_blank"
                                                class="dropdown-item">

                                                <i class="ri-printer-line"></i>

                                                Print

                                            </a>

                                        </li>

                                    </ul>

                                </div>

                            </td>

                        </tr>

                        <?php endforeach; ?>

                    </tbody>

                </table>

            </div>

        </div>

        <!-- ======================================================= -->
        <!-- VIEW HISTORY MODAL -->
        <!-- ======================================================= -->

        <div class="modal fade" id="viewHistoryModal" tabindex="-1">

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

                <div class="modal-content">

                    <div class="modal-header">

                        <h5 class="modal-title">

                            Clearance History Details

                        </h5>

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

                        </button>

                    </div>

                    <div class="modal-body">

                        <table class="table table-bordered">

                            <tr>

                                <th width="35%">

                                    Corps Member

                                </th>

                                <td id="historyMember"></td>

                            </tr>

                            <tr>

                                <th>

                                    State Code

                                </th>

                                <td id="historyStateCode"></td>

                            </tr>

                            <tr>

                                <th>

                                    Call-Up Number

                                </th>

                                <td id="historyCallUp"></td>

                            </tr>

                            <tr>

                                <th>

                                    CDS Group

                                </th>

                                <td id="historyGroup"></td>

                            </tr>

                            <tr>

                                <th>

                                    Clearance Month

                                </th>

                                <td id="historyMonth"></td>

                            </tr>

                            <tr>

                                <th>

                                    Clearance Year

                                </th>

                                <td id="historyYear"></td>

                            </tr>

                            <tr>

                                <th>

                                    CDS Attendance

                                </th>

                                <td id="historyCDS"></td>

                            </tr>

                            <tr>

                                <th>

                                    Camp Activity

                                </th>

                                <td id="historyCamp"></td>

                            </tr>

                            <tr>

                                <th>

                                    Biometric

                                </th>

                                <td id="historyBiometric"></td>

                            </tr>

                            <tr>

                                <th>

                                    Submitted Date

                                </th>

                                <td id="historySubmitted"></td>

                            </tr>

                            <tr>

                                <th>

                                    Approval Date

                                </th>

                                <td id="historyApproved"></td>

                            </tr>

                            <tr>

                                <th>

                                    Approved By

                                </th>

                                <td id="historyApprovedBy"></td>

                            </tr>

                            <tr>

                                <th>

                                    Status

                                </th>

                                <td id="historyStatus"></td>

                            </tr>

                            <tr>

                                <th>

                                    Remarks

                                </th>

                                <td id="historyRemarks"></td>

                            </tr>

                        </table>

                    </div>

                    <div class="modal-footer">

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

                            Close

                        </button>

                    </div>

                </div>

            </div>

        </div>

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

        <script>
        /* ==========================================================
            VIEW HISTORY
        ========================================================== */

        $(document).on('click', '.view-history-btn', function() {

            $('#historyMember').text($(this).data('name'));

            $('#historyStateCode').text($(this).data('state'));

            $('#historyCallUp').text($(this).data('callup'));

            $('#historyGroup').text($(this).data('group'));

            $('#historyMonth').text($(this).data('month'));

            $('#historyYear').text($(this).data('year'));

            $('#historyCDS').text($(this).data('cds'));

            $('#historyCamp').text($(this).data('camp'));

            $('#historyBiometric').text($(this).data('biometric'));

            $('#historySubmitted').text($(this).data('submitted'));

            $('#historyApproved').text(

                $(this).data('approved') || '-'

            );

            $('#historyApprovedBy').text(

                $(this).data('approvedby') || '-'

            );

            $('#historyStatus').text($(this).data('status'));

            $('#historyRemarks').text(

                $(this).data('remarks') || '-'

            );

        });
        </script>