<?php

$pageTitle = "Platoons";

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

require_login();

$user = current_user();

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

 
/*
|--------------------------------------------------------------------------
| 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']);
}


/*
|--------------------------------------------------------------------------
| PROCESS FORM ACTIONS
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $action = $_POST['action'] ?? '';

    try {

        /*
        |--------------------------------------------------------------------------
        | ADD PLATOON
        |--------------------------------------------------------------------------
        */

        if ($action === 'add') {

            $platoonName = trim($_POST['platoon_name'] ?? '');
            $platoonCode = trim($_POST['platoon_code'] ?? '');
            $status = trim($_POST['status'] ?? 'Active');

            if (empty($platoonName) || empty($platoonCode)) {
                throw new Exception(
                    "Platoon Name and Platoon Code are required."
                );
            }


            /*
            |--------------------------------------------------------------------------
            | CHECK DUPLICATE PLATOON CODE
            |--------------------------------------------------------------------------
            */

            $checkStmt = $db->prepare("
                SELECT id
                FROM platoons
                WHERE platoon_code = ?
                LIMIT 1
            ");

            $checkStmt->execute([
                $platoonCode
            ]);

            if ($checkStmt->fetch()) {
                throw new Exception(
                    "A platoon with this code already exists."
                );
            }


            /*
            |--------------------------------------------------------------------------
            | INSERT PLATOON
            |--------------------------------------------------------------------------
            */

            $stmt = $db->prepare("
                INSERT INTO platoons
                (
                    platoon_name,
                    platoon_code,
                    status
                )
                VALUES
                (
                    ?,
                    ?,
                    ?
                )
            ");

            $stmt->execute([
                $platoonName,
                $platoonCode,
                $status
            ]);

            $_SESSION['success_message'] =
                "Platoon added successfully.";

            header("Location: platoons.php");
            exit;
        }


        /*
        |--------------------------------------------------------------------------
        | EDIT PLATOON
        |--------------------------------------------------------------------------
        */

        if ($action === 'edit') {

            $platoonId = (int) ($_POST['platoon_id'] ?? 0);

            $platoonName = trim($_POST['platoon_name'] ?? '');
            $platoonCode = trim($_POST['platoon_code'] ?? '');
            $status = trim($_POST['status'] ?? 'Active');

            if ($platoonId <= 0) {
                throw new Exception(
                    "Invalid platoon selected."
                );
            }

            if (empty($platoonName) || empty($platoonCode)) {
                throw new Exception(
                    "Platoon Name and Platoon Code are required."
                );
            }


            /*
            |--------------------------------------------------------------------------
            | CHECK DUPLICATE CODE
            |--------------------------------------------------------------------------
            */

            $checkStmt = $db->prepare("
                SELECT id
                FROM platoons
                WHERE platoon_code = ?
                AND id != ?
                LIMIT 1
            ");

            $checkStmt->execute([
                $platoonCode,
                $platoonId
            ]);

            if ($checkStmt->fetch()) {
                throw new Exception(
                    "Another platoon already uses this Platoon Code."
                );
            }


            /*
            |--------------------------------------------------------------------------
            | UPDATE PLATOON
            |--------------------------------------------------------------------------
            */

            $stmt = $db->prepare("
                UPDATE platoons
                SET
                    platoon_name = ?,
                    platoon_code = ?,
                    status = ?
                WHERE id = ?
            ");

            $stmt->execute([
                $platoonName,
                $platoonCode,
                $status,
                $platoonId
            ]);

            $_SESSION['success_message'] =
                "Platoon updated successfully.";

            header("Location: platoons.php");
            exit;
        }


        /*
        |--------------------------------------------------------------------------
        | DELETE PLATOON
        |--------------------------------------------------------------------------
        */

        if ($action === 'delete') {

            $platoonId = (int) ($_POST['platoon_id'] ?? 0);

            if ($platoonId <= 0) {
                throw new Exception(
                    "Invalid platoon selected."
                );
            }


            /*
            |--------------------------------------------------------------------------
            | CHECK ASSIGNED CORPS MEMBERS
            |--------------------------------------------------------------------------
            */

            $memberStmt = $db->prepare("
                SELECT COUNT(*)
                FROM corps_members
                WHERE platoon_id = ?
            ");

            $memberStmt->execute([
                $platoonId
            ]);

            $memberCount = (int) $memberStmt->fetchColumn();

            if ($memberCount > 0) {
                throw new Exception(
                    "This platoon cannot be deleted because Corps Members are currently assigned to it."
                );
            }


            /*
            |--------------------------------------------------------------------------
            | DELETE
            |--------------------------------------------------------------------------
            */

            $stmt = $db->prepare("
                DELETE FROM platoons
                WHERE id = ?
            ");

            $stmt->execute([
                $platoonId
            ]);

            $_SESSION['success_message'] =
                "Platoon deleted successfully.";

            header("Location: platoons.php");
            exit;
        }

    } catch (Throwable $e) {

        $_SESSION['error_message'] =
            $e->getMessage();

        header("Location: platoons.php");
        exit;
    }
}


/*
|--------------------------------------------------------------------------
| FETCH PLATOONS
|--------------------------------------------------------------------------
*/

$platoonsStmt = $db->query("
    SELECT
        p.*,
        COUNT(cm.id) AS total_members

    FROM platoons p

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

    GROUP BY
        p.id

    ORDER BY p.id DESC
");

$platoons = $platoonsStmt->fetchAll(
    PDO::FETCH_ASSOC
);

/*
|--------------------------------------------------------------------------
| FETCH ALL CORPS MEMBERS
|--------------------------------------------------------------------------
|
| Used by the View Members Modal
|
|--------------------------------------------------------------------------
*/

$membersStmt = $db->query("

SELECT

    cm.id,

    cm.firstname,

    cm.lastname,

    cm.othername,

    cm.state_code,

    cm.phone,

    cm.gender,

    cm.status,

    cm.platoon_id,

    p.platoon_name

FROM corps_members cm

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

ORDER BY
cm.firstname ASC

");

$members = $membersStmt->fetchAll(PDO::FETCH_ASSOC);


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

?>

<style>
.my-sidebar,
.edit-sidebar {

    position: fixed;

    top: 0;

    right: -500px;

    width: 480px;

    height: 100vh;

    background: #fff;

    z-index: 9999;

    transition: .35s;

    overflow-y: auto;

    box-shadow: -4px 0 20px rgba(0, 0, 0, .15);

}

.my-sidebar.active,
.edit-sidebar.active {

    right: 0;

}

.overlay {

    position: fixed;

    top: 0;

    left: 0;

    width: 100%;

    height: 100%;

    background: rgba(0, 0, 0, .45);

    z-index: 9998;

    display: none;

}

.overlay.active {

    display: block;

}
</style>


<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 ?>
                    >
                    Camp Management
                    >
                    <?= htmlspecialchars($pageTitle) ?>
                </p>

            </div>


            <button type="button" class="my-sidebar-btn btn btn-primary-600 d-flex align-items-center gap-2">

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

                Add Platoon

            </button>

        </div>


        <!-- ============================================== -->
        <!-- ALERTS -->
        <!-- ============================================== -->

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

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

            <?= htmlspecialchars($successMessage) ?>

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

        </div>

        <?php endif; ?>


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

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

            <?= htmlspecialchars($errorMessage) ?>

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

        </div>

        <?php endif; ?>


        <!-- ============================================== -->
        <!-- PLATOON TABLE -->
        <!-- ============================================== -->

        <div class="mt-24">

            <div class="card h-100">

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


                    <!-- TABLE HEADER -->

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


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

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

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

                                        Export

                                    </span>

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

                                </button>


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

                                    <li>

                                        <button type="button" class="dropdown-item px-16 py-8 rounded">

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

                                            PDF

                                        </button>

                                    </li>


                                    <li>

                                        <button type="button" class="dropdown-item px-16 py-8 rounded">

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

                                            Excel

                                        </button>

                                    </li>

                                </ul>

                            </div>


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

                                <input type="text" class="dt-input bg-transparent radius-4" aria-controls="dataTable"
                                    placeholder="Search...">

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

                            </form>

                        </div>


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

                            <span>
                                Rows per page:
                            </span>

                            <div class="dt-length">

                                <select name="dataTable_length" aria-controls="dataTable"
                                    class="dt-input form-control form-select">

                                    <option value="5">5</option>

                                    <option value="10" selected>10</option>

                                    <option value="25">25</option>

                                    <option value="50">50</option>

                                    <option value="100">100</option>

                                </select>

                            </div>

                        </div>

                    </div>


                    <!-- TABLE -->

                    <div class="p-0">

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

                            <thead>
                                <tr>

                                    <th>S/L</th>

                                    <th>Name</th>

                                    <th>Code No</th>

                                    <th>Members</th>

                                    <th>Status</th>
                                    <th>Created on</th>

                                    <th>Action</th>

                                </tr>
                            </thead>


                            <tbody>

                                <?php if(empty($platoons)): ?>

                                <tr>

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

                                        No platoons found.

                                    </td>

                                </tr>

                                <?php endif; ?>


                                <?php foreach($platoons as $index=>$platoon): ?>

                                <tr>

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

                                    <td>

                                        <strong>

                                            <?= htmlspecialchars($platoon['platoon_name']) ?>

                                        </strong>

                                    </td>

                                    <td>

                                        <?= htmlspecialchars($platoon['platoon_code']) ?>

                                    </td>

                                    <td>

                                        <span class="badge bg-info">

                                            <?= $platoon['total_members'] ?>

                                            Members

                                        </span>

                                    </td>

                                    <td>

                                        <?php if($platoon['status']=="Active"): ?>

                                        <span class="badge bg-success">

                                            Active

                                        </span>

                                        <?php else: ?>

                                        <span class="badge bg-danger">

                                            Inactive

                                        </span>

                                        <?php endif; ?>

                                    </td>

                                    <td>

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

                                    </td>

                                    <td>

                                        <div class="btn-group">

                                            <button class="text-primary-light text-xl" data-bs-toggle="dropdown">

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

                                                </iconify-icon>

                                            </button>

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

                                                <li>

                                                    <button class="dropdown-item view-platoon-btn"
                                                        data-id="<?= $platoon['id'] ?>"
                                                        data-name="<?= htmlspecialchars($platoon['platoon_name']) ?>"
                                                        data-code="<?= htmlspecialchars($platoon['platoon_code']) ?>"
                                                        data-status="<?= $platoon['status'] ?>"
                                                        data-members="<?= $platoon['total_members'] ?>"
                                                        data-created="<?= date('d M Y',strtotime($platoon['created_at'])) ?>"
                                                        data-bs-toggle="modal" data-bs-target="#viewPlatoonModal">

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

                                                        View

                                                    </button>

                                                </li>

                                                <li>

                                                    <button class="dropdown-item view-members-btn"
                                                        data-id="<?= $platoon['id'] ?>"
                                                        data-name="<?= htmlspecialchars($platoon['platoon_name']) ?>"
                                                        data-bs-toggle="modal" data-bs-target="#viewMembersModal">

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

                                                        View Members

                                                    </button>

                                                </li>

                                                <li>

                                                    <button class="dropdown-item edit-sidebar-btn"
                                                        data-id="<?= $platoon['id'] ?>"
                                                        data-name="<?= htmlspecialchars($platoon['platoon_name']) ?>"
                                                        data-code="<?= htmlspecialchars($platoon['platoon_code']) ?>"
                                                        data-status="<?= $platoon['status'] ?>">

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

                                                        Edit

                                                    </button>

                                                </li>

                                                <li>

                                                    <button class="dropdown-item text-danger delete-platoon-btn"
                                                        data-id="<?= $platoon['id'] ?>"
                                                        data-name="<?= htmlspecialchars($platoon['platoon_name']) ?>"
                                                        data-bs-toggle="modal" data-bs-target="#deleteModal">

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

                                                        Delete

                                                    </button>

                                                </li>

                                            </ul>

                                        </div>

                                    </td>

                                </tr>

                                <?php endforeach; ?>

                            </tbody>


                        </table>

                    </div>

                </div>

            </div>

        </div>


    </div>

    <!-- ====================== View Members of Platoon ======================== -->
    <div class="modal fade" id="viewMembersModal" tabindex="-1">

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

            <div class="modal-content">

                <div class="modal-header">

                    <h5 id="membersTitle">

                        Platoon Members

                    </h5>

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

                    </button>

                </div>

                <div class="modal-body">

                    <table class="table table-bordered">

                        <thead>

                            <tr>

                                <th>#</th>

                                <th>State Code</th>

                                <th>Name</th>

                                <th>Gender</th>

                                <th>Phone</th>

                                <th>Status</th>

                            </tr>

                        </thead>

                        <tbody id="membersBody">

                        </tbody>

                    </table>

                </div>

            </div>

        </div>

    </div>

    <!-- ================= ADD PLATOON SIDEBAR ================= -->

    <div class="my-sidebar">

        <div class="p-24 border-bottom d-flex justify-content-between align-items-center">

            <h5 class="mb-0">
                Add Platoon
            </h5>

            <button type="button" class="close-my-sidebar btn btn-light">
                <i class="ri-close-line"></i>
            </button>

        </div>

        <form method="POST">

            <input type="hidden" name="action" value="add">

            <div class="p-24">

                <div class="mb-20">

                    <label class="form-label">
                        Platoon Name <span class="text-danger">*</span>
                    </label>

                    <input type="text" name="platoon_name" class="form-control" required>

                </div>

                <div class="mb-20">

                    <label class="form-label">
                        Platoon Code <span class="text-danger">*</span>
                    </label>

                    <input type="text" name="platoon_code" class="form-control" required>

                </div>

                <div class="mb-20">

                    <label class="form-label">
                        Status
                    </label>

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

                        <option value="Active">
                            Active
                        </option>

                        <option value="Inactive">
                            Inactive
                        </option>

                    </select>

                </div>

            </div>

            <div class="p-24 border-top">

                <button class="btn btn-primary w-100">

                    Save Platoon

                </button>

            </div>

        </form>

    </div>

    <!-- ================= EDIT PLATOON SIDEBAR ================= -->

    <div class="edit-sidebar">

        <div class="p-24 border-bottom d-flex justify-content-between align-items-center">

            <h5 class="mb-0">

                Edit Platoon

            </h5>

            <button class="close-edit-sidebar btn btn-light">

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

            </button>

        </div>

        <form method="POST">

            <input type="hidden" name="action" value="edit">

            <input type="hidden" id="editPlatoonId" name="platoon_id">

            <div class="p-24">

                <div class="mb-20">

                    <label>

                        Platoon Name

                    </label>

                    <input id="editPlatoonName" name="platoon_name" class="form-control" required>

                </div>

                <div class="mb-20">

                    <label>

                        Platoon Code

                    </label>

                    <input id="editPlatoonCode" name="platoon_code" class="form-control" required>

                </div>

                <div class="mb-20">

                    <label>

                        Status

                    </label>

                    <select id="editPlatoonStatus" name="status" class="form-select">

                        <option value="Active">

                            Active

                        </option>

                        <option value="Inactive">

                            Inactive

                        </option>

                    </select>

                </div>

            </div>

            <div class="p-24 border-top">

                <button class="btn btn-success w-100">

                    Update Platoon

                </button>

            </div>

        </form>

    </div>


    <div class="modal fade" id="deleteModal">

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

            <div class="modal-content">

                <div class="modal-header">

                    <h5>

                        Delete Platoon

                    </h5>

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

                    </button>

                </div>

                <form method="POST">

                    <input type="hidden" name="action" value="delete">

                    <input type="hidden" name="platoon_id" id="deletePlatoonId">

                    <div class="modal-body">

                        <p>

                            Are you sure you want to delete

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

                        </p>

                        <p class="text-danger">

                            This action cannot be undone.

                        </p>

                    </div>

                    <div class="modal-footer">

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

                            Cancel

                        </button>

                        <button class="btn btn-danger">

                            Delete Platoon

                        </button>

                    </div>

                </form>

            </div>

        </div>

    </div>

    <div class="modal fade" id="viewPlatoonModal">

        <div class="modal-dialog">

            <div class="modal-content">

                <div class="modal-header">

                    <h5>

                        Platoon Details

                    </h5>

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

                    </button>

                </div>

                <div class="modal-body">

                    <table class="table">

                        <tr>

                            <th width="40%">

                                Platoon Name

                            </th>

                            <td id="viewName"></td>

                        </tr>

                        <tr>

                            <th>

                                Platoon Code

                            </th>

                            <td id="viewCode"></td>

                        </tr>

                        <tr>

                            <th>

                                Status

                            </th>

                            <td id="viewStatus"></td>

                        </tr>

                        <tr>

                            <th>

                                Members

                            </th>

                            <td id="viewMembers"></td>

                        </tr>

                        <tr>

                            <th>

                                Created

                            </th>

                            <td id="viewCreated"></td>

                        </tr>

                    </table>

                </div>

            </div>

        </div>

    </div>




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

    <script>
    $(function() {

        /*
        |--------------------------------------------------------------------------
        | EDIT
        |--------------------------------------------------------------------------
        */

        $('.edit-sidebar-btn').click(function() {

            $('#editPlatoonId').val($(this).data('id'));

            $('#editPlatoonName').val($(this).data('name'));

            $('#editPlatoonCode').val($(this).data('code'));

            $('#editPlatoonStatus').val($(this).data('status'));

            $('.edit-sidebar').addClass('active');

            $('.overlay').addClass('active');

        });

        $('.close-edit-sidebar').click(function() {

            $('.edit-sidebar').removeClass('active');

            $('.overlay').removeClass('active');

        });


        /*
        |--------------------------------------------------------------------------
        | DELETE
        |--------------------------------------------------------------------------
        */

        $('.delete-platoon-btn').click(function() {

            $('#deletePlatoonId').val($(this).data('id'));

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

        });


        /*
        |--------------------------------------------------------------------------
        | VIEW
        |--------------------------------------------------------------------------
        */

        $('.view-platoon-btn').click(function() {

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

            $('#viewCode').text($(this).data('code'));

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

            $('#viewMembers').text($(this).data('members'));

            $('#viewCreated').text($(this).data('created'));

        });

        /*
        |--------------------------------------------------------------------------
        | VIEW MEMBERS
        |--------------------------------------------------------------------------
        */


        const members = <?= json_encode($members) ?>;

        $('.view-members-btn').click(function() {

            let platoonId = $(this).data('id');

            let platoonName = $(this).data('name');

            $('#membersTitle').text(
                platoonName + ' Members'
            );

            let html = '';

            let count = 1;

            members.forEach(function(member) {

                if (member.platoon_id == platoonId) {

                    html += `

            <tr>

                <td>${count++}</td>

                <td>${member.state_code}</td>

                <td>

                    ${member.firstname}

                    ${member.lastname}

                </td>

                <td>${member.gender ?? ''}</td>

                <td>${member.phone ?? ''}</td>

                <td>

                    <span class="badge bg-success">

                        ${member.status}

                    </span>

                </td>

            </tr>

            `;

                }

            });

            if (html === '') {

                html =

                    `<tr>

            <td colspan="6"

            class="text-center">

                No Corps Members have been assigned to this platoon.

            </td>

        </tr>`;

            }

            $('#membersBody').html(html);

        });

    });
    </script>