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

?>
<!doctype html>
<html class="fixed dark">
<?php 
	$pagerole="lists";
	include('include/head.php');?>
<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>Availability Groups</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>Manage Availability Groups</span></li>
                        </ol>

                        <a class="sidebar-right-toggle" data-open="sidebar-right"><i
                                class="fas fa-chevron-left"></i></a>
                    </div>
                </header>
       
                <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">Manage Availability Groups</h2>
                            <button class="btn btn-primary mt-4" id="add-group-btn">+ Add Group</button>
                            </header>

                            <div class="card-body">
<?php 
// Query to find models NOT in any availability group
$unassignedModelsQuery = "
    SELECT jvc.id, jvc.name 
    FROM jostj_vikrentcar_cars jvc
    LEFT JOIN car_availability_groups cag ON jvc.id = cag.car_id
    WHERE cag.car_id IS NULL
    ORDER BY jvc.name ASC";

$unassignedModelsResult = mysqli_query($db2, $unassignedModelsQuery);
$unassignedModels = [];

while ($row = mysqli_fetch_assoc($unassignedModelsResult)) {
    $unassignedModels[] = $row;
}
?>
<?php if (!empty($unassignedModels)) { ?>
    <div class="alert alert-danger">
        <strong>⚠ Warning!</strong> The following models are not assigned to any availability group:
        <ul>
            <?php foreach ($unassignedModels as $model) { ?>
                <li>
                    <strong><?php echo $model['name']; ?></strong> 
                    <a href="#" class="btn btn-sm btn-success assign-model-btn" 
                       data-model-id="<?php echo $model['id']; ?>" 
                       data-model-name="<?php echo $model['name']; ?>">
                        <i class="fas fa-plus"></i> Assign to Group
                    </a>
                </li>
            <?php } ?>
        </ul>
    </div>
<?php } ?>

                                <table class="table table-bordered table-striped mb-0" id="datatable-tabletools">
                             <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Name</th>
                                        <th>Alias</th>
                                          <th>Models</th>
                                        <th>Total Vehicles</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                  <tbody>
    <?php 
    $sql = "SELECT ag.id, ag.name, ag.alias,
            GROUP_CONCAT(DISTINCT jvc.name ORDER BY jvc.name ASC SEPARATOR ' / ') AS models,
            COUNT(DISTINCT f.fleet_id) AS total_active_vehicles
            FROM availability_groups ag
            LEFT JOIN car_availability_groups cag ON ag.id = cag.avail_group
            LEFT JOIN jostj_vikrentcar_cars jvc ON cag.car_id = jvc.id
            LEFT JOIN fleet f ON jvc.id = f.veh_id AND f.active = 1
            GROUP BY ag.id";
    
    $result = mysqli_query($db2, $sql);

    while ($row = mysqli_fetch_assoc($result)) {
        ?>
        <tr>
            <td><?php echo $row['id']; ?></td>
            <td><?php echo $row['name']; ?></td>
            <td><?php echo $row['alias']; ?></td>

            <!-- Models Column -->
            <td>
                <?php 
                if (!empty($row['models'])) {
                    $models = explode(" / ", $row['models']);
                    foreach ($models as $model) {
                        echo "<span class='model-item'>{$model} 
                                <a href='#' class='delete-model-btn text-danger' 
                                   data-group-id='{$row['id']}' data-model-name='{$model}'>
                                   <i class='fas fa-times'></i>
                                </a> / 
                              </span>";
                    }
                } else {
                    echo "<span class='text-muted'>No Models Assigned</span>";
                }
                ?>
            </td>

            <!-- Total Vehicles Column -->
            <td class="text-center">
                <strong><?php echo $row['total_active_vehicles']; ?></strong>
            </td>

            <!-- Actions -->
            <td class="actions">
                <a href="#" class="on-default edit-row edit-group-btn" 
                    data-id="<?php echo $row['id']; ?>" 
                    data-name="<?php echo $row['name']; ?>"
                    data-alias="<?php echo $row['alias']; ?>">
                    <i class="fas fa-edit"></i>
                </a>
                <a href="#" class="on-default delete-row delete-group-btn" data-id="<?php echo $row['id']; ?>">
                    <i class="fas fa-trash-alt"></i>
                </a>
               
                <a href="#" class="on-default add-model-btn" data-group-id="<?php echo $row['id']; ?>" data-group-name="<?php echo $row['name']; ?>">
                    <i class="fas fa-plus"></i
                </a>
            </td>
        </tr>
    <?php } ?>
