<?php

$pageTitle = "Hostels";

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

require_login();

$user = current_user();

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

/*
|--------------------------------------------------------------------------
| FLASH MESSAGE
|--------------------------------------------------------------------------
*/

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

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

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

    try {

        /*
        |--------------------------------------------------------------------------
        | ADD HOSTEL
        |--------------------------------------------------------------------------
        */

        if ($action == 'add') {

            $hostelName = trim($_POST['hostel_name']);
            $hostelCode = trim($_POST['hostel_code']);
            $gender = trim($_POST['gender']);
            $capacity = (int)$_POST['capacity'];
            $description = trim($_POST['description']);
            $status = trim($_POST['status']);

            if (
                empty($hostelName) ||
                empty($hostelCode) ||
                empty($gender)
            ) {

                throw new Exception(
                    "Please complete all required fields."
                );
            }

            $check = $db->prepare("
                SELECT id
                FROM hostels
                WHERE hostel_code=?
                LIMIT 1
            ");

            $check->execute([
                $hostelCode
            ]);

            if ($check->fetch()) {

                throw new Exception(
                    "Hostel Code already exists."
                );
            }

            $stmt = $db->prepare("
                INSERT INTO hostels
                (
                    hostel_name,
                    hostel_code,
                    gender,
                    capacity,
                    description,
                    status
                )

                VALUES

                (?,?,?,?,?,?)
            ");

            $stmt->execute([

                $hostelName,

                $hostelCode,

                $gender,

                $capacity,

                $description,

                $status

            ]);

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

            header("Location: hostels.php");

            exit;
        }

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

        if ($action == 'edit') {

            $hostelId = (int)$_POST['hostel_id'];

            $hostelName = trim($_POST['hostel_name']);

            $hostelCode = trim($_POST['hostel_code']);

            $gender = trim($_POST['gender']);

            $capacity = (int)$_POST['capacity'];

            $description = trim($_POST['description']);

            $status = trim($_POST['status']);

            $check = $db->prepare("

                SELECT id

                FROM hostels

                WHERE hostel_code=?

                AND id!=?

            ");

            $check->execute([

                $hostelCode,

                $hostelId

            ]);

            if ($check->fetch()) {

                throw new Exception(
                    "Hostel code already exists."
                );
            }

            $stmt = $db->prepare("

                UPDATE hostels

                SET

                hostel_name=?,

                hostel_code=?,

                gender=?,

                capacity=?,

                description=?,

                status=?

                WHERE id=?

            ");

            $stmt->execute([

                $hostelName,

                $hostelCode,

                $gender,

                $capacity,

                $description,

                $status,

                $hostelId

            ]);

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

            header("Location: hostels.php");

            exit;
        }

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

        if ($action == 'delete') {

            $hostelId = (int)$_POST['hostel_id'];

            $memberCheck = $db->prepare("

                SELECT COUNT(*)

                FROM corps_members

                WHERE hostel_id=?

            ");

            $memberCheck->execute([$hostelId]);

            if ($memberCheck->fetchColumn() > 0) {

                throw new Exception(
                    "Cannot delete hostel because members are assigned."
                );
            }

            $stmt = $db->prepare("

                DELETE FROM hostels

                WHERE id=?

            ");

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

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

            header("Location: hostels.php");

            exit;
        }

    } catch (Throwable $e) {

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

        header("Location: hostels.php");

        exit;
    }
}

/*
|--------------------------------------------------------------------------
| FETCH HOSTELS
|--------------------------------------------------------------------------
*/

$hostelsStmt = $db->query("

SELECT

h.*,

COUNT(cm.id) AS occupants

FROM hostels h

LEFT JOIN corps_members cm

ON cm.hostel_id = h.id

GROUP BY h.id

ORDER BY h.id DESC

");

$hostels = $hostelsStmt->fetchAll(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| FETCH MEMBERS
|--------------------------------------------------------------------------
*/

$membersStmt = $db->query("

SELECT

cm.*,

p.platoon_name

FROM corps_members cm

LEFT JOIN platoons p

ON p.id=cm.platoon_id

ORDER BY firstname

");

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

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

                    >
                    Camp Management
                    >

                    <?= $pageTitle ?>

                </p>

            </div>

            <button class="my-sidebar-btn btn btn-primary-600">

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

                Add Hostel

            </button>

        </div>

        <?php if($successMessage): ?>

        <div class="alert alert-success">

            <?= $successMessage ?>

        </div>

        <?php endif; ?>

        <?php if($errorMessage): ?>

        <div class="alert alert-danger">

            <?= $errorMessage ?>

        </div>

        <?php endif; ?>

        <div class="card">

            <div class="card-body">

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

                    <thead>

                        <tr>

                            <th>#</th>

                            <th>Hostel</th>

                            <th>Code</th>

                            <th>Gender</th>

                            <th>Capacity</th>

                            <th>Occupants</th>

                            <th>Available</th>

                            <th>Status</th>

                            <th>Action</th>

                        </tr>

                    </thead>

                    <tbody>

                        <?php

$count = 1;

foreach($hostels as $hostel):

$available =
$hostel['capacity']
-
$hostel['occupants'];

?>

                        <tr>

                            <td>

                                <?= $count++ ?>

                            </td>

                            <td>

                                <?= htmlspecialchars($hostel['hostel_name']) ?>

                            </td>

                            <td>

                                <?= htmlspecialchars($hostel['hostel_code']) ?>

                            </td>

                            <td>

                                <?= $hostel['gender'] ?>

                            </td>

                            <td>

                                <?= $hostel['capacity'] ?>

                            </td>

                            <td>

                                <?= $hostel['occupants'] ?>

                            </td>

                            <td>

                                <?= $available ?>

                            </td>

                            <td>

                                <?php

                                    if($hostel['status']=="Available"){

                                    ?>

                                <span class="badge bg-success">

                                    Available

                                </span>

                                <?php

                                    }elseif($hostel['status']=="Full"){

                                    ?>

                                <span class="badge bg-warning">

                                    Full

                                </span>

                                <?php

                                    }else {

                                    ?>

                                <span class="badge bg-danger">

                                    Unavailable

                                </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-hostel-btn" data-id="<?= $hostel['id'] ?>"
                                                data-name="<?= htmlspecialchars($hostel['hostel_name']) ?>"
                                                data-code="<?= htmlspecialchars($hostel['hostel_code']) ?>"
                                                data-gender="<?= $hostel['gender'] ?>"
                                                data-capacity="<?= $hostel['capacity'] ?>"
                                                data-description="<?= htmlspecialchars($hostel['description']) ?>"
                                                data-status="<?= $hostel['status'] ?>" data-bs-toggle="modal"
                                                data-bs-target="#viewHostelModal">

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

                                                View

                                            </button>

                                        </li>

                                        <li>

                                            <button class="dropdown-item occupants-btn" data-id="<?= $hostel['id'] ?>">

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

                                                View Occupants

                                            </button>

                                        </li>

                                        <li>

                                            <button class="dropdown-item assign-members-btn"
                                                data-id="<?= $hostel['id'] ?>">

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

                                                Assign Members

                                            </button>

                                        </li>

                                        <li>

                                            <button class="dropdown-item edit-sidebar-btn"
                                                data-id="<?= $hostel['id'] ?>"
                                                data-name="<?= htmlspecialchars($hostel['hostel_name']) ?>"
                                                data-code="<?= htmlspecialchars($hostel['hostel_code']) ?>"
                                                data-gender="<?= $hostel['gender'] ?>"
                                                data-capacity="<?= $hostel['capacity'] ?>"
                                                data-description="<?= htmlspecialchars($hostel['description']) ?>"
                                                data-status="<?= $hostel['status'] ?>">

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

                                                Edit

                                            </button>

                                        </li>

                                        <li>

                                            <button class="dropdown-item delete-hostel-btn"
                                                data-id="<?= $hostel['id'] ?>"
                                                data-name="<?= htmlspecialchars($hostel['hostel_name']) ?>"
                                                data-bs-toggle="modal" data-bs-target="#deleteHostelModal">

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

                                                Delete

                                            </button>

                                        </li>

                                    </ul>

                                </div>

                            </td>

                        </tr>

                        <?php endforeach; ?>

                    </tbody>

                </table>

            </div>

        </div>

    </div>

    <!-- ================= ADD HOSTEL SIDEBAR ================= -->

    <div class="my-sidebar">

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

            <h5 class="mb-0">Add Hostel</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">
                        Hostel Name <span class="text-danger">*</span>
                    </label>

                    <input type="text" name="hostel_name" class="form-control" required>
                </div>

                <div class="mb-20">
                    <label class="form-label">
                        Hostel Code <span class="text-danger">*</span>
                    </label>

                    <input type="text" name="hostel_code" class="form-control" required>
                </div>

                <div class="mb-20">

                    <label class="form-label">

                        Gender

                    </label>

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

                        <option value="Male">Male</option>

                        <option value="Female">Female</option>

                    </select>

                </div>

                <div class="mb-20">

                    <label class="form-label">

                        Capacity

                    </label>

                    <input type="number" name="capacity" class="form-control" value="50">

                </div>

                <div class="mb-20">

                    <label>

                        Description

                    </label>

                    <textarea name="description" class="form-control" rows="3"></textarea>

                </div>

                <div class="mb-20">

                    <label>

                        Status

                    </label>

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

                        <option value="Available">Available</option>

                        <option value="Full">Full</option>
                        <option value="Maintenance">Maintenance</option>

                    </select>

                </div>

            </div>

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

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

                    Save Hostel

                </button>

            </div>

        </form>

    </div>


    <!-- ================= EDIT HOSTEL ================= -->

    <div class="edit-sidebar">

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

            <h5>Edit Hostel</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="editHostelId" name="hostel_id">

            <div class="p-24">

                <div class="mb-20">

                    <label>

                        Hostel Name

                    </label>

                    <input id="editHostelName" name="hostel_name" class="form-control" required>

                </div>

                <div class="mb-20">

                    <label>

                        Hostel Code

                    </label>

                    <input id="editHostelCode" name="hostel_code" class="form-control" required>

                </div>

                <div class="mb-20">

                    <label>

                        Gender

                    </label>

                    <select id="editGender" name="gender" class="form-select">

                        <option value="Male">Male</option>

                        <option value="Female">Female</option>

                    </select>

                </div>

                <div class="mb-20">

                    <label>

                        Capacity

                    </label>

                    <input type="number" id="editCapacity" name="capacity" class="form-control">

                </div>

                <div class="mb-20">

                    <label>

                        Description

                    </label>

                    <textarea id="editDescription" name="description" class="form-control"></textarea>

                </div>

                <div class="mb-20">

                    <label>

                        Status

                    </label>

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

                        <option value="Available">Available</option>

                        <option value="Full">Full</option>
                        <option value="Maintenance">Maintenance</option>

                    </select>

                </div>

            </div>

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

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

                    Update Hostel

                </button>

            </div>

        </form>

    </div>

    <!-- ================= VIEW HOSTEL ================= -->

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

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

            <div class="modal-content">

                <div class="modal-header">

                    <h5>

                        Hostel Details

                    </h5>

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

                    </button>

                </div>

                <div class="modal-body">

                    <table class="table table-bordered">

                        <tr>

                            <th>Hostel</th>

                            <td id="viewHostelName"></td>

                        </tr>

                        <tr>

                            <th>Code</th>

                            <td id="viewHostelCode"></td>

                        </tr>

                        <tr>

                            <th>Gender</th>

                            <td id="viewGender"></td>

                        </tr>

                        <tr>

                            <th>Capacity</th>

                            <td id="viewCapacity"></td>

                        </tr>

                        <tr>

                            <th>Description</th>

                            <td id="viewDescription"></td>

                        </tr>

                        <tr>

                            <th>Status</th>

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

                        </tr>

                    </table>

                </div>

            </div>

        </div>

    </div>


    <!-- ================= DELETE HOSTEL ================= -->

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

        <div class="modal-dialog">

            <div class="modal-content">

                <form method="POST">

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

                    <input type="hidden" id="deleteHostelId" name="hostel_id">

                    <div class="modal-header">

                        <h5>

                            Delete Hostel

                        </h5>

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

                    </div>

                    <div class="modal-body">

                        Delete

                        <strong id="deleteHostelName"></strong>

                        ?

                    </div>

                    <div class="modal-footer">

                        <button class="btn btn-danger">

                            Delete

                        </button>

                    </div>

                </form>

            </div>

        </div>

    </div>

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

    <script>
    $('.close-my-sidebar').click(function() {

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

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

    });

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

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

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

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

        $('#editGender').val($(this).data('gender'));

        $('#editCapacity').val($(this).data('capacity'));

        $('#editDescription').val($(this).data('description'));

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

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

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

    });

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

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

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

        $('#viewGender').text($(this).data('gender'));

        $('#viewCapacity').text($(this).data('capacity'));

        $('#viewDescription').text($(this).data('description'));

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

    });

    $(document).on('click', '.delete-hostel-btn', function() {

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

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

    });

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

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

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

    });

    $('.overlay').click(function() {

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

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

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

    });
    </script>