<?php include('include/auth.php'); 

?>
<!doctype html>
<html class="fixed dark">
<?php 
	$pagerole="list";
	include('include/head.php');
	// Fetch categories without assigned vehicles
$categories_without_vehicles = [];
$category_query = "SELECT c.id, c.name
                   FROM jostj_vikrentcar_categories c
                   WHERE c.id NOT IN (
                       SELECT DISTINCT TRIM(BOTH ';' FROM SUBSTRING_INDEX(SUBSTRING_INDEX(v.idcat, ';', n.n), ';', -1))
                       FROM jostj_vikrentcar_cars v
                       JOIN (SELECT 1 n UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) n
                       ON CHAR_LENGTH(v.idcat) - CHAR_LENGTH(REPLACE(v.idcat, ';', '')) >= n.n - 1
                       WHERE v.idcat IS NOT NULL AND v.idcat != ''
                   )";

$category_result = mysqli_query($db2, $category_query);
while ($row = mysqli_fetch_assoc($category_result)) {
    $categories_without_vehicles[] = $row['name'];
}

// Fetch vehicles without categories (excluding category IDs 1 and 2)
$vehicles_without_categories = [];
$vehicle_query = "SELECT v.id, v.name 
                  FROM jostj_vikrentcar_cars v
                  WHERE (v.idcat IS NULL OR v.idcat = '' OR v.idcat = ';')
                  AND NOT (FIND_IN_SET(1, v.idcat) OR FIND_IN_SET(2, v.idcat))";

$vehicle_result = mysqli_query($db2, $vehicle_query);
while ($row = mysqli_fetch_assoc($vehicle_result)) {
    $vehicles_without_categories[] = "{$row['name']} (ID: {$row['id']})";
}


?>
	
	?>
<style>
    .green {
        color: green !important;
    }

    .red {
        color: red !important;
    }