</tbody>


                                </table>
                            </div>

                        </section>

                    </div>
                </div>
            
                <!-- 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>
<!-- Add Group Modal -->
    <div id="modalAddGroup" class="modal-block modal-block-primary mfp-hide">
        <section class="card">
            <header class="card-header">
                <h2 class="card-title">Add Availability Group</h2>
                <div class="card-actions">
                    <a href="#" class="modal-dismiss"><i class="fas fa-times"></i></a>
                </div>
            </header>
            <div class="card-body">
                <form id="addGroupForm">
                    <div class="form-group">
                        <label for="group_name">Group Name</label>
                        <input type="text" class="form-control" id="group_name" name="name" required>
                    </div>
                    <div class="form-group">
                        <label for="group_alias">Alias</label>
                        <input type="text" class="form-control" id="group_alias" name="alias" required>
                    </div>
                </form>
            </div>
            <footer class="card-footer">
                <button type="button" class="btn btn-primary" id="submit-add-group">Add Group</button>
            </footer>
        </section>
    </div>

    <!-- Edit Group Modal -->
    <div id="modalEditGroup" class="modal-block modal-block-primary mfp-hide">
        <section class="card">
            <header class="card-header">
                <h2 class="card-title">Edit Availability Group</h2>
                <div class="card-actions">
                    <a href="#" class="modal-dismiss"><i class="fas fa-times"></i></a>
                </div>
            </header>
            <div class="card-body">
                <form id="editGroupForm">
                    <input type="hidden" id="edit_group_id" name="id">
                    <div class="form-group">
                        <label for="edit_group_name">Group Name</label>
                        <input type="text" class="form-control" id="edit_group_name" name="name" required>
                    </div>
                    <div class="form-group">
                        <label for="edit_group_alias">Alias</label>
                        <input type="text" class="form-control" id="edit_group_alias" name="alias" required>
                    </div>
                </form>
            </div>
            <footer class="card-footer">
                <button type="button" class="btn btn-primary" id="submit-edit-group">Save Changes</button>
            </footer>
        </section>
    </div>
<div id="modalAddModel" class="modal-block modal-block-primary mfp-hide">
    <section class="card">
        <header class="card-header">
            <h2 class="card-title">Add Model to <span id="modal-add-group-name"></span></h2>
            <div class="card-actions">
                <a href="#" class="modal-dismiss"><i class="fas fa-times"></i></a>
            </div>
        </header>
        <div class="card-body">
            <form id="addModelForm">
                <input type="hidden" id="add_group_id" name="group_id">
                <div class="form-group">
                    <label for="model_select">Select Model</label>
                    <select class="form-control" id="model_select" name="model_id">
                        <option value="">-- Select a Model --</option>
                        <?php
                        $modelQuery = "SELECT id, name FROM jostj_vikrentcar_cars ORDER BY name ASC";
                        $modelResult = mysqli_query($db2, $modelQuery);
                        while ($modelRow = mysqli_fetch_assoc($modelResult)) {
                            echo "<option value='{$modelRow['id']}'>{$modelRow['name']}</option>";
                        }
                        ?>
                    </select>
                </div>
            </form>
        </div>
        <footer class="card-footer">
            <button type="button" class="btn btn-primary" id="submit-add-model">Add Model</button>
        </footer>
    </section>
