<?php
session_start();
error_reporting(0);
include('includes/config.php');

if (strlen($_SESSION['alogin']) == 0) {
    header('location:index.php');
    exit;
}
// Fetch distinct cupboards
$sqlCup = "
    SELECT DISTINCT 
        CASE 
            WHEN rack_no IS NULL OR rack_no = '' THEN 'No Cupboard'
            ELSE rack_no
        END AS rack_no
    FROM tbl_racks
    ORDER BY rack_no ASC
";
$queryCup = $dbh->prepare($sqlCup);
$queryCup->execute();
$cupboards = $queryCup->fetchAll(PDO::FETCH_OBJ);

// Default cupboard = first one
// $defaultCupboard = $cupboards[0]->rack_no ?? '';
// ✅ Delete Rack (server-side redirect, same as your other pages)
if (isset($_GET['del'])) {
    $id = intval($_GET['del']);
    $sql = "DELETE FROM tbl_racks WHERE id = :id";
    $query = $dbh->prepare($sql);
    $query->bindParam(':id', $id, PDO::PARAM_INT);
    $query->execute();
    $_SESSION['delmsg'] = "Cupboard deleted successfully";
    header('location:manage-racks.php');
    exit;
}
$selectedCupboard = $_GET['cupboard'] ?? ($cupboards[0]->rack_no ?? '');

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title>Manage Cupboards | Library System</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="icon" type="image/x-icon" href="../<?php echo $_SESSION['logo']; ?>">

    <!-- ✅ Bootstrap 5 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- ✅ DataTables Bootstrap 5 -->
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">

    <!-- ✅ FontAwesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">

    <style>
        .square-card {
            width: 100%;
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
            border-radius: 5px;
        }

        .flash-message {
            max-width: 600px;
            margin: 0 auto 15px;
        }

        .table-wrapper {
            overflow-x: auto;
            padding: 10px;
        }

        .col-md-12 h5 {
            color: #0d6efd;
            font-size: 20px;
        }

        .btn+.btn {
            margin-left: 5px;
        }
    </style>
</head>