</style>

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

            <!-- start: search & user box -->
            <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>
            <!-- end: search & user box -->
        </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 Categories</h2>

                    <div class="right-wrapper text-right">
                        <ol class="breadcrumbs">
                            <li>
                                <a href="index.php">
                                    <i class="fas fa-home"></i>
                                </a>
                            </li>
                            <li><span>WV Admin</span></li>
                            <li><span>Vehicles Categories</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 {

// Display alert if there are missing assignments
if (!empty($categories_without_vehicles) || !empty($vehicles_without_categories)) {
    echo '<div class="alert alert-warning" role="alert">';
    echo '<strong>Warning:</strong> There are category and vehicle assignment issues.<br>';

    // Display categories without vehicles
    if (!empty($categories_without_vehicles)) {
        echo '<strong>Categories without vehicles:</strong> ' . implode(', ', $categories_without_vehicles) . '<br>';
    }

    // Display vehicles without categories
    if (!empty($vehicles_without_categories)) {
        echo '<strong>Vehicles without categories:</strong> ' . implode(', ', $vehicles_without_categories);
    }

    echo '</div>';
}
?>
                  <h3>Filters</h3>
                <div class="row mb-0">

                    <div class="col-md-4"> <label>Type</label>
                        <select class="form-control populate" onChange="window.location.href=this.value">
                            <option value="?<?php echo http_build_query(array_merge($_GET, array("type"=>"0")))?>" <?php if(isset($_GET['type']) && $_GET['type']=='0') { echo "selected"; } ?>>All</option>
                            <option value="?<?php echo http_build_query(array_merge($_GET, array("type"=>"CAR")))?>" <?php if(isset($_GET['type']) && $_GET['type']=='CAR') { echo "selected"; } ?>>CARS</option>
                            <option value="?<?php echo http_build_query(array_merge($_GET, array("type"=>"BIKE")))?>" <?php if(isset($_GET['type']) && $_GET['type']=='BIKE') { echo "selected"; } ?>>BIKES</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <div class="col-md-12 text-right">
        <button class="btn btn-primary" onclick="openAddCategoryModal()">
            <i class="fas fa-plus"></i> Add New Category
        </button>
    </div>
                        </div>

                </div>
                <div class="row">
                    <div class="col">
                        <section class="card">
                            <header class="card-header">
                                <div class="card-actions">
                                    <a href="#" class="card-action card-action-toggle" data-card-toggle></a>
                                    <a href="#" class="card-action card-action-dismiss" data-card-dismiss></a>
                                </div>

                                <h2 class="card-title">Filtered Data</h2>
                            </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>Alias</th>
                                            <th>Description</th>
                                            <th class="text-center">Vehicles</th>
                                            <th class='d-none'>Ordering</th>
                                            <th>Type</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
    <?php 
        $sql = "SELECT * FROM jostj_vikrentcar_categories";
        if (isset($_GET['type']) && $_GET['type'] != '0') {
            $type = $_GET['type'];
            $sql .= " WHERE type = '$type'";
        }

        $result = mysqli_query($db2, $sql);
        if (!$result) {
            echo "Error in main query: " . mysqli_error($db2);
        }

         while ($row = mysqli_fetch_assoc($result)) : ?>
            <tr>
                <td class="text-center"><?= $row['id']; ?></td>
                <td class="text-center"><?= htmlspecialchars($row['name']); ?></td>
                 <td class="text-center"><?= htmlspecialchars($row['alias']); ?></td>
                <td class="text-center"><?= htmlspecialchars($row['descr']); ?></td>
           <!-- Vehicles Column -->
<td class="text-center">
    <?php
    $category_id = $row['id'];
    $vehicles_query = "SELECT id, name FROM jostj_vikrentcar_cars WHERE CONCAT(';', idcat, ';') LIKE '%;$category_id;%'";
    $vehicles_result = mysqli_query($db2, $vehicles_query);

    $vehicle_list = [];
    while ($vehicle = mysqli_fetch_assoc($vehicles_result)) {
        $vehicle_list[] = htmlspecialchars($vehicle['name']) . 
            " <a href='#' onclick=\"removeVehicleFromCategory({$vehicle['id']}, $category_id)\" class='text-danger'><i class='fas fa-times'></i></a>";
    }

    echo empty($vehicle_list) ? '<em>No vehicles</em>' : implode(' / ', $vehicle_list);
    ?>
</td>
                <td class="text-center d-none"><?= $row['ordering']; ?></td>
                <td class="text-center"><?= htmlspecialchars($row['type']); ?></td>
                <td class="actions">
                    <!-- Edit Button -->
                    <a href="#" class="on-default edit-row"
    onclick="openEditModal('<?= $row['id']; ?>', '<?= addslashes($row['name']); ?>', '<?= addslashes($row['descr']); ?>', '<?= $row['type']; ?>', '<?= addslashes($row['alias']); ?>')">
    <i class="fas fa-pencil-alt"></i>
</a>

                    <!-- View Vehicles in Category -->
                    <a href="category_vehicles.php?category_id=<?= $row['id']; ?>" class="on-default edit-row">
                        <i class="fa fa-eye"></i>
                    </a>

                    <?php
                    // Check if there are any vehicles associated with this category
                    $vehicle_count_query = "SELECT COUNT(*) AS count FROM jostj_vikrentcar_cars WHERE idcat LIKE '%{$row['id']};%'";
                    $vehicle_count_result = mysqli_query($db2, $vehicle_count_query);
                    $vehicle_count_row = mysqli_fetch_assoc($vehicle_count_result);

                    // Show Delete Button Only if No Vehicles are Assigned
                    if ($vehicle_count_row['count'] == 0) :
                    ?>
                        <a href="actions/delete_category.php?id=<?= $row['id']; ?>" class="on-default delete-row"
                            onclick="return confirm('Are you sure you want to delete this category?');">
                            <i class="fas fa-trash-alt"></i>
                        </a>
                    <?php endif; ?>

                    <!-- Add Vehicle Button -->
                    <a href="#" class="on-default edit-row"
                        onclick="openAddVehicleModal(<?= $row['id']; ?>, '<?= addslashes($row['name']); ?>')">
                        <i class="fas fa-plus"></i>
                    </a>
                </td>
            </tr>
        <?php endwhile; ?>
</tbody>



                                </table>
                            </div>

                        </section>

                    </div>
                </div>
                <?php } ?>
                <!-- end: page -->
            </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/select2/js/select2.js"></script>
    <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>


    <!--(remove-empty-lines-end)-->

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

    <script>
        (function ($) {

            'use strict';

            var datatableInit = function () {
                var $table = $('#datatable-tabletools');


                var table = $table.dataTable({
                    "pageLength": 50,
                    "order": [
                        [0, "asc"]
                    ],
                    sDom: '<"text-right mb-md"T><"row"<"col-lg-6"l><"col-lg-6"f>><"table-responsive"t>p',
                    buttons: [{
                            extend: 'print',
                            text: 'Print'
                        },
                        {
                            extend: 'excel',
                            text: 'Excel'
                        },
                        {
                            extend: 'pdf',
                            text: 'PDF',
                            customize: function (doc) {
                                var colCount = new Array();
                                $('#datatable-tabletools').find('tbody tr:first-child td').each(
                                    function () {
                                        if ($(this).attr('colspan')) {
                                            for (var i = 1; i <= $(this).attr(
                                                    'colspan'); $i++) {
                                                colCount.push('*');
                                            }
                                        } else {
                                            colCount.push('*');
                                        }
                                    });
                                doc.content[1].table.widths = colCount;
                            }
                        }
                    ]
                });

                $('<div />').addClass('dt-buttons mb-2 pb-1 text-right').prependTo(
                    '#datatable-tabletools_wrapper');

                $table.DataTable().buttons().container().prependTo('#datatable-tabletools_wrapper .dt-buttons');

                $('#datatable-tabletools_wrapper').find('.btn-secondary').removeClass('btn-secondary').addClass(
                    'btn-default');
            };

            $(function () {
                datatableInit();
            });

        }).apply(this, [jQuery]);
    </script>
  <!-- Edit Category Modal -->
