<?php

$pageTitle = "All Corps Members";

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

require_login();

$user = current_user();


/*
|--------------------------------------------------------------------------
| OPTIONAL ROLE PROTECTION
|--------------------------------------------------------------------------
|
| Uncomment this when you want only Administrator and Camp Officer
| to access this page.
|--------------------------------------------------------------------------
*/

// $allowedRoles = ['Administrator', 'Camp Officer'];
//
// if (!in_array($user['role'], $allowedRoles)) {
//     header("Location: index.php");
//     exit;
// }


/*
|--------------------------------------------------------------------------
| GET FILTER VALUES
|--------------------------------------------------------------------------
*/

$genderFilter = trim($_GET['gender'] ?? '');

$statusFilter = trim($_GET['status'] ?? '');

$batchFilter = trim($_GET['batch'] ?? '');

$streamFilter = trim($_GET['stream'] ?? '');


/*
|--------------------------------------------------------------------------
| BUILD CORPS MEMBERS QUERY
|--------------------------------------------------------------------------
*/

$sql = "
    SELECT
        cm.id,
        cm.user_id,
        cm.state_id,
        cm.lga_id,
        cm.platoon_id,
        cm.hostel_id,

        cm.state_code,
        cm.call_up_number,

        cm.firstname,
        cm.lastname,
        cm.othername,

        cm.gender,
        cm.date_of_birth,
        cm.phone,
        cm.email,

        cm.institution,
        cm.course_of_study,
        cm.qualification,
        cm.graduation_year,

        cm.marital_status,
        cm.passport,

        cm.home_address,

        cm.next_of_kin,
        cm.next_of_kin_phone,

        cm.batch,
        cm.stream,
        cm.year_of_service,
        cm.registration_date,

        cm.status AS corps_status,

        u.status AS account_status,
        u.avatar AS user_avatar,

        s.state_name,

        lga.lga_name,

        p.platoon_name,
        p.platoon_code,

        h.hostel_name,
        h.hostel_code

    FROM corps_members cm

    LEFT JOIN users u
        ON cm.user_id = u.id

    LEFT JOIN states s
        ON cm.state_id = s.id

    LEFT JOIN local_governments lga
        ON cm.lga_id = lga.id

    LEFT JOIN platoons p
        ON cm.platoon_id = p.id

    LEFT JOIN hostels h
        ON cm.hostel_id = h.id

    WHERE 1 = 1
";


/*
|--------------------------------------------------------------------------
| QUERY PARAMETERS
|--------------------------------------------------------------------------
*/

$params = [];


/*
|--------------------------------------------------------------------------
| FILTER BY GENDER
|--------------------------------------------------------------------------
*/

if (!empty($genderFilter)) {

    $sql .= "
        AND cm.gender = ?
    ";

    $params[] = $genderFilter;
}


/*
|--------------------------------------------------------------------------
| FILTER BY CORPS MEMBER STATUS
|--------------------------------------------------------------------------
*/

if (!empty($statusFilter)) {

    $sql .= "
        AND cm.status = ?
    ";

    $params[] = $statusFilter;
}


/*
|--------------------------------------------------------------------------
| FILTER BY BATCH
|--------------------------------------------------------------------------
*/

if (!empty($batchFilter)) {

    $sql .= "
        AND cm.batch = ?
    ";

    $params[] = $batchFilter;
}


/*
|--------------------------------------------------------------------------
| FILTER BY STREAM
|--------------------------------------------------------------------------
*/

if (!empty($streamFilter)) {

    $sql .= "
        AND cm.stream = ?
    ";

    $params[] = $streamFilter;
}


/*
|--------------------------------------------------------------------------
| ORDER RESULTS
|--------------------------------------------------------------------------
*/

$sql .= "
    ORDER BY cm.created_at DESC
";


/*
|--------------------------------------------------------------------------
| EXECUTE QUERY
|--------------------------------------------------------------------------
*/

$stmt = $db->prepare($sql);

$stmt->execute($params);

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


/*
|--------------------------------------------------------------------------
| GET AVAILABLE BATCHES
|--------------------------------------------------------------------------
*/

