<?php
include('include/auth.php');
include('include/lskfjwfe.php'); // Database connectivity file

if (!isset($_GET['category_id']) || empty($_GET['category_id'])) {
    die("Invalid request.");
}

$category_id = intval($_GET['category_id']);
?>

<!doctype html>
<html class="fixed dark">
<?php 
    $pagerole = "vehicles";
    include('include/head.php');
?>

<body>
    <section class="body">

        <!-- start: header -->
        <header class="header">
            <div class="logo-container">
                <a href="index.php" class="logo">
                    <img src="img/logo-light.png" width="75" height="35" alt="Web Voyage" />
                </a>
                <div class="d-md-none toggle-sidebar-left" data-toggle-class="sidebar-left-opened" data-target="html"
                    data-fire-event="sidebar-left-opened">
                    <i class="fas fa-bars" aria-label="Toggle sidebar"></i>
                </div>
            </div>

            <div class="header-right">
                <?php include('include/search.php'); ?>
                <span class="separator"></span>
                <?php include('include/notifications.php'); ?>
                <span class="separator"></span>
                <?php include('include/userbox.php'); ?>
            </div>
        </header>
        <!-- end: header -->

        <div class="inner-wrapper">
            <!-- start: sidebar -->
            <?php include('include/nav.php'); ?>
            <!-- end: sidebar -->

            <section role="main" class="content-body">
                <header class="page-header">
                    <h2>Vehicles in Category</h2>
                    <div class="right-wrapper text-right">
                        <ol class="breadcrumbs">
                            <li>
                                <a href="index.php"><i class="fas fa-home"></i></a>
                            </li>
                            <li>
                                <a href="categories.php">Categories</a>
                            </li>
                            <li><span>Vehicles</span></li>
                        </ol>
                        <a class="sidebar-right-toggle" data-open="sidebar-right"><i
                                class="fas fa-chevron-left"></i></a>
                    </div>
                </header>

                <?php if ($userrole == 2) { echo "You do not have permissions for this operation."; } else { ?>

                <div class="row">
                    <div class="col">
                        <section class="card">
                            <header class="card-header">
                                <h2 class="card-title">Vehicles in Category</h2>
                                <div class="text-right">
    <a href="#" class="btn btn-primary" onclick="openAddVehicleModal(<?= $category_id; ?>)">
        <i class="fas fa-plus"></i> Add Vehicle
    </a>
</div>

                            </header>

                            <div class="card-body">
                                <table class="table table-bordered table-striped mb-0" id="datatable-tabletools">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>Name</th>
                                            <th>Actions</th>
                                           
                                        </tr>
                                    </thead>
                                   <tbody>
    <?php
    $sql = "SELECT * FROM jostj_vikrentcar_cars WHERE 
            idcat = '$category_id' OR 
            idcat LIKE '$category_id;%' OR 
            idcat LIKE '%;$category_id' OR 
            idcat LIKE '%;$category_id;%'";
    $result = mysqli_query($db2, $sql);
    ?>

    <?php if (!$result): ?>
        <tr>
            <td colspan="4">Error fetching vehicles: <?= mysqli_error($db2); ?></td>
        </tr>
    <?php else: ?>
        <?php while ($row = mysqli_fetch_assoc($result)) : ?>
            <tr>
                <td class="text-center"><?= $row['id']; ?></td>
                <td class="text-center"><?= htmlspecialchars($row['name']); ?></td>
                <td class="actions">
                    <!-- Edit Vehicle Categories -->
                    <a href="#" class="on-default edit-row" onclick="openEditIdcatModal('<?= $row['id']; ?>', '<?= $row['idcat']; ?>')">
                        <i class="fas fa-pencil-alt"></i>
                    </a>

                    <!-- Remove Vehicle from Category -->
                    <a href="#" class="on-default delete-row text-danger" onclick="removeVehicleFromCategory(<?= $row['id']; ?>, <?= $category_id; ?>)">
                        <i class="fas fa-times"></i>
                    </a>
                </td>
            </tr>
        <?php endwhile; ?>
    <?php endif; ?>
</tbody>


                                </table>
                            </div>

                            <footer class="card-footer text-right">
                                <a href="categories.php" class="btn btn-default">Back to Categories</a>
                            </footer>
                        </section>
                    </div>
                </div>
                <?php } ?>
            </section>
        </div>

        <?php include('include/aside.php'); ?>

    </section>

    <!-- Vendor -->
    <script src="vendor/jquery/jquery.js"></script>
    <script src="vendor/jquery-browser-mobile/jquery.browser.mobile.js"></script>
    <script src="vendor/popper/umd/popper.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.js"></script>
    <script src="vendor/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
    <script src="vendor/common/common.js"></script>
    <script src="vendor/nanoscroller/nanoscroller.js"></script>
    <script src="vendor/magnific-popup/jquery.magnific-popup.js"></script>
    <script src="vendor/jquery-placeholder/jquery.placeholder.js"></script>

    <!-- Specific Page Vendor -->
    <script src="vendor/datatables/media/js/jquery.dataTables.min.js"></script>
    <script src="vendor/datatables/media/js/dataTables.bootstrap4.min.js"></script>
    <script src="vendor/datatables/extras/TableTools/Buttons-1.4.2/js/dataTables.buttons.min.js"></script>
    <script src="vendor/datatables/extras/TableTools/Buttons-1.4.2/js/buttons.bootstrap4.min.js"></script>
    <script src="vendor/datatables/extras/TableTools/Buttons-1.4.2/js/buttons.html5.min.js"></script>
    <script src="vendor/datatables/extras/TableTools/Buttons-1.4.2/js/buttons.print.min.js"></script>
    <script src="vendor/datatables/extras/TableTools/JSZip-2.5.0/jszip.min.js"></script>
    <script src="vendor/datatables/extras/TableTools/pdfmake-0.1.32/pdfmake.min.js"></script>
    <script src="vendor/datatables/extras/TableTools/pdfmake-0.1.32/vfs_fonts.js"></script>

    <!-- Theme Base, Components and Settings -->
    <script src="js/theme.js"></script>

    <!-- Theme Custom -->
    <script src="js/custom.js"></script>

    <!-- Theme Initialization Files -->
    <script src="js/theme.init.js"></script>

    <!-- Examples -->
    <script src="js/examples/examples.datatables.default.js"></script>