</div>
<div id="modalAssignModel" class="modal-block modal-block-primary mfp-hide">
    <section class="card">
        <header class="card-header">
            <h2 class="card-title">Assign <span id="assign-model-name"></span> to a Group</h2>
            <div class="card-actions">
                <a href="#" class="modal-dismiss"><i class="fas fa-times"></i></a>
            </div>
        </header>
        <div class="card-body">
            <form id="assignModelForm">
                <input type="hidden" id="assign_model_id" name="model_id">
                <div class="form-group">
                    <label for="assign_group_select">Select Group</label>
                    <select class="form-control" id="assign_group_select" name="group_id">
                        <option value="">-- Select a Group --</option>
                        <?php
                        $groupQuery = "SELECT id, name FROM availability_groups ORDER BY name ASC";
                        $groupResult = mysqli_query($db2, $groupQuery);
                        while ($groupRow = mysqli_fetch_assoc($groupResult)) {
                            echo "<option value='{$groupRow['id']}'>{$groupRow['name']}</option>";
                        }
                        ?>
                    </select>
                </div>
            </form>
        </div>
        <footer class="card-footer">
            <button type="button" class="btn btn-primary" id="submit-assign-model">Assign Model</button>
        </footer>
    </section>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('.delete-model-btn').forEach(button => {
        button.addEventListener('click', function (e) {
            e.preventDefault();
            
            let groupId = this.dataset.groupId;
            let modelName = this.dataset.modelName;

            if (confirm(`Are you sure you want to remove "${modelName}" from this group?`)) {
                fetch('actions/delete_model_from_group.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ group_id: groupId, model_name: modelName })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert("Model removed successfully!");
                        location.reload();
                    } else {
                        alert("Error: " + data.message);
                    }
                })
                .catch(error => {
                    console.error("Error deleting model:", error);
                    alert("An error occurred. Please try again.");
                });
            }
        });
    });
});

</script>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            document.getElementById('add-group-btn').addEventListener('click', function () {
                $.magnificPopup.open({ items: { src: '#modalAddGroup' }, type: 'inline' });
            });

            document.getElementById('submit-add-group').addEventListener('click', function () {
                const form = document.getElementById('addGroupForm');
                const formData = new FormData(form);
                
                fetch('actions/add_availability_group.php', { method: 'POST', body: formData })
                .then(response => response.json())
                .then(data => { if (data.success) location.reload(); })
                .catch(error => alert('Error: ' + error));
            });

            document.querySelectorAll('.edit-group-btn').forEach(button => {
                button.addEventListener('click', function () {
                    document.getElementById('edit_group_id').value = this.dataset.id;
                    document.getElementById('edit_group_name').value = this.dataset.name;
                    document.getElementById('edit_group_alias').value = this.dataset.alias;
                    $.magnificPopup.open({ items: { src: '#modalEditGroup' }, type: 'inline' });
                });
            });

            document.getElementById('submit-edit-group').addEventListener('click', function () {
                const form = document.getElementById('editGroupForm');
                const formData = new FormData(form);
                
                fetch('actions/edit_availability_group.php', { method: 'POST', body: formData })
                .then(response => response.json())
                .then(data => { if (data.success) location.reload(); })
                .catch(error => alert('Error: ' + error));
            });

            document.querySelectorAll('.delete-group-btn').forEach(button => {
                button.addEventListener('click', function () {
                    if (confirm('Are you sure you want to delete this group?')) {
                        fetch('actions/delete_availability_group.php?id=' + this.dataset.id, { method: 'GET' })
                        .then(response => response.json())
                        .then(data => { if (data.success) location.reload(); })
                        .catch(error => alert('Error: ' + error));
                    }
                });
            });
        });
       
