<?php

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/csrf.php';

if (($_SESSION['role'] ?? '') !== 'admin') {
    header('Location: ' . BASE_URL . 'dashboard.php');
    exit();
}

$equipmentStatement = mysqli_prepare(
    $conn,
    'SELECT em.id, em.equipment_name, em.display_order, em.status,
            GROUP_CONCAT(ue.unit_id ORDER BY ue.unit_id) AS unit_ids,
            GROUP_CONCAT(um.unit_name ORDER BY um.display_order, um.unit_name SEPARATOR ", ") AS unit_names
     FROM equipment_master em
     LEFT JOIN unit_equipment ue ON ue.equipment_id = em.id
     LEFT JOIN unit_master um ON um.id = ue.unit_id
     GROUP BY em.id, em.equipment_name, em.display_order, em.status
     ORDER BY em.display_order ASC, em.equipment_name ASC'
);
mysqli_stmt_execute($equipmentStatement);
$equipmentRows = mysqli_fetch_all(mysqli_stmt_get_result($equipmentStatement), MYSQLI_ASSOC);
mysqli_stmt_close($equipmentStatement);

if (!$equipmentStatement) {
    die('Unable to load equipment: ' . mysqli_error($conn));
}

$unitStatement = mysqli_prepare(
    $conn,
    'SELECT id, unit_name FROM unit_master WHERE status = ? ORDER BY display_order ASC, unit_name ASC'
);

if (!$unitStatement) {
    die('Unable to load units: ' . mysqli_error($conn));
}


$activeStatus = 'Active';
mysqli_stmt_bind_param($unitStatement, 's', $activeStatus);
mysqli_stmt_execute($unitStatement);
$units = mysqli_fetch_all(mysqli_stmt_get_result($unitStatement), MYSQLI_ASSOC);
mysqli_stmt_close($unitStatement);

include '../includes/header.php';
include '../includes/navbar.php';
?>

<main class="container mt-4">
    <div class="card shadow">
        <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="fa-solid fa-computer"></i> Equipment Management</h5>
            <button type="button" class="btn btn-light btn-sm" id="addEquipmentButton">
                <i class="fa-solid fa-plus"></i> Add Equipment
            </button>
        </div>

        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover align-middle mb-0">
                    <thead class="table-dark">
                        <tr>
                            <th width="60">#</th>
                            <th>Equipment Name</th>
                            <th width="90">Order</th>
                            <th>Assigned Units</th>
                            <th width="110">Status</th>
                            <th width="130">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if ($equipmentRows) { ?>
                        <?php foreach ($equipmentRows as $index => $equipment) { ?>
                            <tr>
                                <td><?= $index + 1 ?></td>
                                <td><?= htmlspecialchars($equipment['equipment_name']) ?></td>
                                <td><?= (int)$equipment['display_order'] ?></td>
                                <td><?= $equipment['unit_names'] ? htmlspecialchars($equipment['unit_names']) : '<span class="text-muted">Not assigned</span>' ?></td>
                                <td>
                                    <span class="badge bg-<?= $equipment['status'] === 'Active' ? 'success' : 'danger' ?>">
                                        <?= htmlspecialchars($equipment['status']) ?>
                                    </span>
                                </td>
                                <td>
                                    <button type="button" class="btn btn-warning btn-sm edit-equipment"
                                        data-id="<?= (int)$equipment['id'] ?>"
                                        data-name="<?= htmlspecialchars($equipment['equipment_name'], ENT_QUOTES) ?>"
                                        data-order="<?= (int)$equipment['display_order'] ?>"
                                        data-status="<?= htmlspecialchars($equipment['status'], ENT_QUOTES) ?>"
                                        data-units="<?= htmlspecialchars($equipment['unit_ids'] ?? '', ENT_QUOTES) ?>">
                                        <i class="fa-solid fa-pen-to-square"></i>
                                    </button>
                                    <button type="button" class="btn btn-danger btn-sm delete-equipment"
                                        data-id="<?= (int)$equipment['id'] ?>"
                                        data-name="<?= htmlspecialchars($equipment['equipment_name'], ENT_QUOTES) ?>">
                                        <i class="fa-solid fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                        <?php } ?>
                    <?php } else { ?>
                        <tr>
                            <td colspan="6" class="text-center text-muted">No equipment found.</td>
                        </tr>
                    <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</main>

<div class="modal fade" id="equipmentModal" tabindex="-1" aria-labelledby="equipmentModalTitle" aria-hidden="true">
    <div class="modal-dialog">
        <form class="modal-content" id="equipmentForm" autocomplete="off">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="equipmentModalTitle">Add Equipment</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="id" id="equipment_id">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">

                <div class="mb-3">
                    <label class="form-label" for="equipment_name">Equipment Name</label>
                    <input type="text" class="form-control" name="equipment_name" id="equipment_name" maxlength="100" required>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="equipment_order">Display Order</label>
                        <input type="number" class="form-control" name="display_order" id="equipment_order" min="1" value="1" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="equipment_status">Status</label>
                        <select class="form-select" name="status" id="equipment_status">
                            <option value="Active">Active</option>
                            <option value="Inactive">Inactive</option>
                        </select>
                    </div>
                </div>

                <label class="form-label">Standard Unit Assignments</label>
                <div class="border rounded p-2">
                    <?php if ($units) { ?>
                        <?php foreach ($units as $unit) { ?>
                            <div class="form-check">
                                <input class="form-check-input unit-assignment" type="checkbox" name="unit_ids[]"
                                    value="<?= (int)$unit['id'] ?>" id="unit_<?= (int)$unit['id'] ?>">
                                <label class="form-check-label" for="unit_<?= (int)$unit['id'] ?>">
                                    <?= htmlspecialchars($unit['unit_name']) ?>
                                </label>
                            </div>
                        <?php } ?>
                    <?php } else { ?>
                        <p class="mb-0 text-muted">No active units are available.</p>
                    <?php } ?>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-success" id="saveEquipmentButton">
                    <i class="fa-solid fa-floppy-disk"></i> Save Equipment
                </button>
            </div>
        </form>
    </div>
</div>


<script src="<?= BASE_URL ?>assets/js/equipment.js?v=<?= urlencode(SYSTEM_VERSION) ?>"></script>

<?php include '../includes/footer.php'; ?>