<!-- Edit IDCAT Modal -->
<div id="modalEditIdcat" class="modal-block modal-block-primary mfp-hide">
    <section class="card">
        <header class="card-header">
            <h2 class="card-title">Edit Vehicle Category</h2>
        </header>
        <div class="card-body">
            <form method="post" action="actions/update_idcat.php">
                <div class="modal-wrapper">
                    <div class="modal-icon">
                        <i class="fas fa-edit"></i>
                    </div>
                    <div class="modal-text">
                        <div class="form-group">
                            <label for="new_idcat">Select New Subcategory</label>
                            <select class="form-control" name="new_subcategory_id" id="new_subcategory_id" required>
                                <?php
                                $categories_query = "SELECT id, name FROM jostj_vikrentcar_categories";
                                $categories_result = mysqli_query($db2, $categories_query);
                                while ($category = mysqli_fetch_assoc($categories_result)) {
                                    echo "<option value='{$category['id']}'>{$category['name']}</option>";
                                }
                                ?>
                            </select>
                        </div>
                    </div>
                </div>
                <input type="hidden" name="vehicle_id" id="vehicle_id">
                <input type="hidden" name="current_idcat" id="current_idcat">
        </div>
        <footer class="card-footer">
            <div class="row">
                <div class="col-md-12 text-right">
                    <button class="btn btn-primary" type="submit">Save Changes</button>
                    <button class="btn btn-default modal-dismiss">Cancel</button>
                </div>
            </div>
        </footer>
        </form>
    </section>
</div>
<!-- Add Vehicle to Category Modal -->
<div id="addVehicleModal" class="modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Vehicle to Category</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <form id="addVehicleForm">
                    <input type="hidden" id="categoryId" name="category_id" value="<?= $category_id; ?>">

                    <!-- Vehicle Selection -->
                    <div class="form-group">
                        <label for="vehicleId">Select Vehicle:</label>
                        <select id="vehicleId" name="vehicle_id" class="form-control">
                            <option value="">-- Select a Vehicle --</option>
                            <?php
                            $vehicle_query = "SELECT id, name FROM jostj_vikrentcar_cars ORDER BY name";
                            $vehicle_result = mysqli_query($db2, $vehicle_query);
                            while ($vehicle = mysqli_fetch_assoc($vehicle_result)) {
                                echo "<option value='{$vehicle['id']}'>{$vehicle['name']} (ID: {$vehicle['id']})</option>";
                            }
                            ?>
                        </select>
                    </div>

                    <button type="button" class="btn btn-primary" onclick="submitAddVehicle()">Add Vehicle</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    function openEditIdcatModal(vehicleId, currentIdcat) {
        $('#vehicle_id').val(vehicleId);
        $('#current_idcat').val(currentIdcat);

        // Extract the subcategory ID (second part of idcat)
        const subcategoryId = currentIdcat.split(';')[1];
        $('#new_subcategory_id').val(subcategoryId);

        $.magnificPopup.open({
            items: {
                src: '#modalEditIdcat'
            },
            type: 'inline'
        });
    }
    function removeVehicleFromCategory(vehicleId, categoryId) {
    if (!confirm("Are you sure you want to remove this vehicle from the category?")) {
        return;
    }

    $.ajax({
        url: "actions/remove_vehicle_from_category.php",  // Using the same file
        type: "POST",
        data: { vehicle_id: vehicleId, category_id: categoryId },
        success: function(response) {
            alert(response);
            location.reload();
        },
        error: function() {
            alert("Error processing request.");
        }
    });
}
function openAddVehicleModal(categoryId) {
    document.getElementById("categoryId").value = categoryId;
    $("#addVehicleModal").modal("show");
}

function submitAddVehicle() {
    var categoryId = document.getElementById("categoryId").value;
    var vehicleId = document.getElementById("vehicleId").value;

    if (!vehicleId) {
        alert("Please select a vehicle.");
        return;
    }

    $.ajax({
        url: "actions/add_vehicle_to_category.php", // Using the same file
        type: "POST",
        data: { category_id: categoryId, vehicle_id: vehicleId },
        success: function(response) {
            alert(response);
            $("#addVehicleModal").modal("hide");
            location.reload();
        },
        error: function() {
            alert("Error processing request.");
        }
    });
}


</script>

</body>
</html>