document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('.view-cars-btn').forEach(button => {
        button.addEventListener('click', function () {
            let groupId = this.dataset.id;
            let groupName = this.dataset.name;

            console.log("Opening modal for group ID:", groupId);

            let modalTitle = document.getElementById('modal-group-name');
            let carList = document.getElementById('carList');

            if (!modalTitle || !carList) {
                console.error("Error: Modal elements not found in DOM.");
                return;
            }

            modalTitle.innerText = groupName;
           carList.innerHTML = ''; // Make sure we clear previous entries

            fetch('actions/get_cars_in_group.php?group_id=' + groupId)
                .then(response => response.json())
                .then(data => {
                    console.log("Fetched Cars Data:", data);

                    if (data.success && data.cars.length > 0) {
                        carList.innerHTML = "";
                        data.cars.forEach(car => {
                            let row = document.createElement("tr");
                            row.innerHTML = `
                                <td>${car.car_id}</td>
                                <td>${car.model}</td>
                                <td>${car.lic_num}</td>
                                <td>
                                    <button class="btn btn-danger btn-sm delete-car-btn" 
                                        data-car-id="${car.car_id}" 
                                        data-group-id="${groupId}">
                                        <i class="fas fa-trash-alt"></i> Delete
                                    </button>
                                </td>
                            `;
                            carList.appendChild(row);
                        });

                        // Attach event listeners to delete buttons
                        document.querySelectorAll('.delete-car-btn').forEach(deleteBtn => {
                            deleteBtn.addEventListener('click', function () {
                                let carId = this.dataset.carId;
                                let groupId = this.dataset.groupId;
                                deleteCarFromGroup(carId, groupId);
                            });
                        });

                    } else {
                        carList.innerHTML = "<tr><td colspan='4'>No cars found in this group.</td></tr>";
                    }

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

                })
                .catch(error => {
                    console.error("Error fetching cars:", error);
                    carList.innerHTML = "<tr><td colspan='4'>Error loading data</td></tr>";
                });
        });
    });
});

// Function to delete a car from a group
function deleteCarFromGroup(carId, groupId) {
    if (!confirm("Are you sure you want to remove this car from the group?")) {
        return;
    }

    fetch('actions/delete_car_from_group.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ car_id: carId, group_id: groupId })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert("Car removed from group successfully!");
            location.reload(); // Refresh page after deletion
        } else {
            alert("Error: " + data.message);
        }
    })
    .catch(error => {
        console.error("Error deleting car:", error);
        alert("An error occurred. Please try again.");
    });
}
document.addEventListener('DOMContentLoaded', function () {
    // Open "Add Model" Modal
    document.querySelectorAll('.add-model-btn').forEach(button => {
        button.addEventListener('click', function (e) {
            e.preventDefault();

            let groupId = this.dataset.groupId;
            let groupName = this.dataset.groupName;

            document.getElementById('add_group_id').value = groupId;
            document.getElementById('modal-add-group-name').innerText = groupName;

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

    // Submit "Add Model" Form
    document.getElementById('submit-add-model').addEventListener('click', function () {
        const form = document.getElementById('addModelForm');
        const formData = new FormData(form);

        fetch('actions/add_model_to_group.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Model added successfully!');
                location.reload(); // Refresh the page
            } else {
                alert('Error: ' + (data.message || 'Unknown error occurred.'));
            }
        })
        .catch(error => {
            console.error('Error:', error || 'Unknown error occurred');
            alert('An error occurred. Please try again.');
        });
    });
});
document.addEventListener('DOMContentLoaded', function () {
    // Open Assign Model Modal
    document.querySelectorAll('.assign-model-btn').forEach(button => {
        button.addEventListener('click', function (e) {
            e.preventDefault();

            let modelId = this.dataset.modelId;
            let modelName = this.dataset.modelName;

            document.getElementById('assign_model_id').value = modelId;
            document.getElementById('assign-model-name').innerText = modelName;

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

    // Submit Assign Model Form
    document.getElementById('submit-assign-model').addEventListener('click', function () {
        const form = document.getElementById('assignModelForm');
        const formData = new FormData(form);

        fetch('actions/assign_model_to_group.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Model assigned successfully!');
                location.reload(); // Refresh the page
            } else {
                alert('Error: ' + (data.message || 'Unknown error occurred.'));
            }
        })
        .catch(error => {
            console.error('Error:', error || 'Unknown error occurred');
            alert('An error occurred. Please try again.');
        });
    });
});

</script>

    </script>
    <script>
        (function ($) {

            'use strict';

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


                var table = $table.dataTable({
                    "order": [
                        [3, "desc"]
                    ],
                    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>
</body>

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