<body>
    <div class="d-flex flex-column min-vh-100">
        <?php include('includes/header.php'); ?>

        <div class="main-content flex-grow-1">
            <div class="row pad-botm mb-4">
                <div class="col-md-12">
                    <h5 class="header-line" style="color:#0d6efd;">MANAGE BOOK CUPBOARDS</h5>
                </div>
            </div>
            <div class="row mb-3">
                <div class="col-md-4">
                    <label class="fw-bold">Filter by Cupboard</label>
                    <select id="cupboardFilter" class="form-select">
                        <?php foreach ($cupboards as $cup): ?>
                            <option value="<?= htmlentities($cup->rack_no) ?>" <?= ($cup->rack_no === $selectedCupboard) ? 'selected' : '' ?>>
                                <?= htmlentities($cup->rack_no) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>

                </div>
            </div>

            <!-- ✅ Flash Messages -->
            <div class="row justify-content-center">
                <div class="col-md-8" id="flash-container">
                    <?php
                    foreach (['error', 'msg', 'updatemsg', 'delmsg'] as $type):
                        if (!empty($_SESSION[$type])): ?>
                            <div class="alert alert-<?php echo ($type == 'error') ? 'danger' : 'success'; ?> flash-message">
                                <strong><?php echo ucfirst($type); ?> :</strong> <?php echo htmlentities($_SESSION[$type]); ?>
                            </div>
                            <?php $_SESSION[$type] = ""; ?>
                        <?php endif; endforeach; ?>
                </div>
            </div>

            <!-- ✅ Racks Table -->
            <div class="card square-card mb-5">
                <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
                    <span><i class="fa fa-table-list me-2"></i> Cupboards List</span>
                    <button class="btn btn-light btn-sm text-dark shadow-sm rounded-pill px-3"
                        onclick="openRackModal()">
                        <i class="fa fa-plus-circle"></i><b> ADD</b>
                    </button>
                </div>

                <div class="card-body table-wrapper">
                    <table id="racksTable" class="table table-bordered table-hover table-sm text-dark">
                        <thead class="table-theme-header">
                            <tr>
                                <th>#</th>
                                <th>Cupboard Number</th>
                                <th>Shelf Number</th>
                                <th>Book Number</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            if ($selectedCupboard === 'No Cupboard') {
                                $sql = "SELECT * FROM tbl_racks 
            WHERE rack_no IS NULL OR rack_no = '' 
            ORDER BY id DESC";
                                $query = $dbh->prepare($sql);
                            } else {
                                $sql = "SELECT * FROM tbl_racks 
            WHERE rack_no = :rack_no 
            ORDER BY id DESC";
                                $query = $dbh->prepare($sql);
                                $query->bindParam(':rack_no', $selectedCupboard, PDO::PARAM_STR);
                            }

                            $query->execute();
                            $results = $query->fetchAll(PDO::FETCH_OBJ);


                            $cnt = 1;
                            // if ($query->rowCount() > 0) {
                            foreach ($results as $result) { ?>
                                <tr>
                                    <td><?= htmlentities($cnt++) ?></td>
                                    <td><?= htmlentities($result->rack_no ?: 'No Cupboard') ?></td>
                                    <td><?= htmlentities($result->shelf_no) ?></td>
                                    <td><?= htmlentities($result->floor) ?></td>
                                    <td>
                                        <button class="btn btn-sm btn-info" onclick="editRack(<?= $result->id ?>,'<?= htmlentities($result->rack_no ?? '') ?>'
,'<?= htmlentities($result->shelf_no) ?>','<?= htmlentities($result->floor) ?>')">
                                            <i class="fa fa-edit"></i> Edit
                                        </button>
                                        <!-- <a href="manage-racks.php?del=<?= $result->id ?>"
                                       onclick="return confirm('Are you sure you want to delete this rack?');"
                                       class="btn btn-sm btn-danger">
                                        <i class="fa fa-trash"></i> Delete
                                    </a> -->
                                    </td>
                                </tr>
                                <?php
                                //      }
                                // } else {
                                //     echo "<tr><td colspan='5' class='text-center text-muted'>No racks found</td></tr>";
                            } ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- ✅ Rack Modal -->
            <div class="modal fade" id="rackModal" tabindex="-1" role="dialog">
                <div class="modal-dialog modal-dialog-centered modal-md">
                    <div class="modal-content">
                        <div class="modal-header bg-primary text-white">
                            <h5 class="modal-title" id="rackModalTitle">Add Cupboard</h5>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                        </div>
                        <form id="rackForm">
                            <div class="modal-body">
                                <input type="hidden" id="rackId" name="rackId">
                                <div class="form-group mb-3">
                                    <label>Cupboard Number</label>
                                    <input type="text" id="rackNo" name="rackNo" class="form-control" required>
                                </div>
                                <div class="form-group mb-3">
                                    <label>Shelf Number</label>
                                    <input type="text" id="shelfNo" name="shelfNo" class="form-control" required>
                                </div>
                                <div class="form-group mb-3">
                                    <label>Book Number</label>
                                    <input type="text" id="floor" name="floor" class="form-control" required>
                                </div>
                            </div>
                            <div class="modal-footer justify-content-center py-2">
                                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">
                                    <i class="fa fa-times"></i> Cancel
                                </button>
                                <button type="submit" id="saveBtn" class="btn btn-success btn-sm">
                                    <i class="fa fa-save"></i> Save
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

        </div>
    </div>

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

    <!-- ✅ Scripts -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>

    <script>
        $(document).ready(function () {
            var table = $('#racksTable').DataTable({
                pageLength: 10,
                responsive: true,
                language: { search: "🔍 Search" }
            });

            $('#cupboardFilter').on('change', function () {
                let cup = $(this).val();
                window.location.href = "manage-racks.php?cupboard=" + encodeURIComponent(cup);
            });

        });



        // ✅ Open Add Modal
        function openRackModal() {
            $("#rackModalTitle").text("Add Rack");
            $("#rackForm")[0].reset();
            $("#rackId").val("");
            const modal = new bootstrap.Modal(document.getElementById("rackModal"));
            modal.show();
        }

        // ✅ Open Edit Modal
        function editRack(id, rackNo, shelfNo, floor) {
            $("#rackModalTitle").text("Edit Rack");
            $("#rackId").val(id);
            $("#rackNo").val(rackNo);
            $("#shelfNo").val(shelfNo);
            $("#floor").val(floor);
            const modal = new bootstrap.Modal(document.getElementById("rackModal"));
            modal.show();
        }

        // ✅ AJAX: Save / Update Rack
        $("#rackForm").on("submit", function (e) {
            e.preventDefault();

            $.ajax({
                url: "save-rack.php",
                type: "POST",
                data: $(this).serialize(),
                dataType: "json",
                success: function (response) {
                    // Remove existing flash messages
                    $("#flash-container .flash-message").remove();

                    // Choose alert type
                    let alertType = response.status === "success" ? "success" : "danger";

                    // Add new flash message
                    $("#flash-container").prepend(`
                <div class="alert alert-${alertType} flash-message text-center">
                    <strong>${response.status === "success" ? "Success!" : "Error!"}</strong> ${response.message}
                </div>
            `);

                    // Auto hide flash after 3s
                    setTimeout(() => $(".flash-message").fadeOut(), 3000);

                    // Close modal & reload on success
                    if (response.status === "success") {
                        $("#rackModal").modal("hide");
                        setTimeout(() => location.reload(), 1500);
                    }
                },
                error: function () {
                    $("#flash-container .flash-message").remove();
                    $("#flash-container").prepend(`
                <div class="alert alert-danger flash-message text-center">
                    ⚠️ Something went wrong! Please try again.
                </div>
            `);
                    setTimeout(() => $(".flash-message").fadeOut(), 3000);
                }
            });
        });
    </script>

</body>

</html>