<div id="modalEditCategory" class="modal-block modal-block-primary mfp-hide">
    <section class="card">
        <header class="card-header">
            <h2 class="card-title">Edit Category</h2>
        </header>
        <div class="card-body">
            <form method="post" action="actions/edit_category.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>Category Name</label>
                            <input type="text" class="form-control" name="category_name" id="category_name" required>
                        </div>
                        <div class="form-group">
                            <label>Category Alias</label>
                            <input type="text" class="form-control" name="category_alias" id="category_alias">
                        </div>
                        <div class="form-group">
                            <label>Type</label>
                            <select class="form-control" name="category_type" id="category_type" required>
                                <option value="CAR">Car</option>
                                <option value="BIKE">Bike</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Description</label>
                            <textarea class="form-control" name="category_description" id="category_description" rows="4"></textarea>
                        </div>
                    </div>
                </div>
                <footer class="card-footer">
                    <div class="text-right">
                        <button class="btn btn-primary" type="submit">Save Changes</button>
                    </div>
                    <input type="hidden" name="category_id" id="category_id">
                </footer>
            </form>
        </div>
    </section>
</div>

<script>
    function openEditModal(categoryId, name, description, type, alias) {
    $('#category_id').val(categoryId);
    $('#category_name').val(name);
    $('#category_description').val(description);
    $('#category_type').val(type);
    $('#category_alias').val(alias);  // ✅ Populate the alias field too!

    $.magnificPopup.open({
        items: {
            src: '#modalEditCategory'
        },
        type: 'inline'
    });
}

</script>
<!-- Add Category Modal -->
<div id="modalAddCategory" class="modal-block modal-block-primary mfp-hide">
    <section class="card">
        <header class="card-header">
            <h2 class="card-title">Add New Category</h2>
        </header>
        <div class="card-body">
            <form method="post" action="actions/add_category.php">
                <div class="modal-wrapper">
                    <div class="modal-icon">
                        <i class="fas fa-plus"></i>
                    </div>
                    <div class="modal-text">
                        <div class="form-group mb-3">
                            <label for="category_name">Category Name</label>
                            <input type="text" class="form-control" name="category_name" id="category_name" required>
                        </div>
                        <div class="form-group mb-3">
                            <label for="category_alias">Category Alias</label>
                            <input type="text" class="form-control" name="category_alias" id="category_alias">
                        </div>
                        <div class="form-group mb-3">
                            <label for="category_type">Type</label>
                            <select class="form-control" name="category_type" id="category_type" required>
                                <option value="CAR">Car</option>
                                <option value="BIKE">Bike</option>
                            </select>
                        </div>
                        <div class="form-group mb-3">
                            <label for="category_description">Description</label>
                            <textarea class="form-control" name="category_description" id="category_description" rows="4"></textarea>
                        </div>
                    </div>
                </div>
        </div>
        <footer class="card-footer">
            <div class="text-right">
                <button class="btn btn-primary" type="submit">Add Category</button>
            </div>
        </footer>
        </form>
    </section>
</div>

<!-- 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 <span id="categoryName"></span></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">

                    <!-- 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'
        });
    }
</script>
<script>
    function openAddCategoryModal() {
        $.magnificPopup.open({
            items: {
                src: '#modalAddCategory'
            },
            type: 'inline'
        });
    }
    // Function to open the modal and set category details
function openAddVehicleModal(categoryId, categoryName) {
    document.getElementById("categoryId").value = categoryId;
    document.getElementById("categoryName").innerText = categoryName;
    $("#addVehicleModal").modal("show");
}

// AJAX function to submit form
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",
        type: "POST",
        data: { category_id: categoryId, vehicle_id: vehicleId },
        success: function(response) {
            alert(response);
            $("#addVehicleModal").modal("hide");
            location.reload(); // Refresh page to update changes
        },
        error: function() {
            alert("Error processing request.");
        }
    });
}
function removeVehicleFromCategory(vehicleId, categoryId) {
    if (!confirm("Are you sure you want to remove this vehicle from this category?")) {
        return;
    }

    $.ajax({
        url: "actions/remove_vehicle_from_category.php",
        type: "POST",
        data: { vehicle_id: vehicleId, category_id: categoryId },
        success: function(response) {
            alert(response);
            location.reload();
        },
        error: function() {
            alert("Error processing request.");
        }
    });
}

</script>

</body>

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