$batchStmt = $db->query("
    SELECT DISTINCT batch
    FROM corps_members
    WHERE batch IS NOT NULL
    AND batch != ''
    ORDER BY batch ASC
");

$batches = $batchStmt->fetchAll(PDO::FETCH_COLUMN);


/*
|--------------------------------------------------------------------------
| GET AVAILABLE STREAMS
|--------------------------------------------------------------------------
*/

$streamStmt = $db->query("
    SELECT DISTINCT stream
    FROM corps_members
    WHERE stream IS NOT NULL
    AND stream != ''
    ORDER BY stream ASC
");

$streams = $streamStmt->fetchAll(PDO::FETCH_COLUMN);


/*
|--------------------------------------------------------------------------
| 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">

                    <?= htmlspecialchars(APP_SHORT_NAME); ?>

                    >

                    <?= htmlspecialchars($pageTitle); ?>

                </p>

            </div>


            <!-- REGISTER CORPS MEMBER BUTTON -->

            <div>

                <a href="register_corps_member.php" class="btn btn-primary-600 d-flex align-items-center gap-8">

                    <i class="ri-user-add-line"></i>

                    Register Corps Member

                </a>

            </div>

        </div>



        <!-- =========================================================
        SUCCESS MESSAGE
        ========================================================== -->

        <?php if (!empty($_SESSION['success_message'])): ?>

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

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

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

        </div>

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

        <?php endif; ?>



        <!-- =========================================================
        ERROR MESSAGE
        ========================================================== -->

        <?php if (!empty($_SESSION['error_message'])): ?>

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

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

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

        </div>

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

        <?php endif; ?>



        <div class="mt-24">

            <div class="card h-100">

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


                    <!-- =====================================================
                    TABLE TOP BAR
                    ====================================================== -->

                    <div
                        class="d-flex align-items-center justify-content-between flex-wrap gap-16 px-20 py-12 border-bottom border-neutral-200">


                        <div class="d-flex flex-wrap align-items-center gap-16">


                            <!-- =============================================
                            EXPORT DROPDOWN
                            ============================================== -->

                            <div class="dropdown">

                                <button type="button"
                                    class="px-12 py-5-px border border-neutral-300 radius-8 d-flex align-items-center gap-20"
                                    data-bs-toggle="dropdown" aria-expanded="false">

                                    <span class="d-flex align-items-center gap-1 text-secondary-light text-sm">

                                        <i class="ri-file-upload-line text-md line-height-1">
                                        </i>

                                        Export

                                    </span>

                                    <span>

                                        <i class="ri-arrow-down-s-line"></i>

                                    </span>

                                </button>


                                <ul class="dropdown-menu p-12 border bg-base shadow">


                                    <li>

                                        <button type="button"
                                            class="dropdown-item px-16 py-8 rounded text-secondary-light bg-hover-neutral-200 text-hover-neutral-900 d-flex align-items-center gap-10">

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

                                            PDF

                                        </button>

                                    </li>


                                    <li>

                                        <button type="button"
                                            class="dropdown-item px-16 py-8 rounded text-secondary-light bg-hover-neutral-200 text-hover-neutral-900 d-flex align-items-center gap-10">

                                            <i class="ri-file-excel-line"></i>

                                            Excel

                                        </button>

                                    </li>


                                </ul>

                            </div>



                            <!-- =============================================
                            DATATABLE SEARCH
                            ============================================== -->

                            <div class="navbar-search dt-search m-0">

                                <input type="text" id="corpsMemberSearch" class="dt-input bg-transparent radius-4"
                                    placeholder="Search corps member...">

                                <iconify-icon icon="ion:search-outline" class="icon">
                                </iconify-icon>

                            </div>



                            <!-- =============================================
                            FILTER DROPDOWN
                            ============================================== -->

                            <div class="dropdown">


                                <button type="button"
                                    class="px-12 py-5-px border border-neutral-300 radius-8 d-flex align-items-center gap-20"
                                    data-bs-toggle="dropdown" aria-expanded="false">

                                    <span class="d-flex align-items-center gap-1 text-secondary-light text-sm">

                                        <i class="ri-filter-3-line"></i>

                                        Filter

                                    </span>

                                    <span>

                                        <i class="ri-arrow-down-s-line"></i>

                                    </span>

                                </button>



                                <div class="dropdown-menu border bg-base shadow dropdown-menu-lg p-0">


                                    <div
                                        class="d-flex align-items-center justify-content-between border-bottom py-8 px-16">

                                        <span class="fw-semibold text-lg text-primary-light">

                                            Filter Corps Members

                                        </span>

                                    </div>



                                    <form method="GET" action="" class="p-16 d-grid grid-cols-2 gap-16">


                                        <!-- BATCH -->

                                        <div>

                                            <label class="text-sm fw-semibold text-primary-light d-inline-block mb-8">

                                                Batch

                                            </label>


                                            <select name="batch" class="form-control form-select">

                                                <option value="">
                                                    All Batches
                                                </option>


                                                <?php foreach ($batches as $batch): ?>

                                                <option value="<?= htmlspecialchars($batch); ?>" <?= $batchFilter === $batch
                                                            ? 'selected'
                                                            : ''; ?>>

                                                    <?= htmlspecialchars($batch); ?>

                                                </option>

                                                <?php endforeach; ?>

                                            </select>

                                        </div>



                                        <!-- STREAM -->

                                        <div>

                                            <label class="text-sm fw-semibold text-primary-light d-inline-block mb-8">

                                                Stream

                                            </label>


                                            <select name="stream" class="form-control form-select">

                                                <option value="">
                                                    All Streams
                                                </option>


                                                <?php foreach ($streams as $stream): ?>

                                                <option value="<?= htmlspecialchars($stream); ?>" <?= $streamFilter === $stream
                                                            ? 'selected'
                                                            : ''; ?>>

                                                    <?= htmlspecialchars($stream); ?>

                                                </option>

                                                <?php endforeach; ?>

                                            </select>

                                        </div>



                                        <!-- GENDER -->

                                        <div>

                                            <label class="text-sm fw-semibold text-primary-light d-inline-block mb-8">

                                                Gender

                                            </label>


                                            <select name="gender" class="form-control form-select">

                                                <option value="">
                                                    All Genders
                                                </option>

                                                <option value="Male" <?= $genderFilter === 'Male'
                                                        ? 'selected'
                                                        : ''; ?>>

                                                    Male

                                                </option>

                                                <option value="Female" <?= $genderFilter === 'Female'
                                                        ? 'selected'
                                                        : ''; ?>>

                                                    Female

                                                </option>

                                            </select>

                                        </div>



                                        <!-- STATUS -->

                                        <div>

                                            <label class="text-sm fw-semibold text-primary-light d-inline-block mb-8">

                                                NYSC Status

                                            </label>


                                            <select name="status" class="form-control form-select">

                                                <option value="">
                                                    All Statuses
                                                </option>

                                                <option value="Registered" <?= $statusFilter === 'Registered'
                                                        ? 'selected'
                                                        : ''; ?>>

                                                    Registered

                                                </option>

                                                <option value="In Camp" <?= $statusFilter === 'In Camp'
                                                        ? 'selected'
                                                        : ''; ?>>

                                                    In Camp

                                                </option>

                                                <option value="Serving" <?= $statusFilter === 'Serving'
                                                        ? 'selected'
                                                        : ''; ?>>

                                                    Serving

                                                </option>

                                                <option value="Completed" <?= $statusFilter === 'Completed'
                                                        ? 'selected'
                                                        : ''; ?>>

                                                    Completed

                                                </option>

                                            </select>

                                        </div>

                                        <!-- RESET -->
                                        <div>

                                            <a href="all-corps-members.php"
                                                class="btn btn-danger-200 text-danger-600 w-100">
                                                Reset

                                            </a>

                                        </div>



                                        <!-- APPLY -->

                                        <div>

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

                                                Apply

                                            </button>

                                        </div>


                                    </form>

                                </div>

                            </div>

                        </div>


                        <!-- =============================================
                         TOTAL RECORDS
                        ============================================== -->

                        <div class="d-flex align-items-center gap-8 text-secondary-light">

                            <span>

                                Total Corps Members:

                            </span>

                            <span class="fw-semibold text-primary-600">

                                <?= count($corpsMembers); ?>

                            </span>

                        </div>


                    </div>



                    <!-- =====================================================
                    CORPS MEMBERS TABLE
                    ====================================================== -->

                    <div class="p-0">

                        <div class="table-responsive">

                            <table class="table bordered-table mb-0 data-table" id="dataTable" data-page-length="10">


                                <thead>

                                    <tr>

                                        <th scope="col">
                                            S/N
                                        </th>

                                        <th scope="col">
                                            State Code
                                        </th>

                                        <th scope="col">
                                            Corps Member
                                        </th>

                                        <th scope="col">
                                            Call-Up Number
                                        </th>

                                        <th scope="col">
                                            Batch / Stream
                                        </th>

                                        <th scope="col">
                                            Gender
                                        </th>

                                        <th scope="col">
                                            Phone
                                        </th>

                                        <th scope="col">
                                            State
                                        </th>

                                        <th scope="col">
                                            Status
                                        </th>

                                        <th scope="col">
                                            Action
                                        </th>

                                    </tr>

                                </thead>



                                <tbody>


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


                                    <?php

                                        $serialNumber = 1;

                                        foreach ($corpsMembers as $member):


                                            /*
                                            |--------------------------------------------------------------------------
                                            | FULL NAME
                                            |--------------------------------------------------------------------------
                                            */

                                            $fullName = trim(

                                                $member['firstname'] .

                                                ' ' .

                                                ($member['othername'] ?? '') .

                                                ' ' .

                                                $member['lastname']

                                            );


                                            /*
                                            |--------------------------------------------------------------------------
                                            | PASSPORT
                                            |--------------------------------------------------------------------------
                                            */

                                            $passport = $member['passport']
                                                ?: $member['user_avatar'];


                                            if (!empty($passport)) {

                                                $passportUrl =
                                                    '../' .
                                                    ltrim(
                                                        $passport,
                                                        '/'
                                                    );

                                            } else {

                                                $passportUrl =
                                                    '../assets/images/user-grid/user-grid-img13.png';
                                            }


                                            /*
                                            |--------------------------------------------------------------------------
                                            | STATUS BADGE
                                            |--------------------------------------------------------------------------
                                            */

                                            $statusClass =
                                                'bg-neutral-200 text-neutral-600';


                                            switch ($member['corps_status']) {

                                                case 'Registered':

                                                    $statusClass =
                                                        'bg-info-100 text-info-600';

                                                    break;


                                                case 'In Camp':

                                                    $statusClass =
                                                        'bg-warning-100 text-warning-600';

                                                    break;


                                                case 'Serving':

                                                    $statusClass =
                                                        'bg-success-100 text-success-600';

                                                    break;


                                                case 'Completed':

                                                    $statusClass =
                                                        'bg-primary-100 text-primary-600';

                                                    break;


                                                default:

                                                    $statusClass =
                                                        'bg-neutral-200 text-neutral-600';
                                            }

                                        ?>


                                    <tr>


                                        <!-- SERIAL NUMBER -->

                                        <td>

                                            <?= $serialNumber++; ?>

                                        </td>



                                        <!-- STATE CODE -->

                                        <td>

                                            <span class="text-primary-600 fw-semibold">

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

                                            </span>

                                        </td>



                                        <!-- CORPS MEMBER -->

                                        <td>


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


                                                <img src="<?= htmlspecialchars(
                                                                $passportUrl
                                                            ); ?>" alt="Passport" class="flex-shrink-0 me-12 radius-8"
                                                    width="45" height="45" style="object-fit: cover;">


                                                <div>


                                                    <h6 class="text-md mb-0 fw-medium">

                                                        <?= htmlspecialchars(
                                                                    $fullName
                                                                ); ?>

                                                    </h6>


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

                                                        <?= htmlspecialchars(
                                                                    $member['email']
                                                                        ?? ''
                                                                ); ?>

                                                    </span>


                                                </div>


                                            </div>


                                        </td>



                                        <!-- CALL-UP NUMBER -->

                                        <td>

                                            <?= !empty(
                                                        $member['call_up_number']
                                                    )
                                                        ? htmlspecialchars(
                                                            $member['call_up_number']
                                                        )
                                                        : '-'; ?>

                                        </td>



                                        <!-- BATCH / STREAM -->

                                        <td>

                                            <?php

                                                    $batchStream = [];

                                                    if (!empty($member['batch'])) {

                                                        $batchStream[] =
                                                            $member['batch'];
                                                    }

                                                    if (!empty($member['stream'])) {

                                                        $batchStream[] =
                                                            $member['stream'];
                                                    }

                                                    ?>

                                            <?= !empty($batchStream)
                                                        ? htmlspecialchars(
                                                            implode(
                                                                ' / ',
                                                                $batchStream
                                                            )
                                                        )
                                                        : '-'; ?>

                                        </td>



                                        <!-- GENDER -->

                                        <td>

                                            <?= !empty(
                                                        $member['gender']
                                                    )
                                                        ? htmlspecialchars(
                                                            $member['gender']
                                                        )
                                                        : '-'; ?>

                                        </td>



                                        <!-- PHONE -->

                                        <td>

                                            <?= !empty(
                                                        $member['phone']
                                                    )
                                                        ? htmlspecialchars(
                                                            $member['phone']
                                                        )
                                                        : '-'; ?>

                                        </td>



                                        <!-- STATE -->

                                        <td>

                                            <?= !empty(
                                                        $member['state_name']
                                                    )
                                                        ? htmlspecialchars(
                                                            $member['state_name']
                                                        )
                                                        : '-'; ?>

                                        </td>



                                        <!-- STATUS -->

                                        <td>

                                            <span class="<?= $statusClass; ?> px-16 py-4 radius-4 fw-medium text-sm">

                                                <?= htmlspecialchars(
                                                            $member['corps_status']
                                                        ); ?>

                                            </span>

                                        </td>



                                        <!-- ACTION -->

                                        <td>


                                            <div class="btn-group">


                                                <button type="button" class="text-primary-light text-xl"
                                                    data-bs-toggle="dropdown" data-bs-display="static"
                                                    aria-expanded="false">

                                                    <iconify-icon icon="tabler:dots-vertical">
                                                    </iconify-icon>

                                                </button>



                                                <ul class="dropdown-menu dropdown-menu-lg-end border p-12">


                                                    <!-- VIEW PROFILE -->

                                                    <li>

                                                        <a href="view_corps_member.php?id=<?= (int) $member['id']; ?>"
                                                            class="dropdown-item rounded text-secondary-light bg-hover-neutral-200 text-hover-neutral-900 d-flex align-items-center gap-2 py-6">

                                                            <i class="ri-user-3-line">
                                                            </i>

                                                            View Profile

                                                        </a>

                                                    </li>



                                                    <!-- EDIT -->

                                                    <li>

                                                        <a href="edit_corps_member.php?id=<?= (int) $member['id']; ?>"
                                                            class="dropdown-item rounded text-secondary-light bg-hover-neutral-200 text-hover-neutral-900 d-flex align-items-center gap-2 py-6">

                                                            <i class="ri-edit-2-line">
                                                            </i>

                                                            Edit Corps Member

                                                        </a>

                                                    </li>

                                                    <!-- DELETE -->

                                                    <li>

                                                        <button type="button"
                                                            class="dropdown-item rounded text-danger-600 bg-hover-danger-100 d-flex align-items-center gap-2 py-6 deleteCorpsMemberBtn"
                                                            data-id="<?= (int) $member['id']; ?>" data-name="<?= htmlspecialchars(
                                                                        $fullName,
                                                                        ENT_QUOTES
                                                                    ); ?>" data-bs-toggle="modal"
                                                            data-bs-target="#deleteCorpsMemberModal">

                                                            <i class="ri-delete-bin-6-line">
                                                            </i>

                                                            Delete

                                                        </button>

                                                    </li>


                                                </ul>


                                            </div>


                                        </td>


                                    </tr>


                                    <?php endforeach; ?>


                                    <?php else: ?>


                                    <tr>

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

                                            <div class="d-flex flex-column align-items-center">


                                                <i class="ri-user-search-line text-4xl text-secondary-light mb-8">
                                                </i>


                                                <h6 class="mb-4">

                                                    No Corps Members Found

                                                </h6>


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

                                                    No corps member matches your current search or filter.

                                                </p>


                                                <a href="register-corps-member.php" class="btn btn-primary-600">

                                                    Register Corps Member

                                                </a>


                                            </div>

                                        </td>

                                    </tr>


                                    <?php endif; ?>


                                </tbody>


                            </table>


                        </div>

                    </div>


                </div>

            </div>

        </div>


    </div>

</main>



<!-- =============================================================
DELETE CORPS MEMBER MODAL
============================================================== -->

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


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


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


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


                <div class="text-center">


                    <span
                        class="w-64-px h-64-px bg-danger-100 text-danger-600 rounded-circle d-inline-flex align-items-center justify-content-center mb-16">

                        <i class="ri-delete-bin-6-line text-3xl">
                        </i>

                    </span>


                    <h6 class="mb-8">

                        Delete Corps Member?

                    </h6>


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

                        Are you sure you want to delete

                        <strong id="deleteCorpsMemberName">
                        </strong>?

                    </p>


                    <p class="text-danger-600 text-sm">

                        This action cannot be undone.

                    </p>


                </div>



                <div class="d-flex align-items-center justify-content-center gap-12 mt-24">


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

                        Cancel

                    </button>


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


                        <input type="hidden" name="corps_member_id" id="deleteCorpsMemberId">


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

                            Yes, Delete

                        </button>


                    </form>


                </div>


            </div>


        </div>


    </div>


</div>



<!-- =============================================================
DELETE MODAL JAVASCRIPT
============================================================== -->

<script>
document.addEventListener(
    'DOMContentLoaded',
    function() {

        const deleteButtons =
            document.querySelectorAll(
                '.deleteCorpsMemberBtn'
            );

        const deleteIdInput =
            document.getElementById(
                'deleteCorpsMemberId'
            );

        const deleteNameElement =
            document.getElementById(
                'deleteCorpsMemberName'
            );


        deleteButtons.forEach(
            function(button) {

                button.addEventListener(
                    'click',
                    function() {

                        const memberId =
                            this.getAttribute(
                                'data-id'
                            );

                        const memberName =
                            this.getAttribute(
                                'data-name'
                            );


                        deleteIdInput.value =
                            memberId;

                        deleteNameElement.textContent =
                            memberName;

                    }
                );

            }
        );

    }
);
</script>


<?php

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

?>