<?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;
    }
    .rd-container {
        position: fixed !important;
        top: 50% !important;
        left: 50% !important;
        transform: translate(-50%, -50%) !important;
        z-index: 10002;
        zoom: 140%;
    }
</style>
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/rome/3.0.2/rome.css"  crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/rome/3.0.2/rome.js"  crossorigin="anonymous"></script>

<body>
    <section class="body">

        <!-- start: header -->
        <?php include('include/header.php'); ?>
        <!-- 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>Service Dashboard</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>Service Dashboard</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 { ?>

                  <!-- Filters -->
            <div class="row mb-3">
                <!-- Model Filter -->
                <div class="col-md-3">
                    <label>Model</label>
                    <select class="form-control populate" onChange="window.location.href=this.value">
                        <option value="?<?php echo http_build_query(array_merge($_GET, ['model' => 'all'])); ?>">All</option>
                        <?php
                        $models_query = "SELECT id, name FROM jostj_vikrentcar_cars";
                        $models_result = mysqli_query($db2, $models_query);
                        while ($model = mysqli_fetch_assoc($models_result)) {
                            $selected = (isset($_GET['model']) && $_GET['model'] == $model['id']) ? 'selected' : '';
                            echo "<option value='?" . http_build_query(array_merge($_GET, ['model' => $model['id']])) . "' $selected>{$model['name']}</option>";
                        }
                        ?>
                    </select>
                </div>

                <!-- Status Filter -->
                <div class="col-md-3">
                    <label>Status</label>
                    <select class="form-control populate" onChange="window.location.href=this.value">
                        <option value="?<?php echo http_build_query(array_merge($_GET, ['status' => 'all'])); ?>">All</option>
                        <option value="?<?php echo http_build_query(array_merge($_GET, ['status' => 'active'])); ?>">Active</option>
                        <option value="?<?php echo http_build_query(array_merge($_GET, ['status' => 'inactive'])); ?>">Inactive</option>
                    </select>
                </div>

                <!-- Due for Service Filter -->
                <div class="col-md-3">
                    <label>Due for Service</label>
                    <select class="form-control populate" onChange="window.location.href=this.value">
                        <option value="?<?php echo http_build_query(array_merge($_GET, ['service_due' => 'all'])); ?>">All</option>
                        <option value="?<?php echo http_build_query(array_merge($_GET, ['service_due' => 'overdue'])); ?>">Overdue</option>
                        <option value="?<?php echo http_build_query(array_merge($_GET, ['service_due' => 'soon'])); ?>">Due Soon</option>
                        <option value="?<?php echo http_build_query(array_merge($_GET, ['service_due' => 'not_set'])); ?>">Not Set</option>
                    </select>
                </div>
            </div>
                <!-- Mechanics Table -->
                <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">Vehicles for Maintenance</h2>
                            </header>
                            <div class="card-body">
                                <table class="table table-bordered table-striped mb-0" id="datatable-tabletools">
                                    <thead>
                                        <tr>
                                        <th>Fleet ID</th>
                                        <th>Model</th>
                                        <th>License Plate</th>
                                        <th>Color</th>
                                        <th>Active</th>
                                        <th>Last Service</th>
                                        <th>Next Service</th>
                                        <th>Action</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    <?php 
                                    $sql = "SELECT 
                                        fleet.fleet_id, 
                                        jostj_vikrentcar_cars.name AS model_name, 
                                        fleet.lic_num, 
                                        fleet.color, 
                                        fleet.active, 
                                        fleet.fleet_last_service, 
                                        fleet.fleet_next_service, 
                                        fleet.veh_id
                                    FROM fleet 
                                    LEFT JOIN jostj_vikrentcar_cars ON fleet.veh_id = jostj_vikrentcar_cars.id 
                                    WHERE fleet.fleet_sold = 0";

                                    $result = mysqli_query($db2, $sql);
                                    while ($row = mysqli_fetch_assoc($result)) {
                                        $activeClass = $row['active'] == 1 ? 'green' : 'red';
                                        ?>
                                        
                                <tr>
                                    <td><?php echo $row['fleet_id']; ?></td>
        <td><strong><?php echo $row['model_name']; ?></strong></td>
        <td><?php echo $row['lic_num']; ?></td>
          <td><?php echo $row['color']; ?></td>
         <td class="<?php echo ($row['active'] == 1) ? 'green' : 'red'; ?>"> <?php echo ($row['active']) ? '<span class="badge badge-success">Yes</span>' : '<span class="badge badge-danger">No</span>'; ?>
        </td>
          <td>
            <?php echo ($row['fleet_last_service']) ? "<span class='badge badge-warning'>" . date('d/m/Y', $row['fleet_last_service']) . "</span>" : "<span class='text-muted'>Not Set</span>"; ?>
        </td>
        <td>
            <?php echo ($row['fleet_next_service']) ? "<span class='badge badge-primary'>" . date('d/m/Y', $row['fleet_next_service']) . "</span>" : "<span class='text-muted'>Not Set</span>"; ?>
        </td>
         <td class="actions"> 
         <a href="vehicle.php?id=<?php echo $row["fleet_id"] ?? ''; ?>" class="on-default edit-row">
       <i class="fa fa-eye"></i>
    </a>
    <a href="log_service.php?veh_id=<?php echo $row["fleet_id"] ?? ''; ?>" class="on-default edit-row">
       <i class="fas fa-tools"></i>
    </a>
                                   </tr>        
                                 <?php   }
                                    ?>
                                </tbody>
                                </table>
                            </div>
                        </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/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>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"
        integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ=="
        crossorigin="anonymous"></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 src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"
    
    crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rome/3.0.2/rome.standalone.min.js"
    
    crossorigin="anonymous"></script>
    <script>
        (function ($) {

            'use strict';

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


                var table = $table.dataTable({
                    "pageLength": 30,
                    "order": [
                        [2, "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>

<div id="modalLogService" class="modal-block modal-block-primary mfp-hide">
    <section class="card">
        <header class="card-header">
            <h2 class="card-title">Log Service Action</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="logServiceForm">
                <input type="hidden" id="service_veh_id" name="veh_id">

                <!-- Vehicle Info -->
                <div class="form-group row">
                    <div class="col-md-6">
                        <label for="vehicle_name">Vehicle</label>
                        <input type="text" class="form-control" id="vehicle_name" name="vehicle_name" readonly>
                    </div>
                    <div class="col-md-6">
                        <label for="license_plate">License Plate</label>
                        <input type="text" class="form-control" id="license_plate" name="license_plate" readonly>
                    </div>
                </div>

                <!-- Service Dates -->
                <div class="form-group row">
                    <div class="col-md-6">
                        <label for="last_service_date">Last Service Date</label>
                        <input type="text" class="form-control" id="last_service_date" name="last_service_date" readonly>
                    </div>
                    <div class="col-md-6">
                        <label for="next_service_date">Next Service Date</label>
                        <input type="text" class="form-control datepicker" id="next_service_date" name="next_service_date">
                    </div>
                </div>

                <!-- Current KM -->
                <div class="form-group">
                    <label for="current_km">Current KM</label>
                    <input type="number" class="form-control" id="current_km" name="current_km" required>
                </div>

                <!-- Service Group -->
                <div class="form-group">
                    <label for="service_group">Service Group</label>
                    <select class="form-control" id="service_group" name="service_group" required>
                        <option value="">Select Group</option>
                        <?php
                        $groups_query = "SELECT * FROM service_groups";
                        $groups_result = mysqli_query($db2, $groups_query);
                        while ($group = mysqli_fetch_assoc($groups_result)) {
                            echo "<option value='{$group['service_groups_id']}'>{$group['service_groups_name']}</option>";
                        }
                        ?>
                    </select>
                </div>

                <!-- Service Tasks -->
                <div class="form-group">
                    <label for="service_tasks">Service Tasks</label>
                    <div id="service_tasks" class="form-check">
                        <!-- Dynamically populated checkboxes -->
                    </div>
                </div>

                <!-- Additional Info -->
                <div class="form-group">
                    <label for="info">Additional Info</label>
                    <textarea class="form-control" id="info" name="info" rows="3"></textarea>
                </div>

                <!-- Save Button -->
                <footer class="card-footer">
                    <div class="row">
                        <div class="col-md-12 text-right">
                            <button type="button" class="btn btn-primary" id="submit-log-service">Save</button>
                        </div>
                    </div>
                </footer>
            </form>
        </div>
    </section>
</div>





<script>

document.addEventListener('DOMContentLoaded', function () {
    window.openLogServiceModal = function (veh_id, vehicle_name, license_plate, last_service, next_service) {
        console.log("Opening modal for:", veh_id, vehicle_name, license_plate, last_service, next_service);

        document.getElementById('service_veh_id').value = veh_id;
        document.getElementById('vehicle_name').value = vehicle_name;
        document.getElementById('license_plate').value = license_plate;
        document.getElementById('last_service_date').value = last_service;
        document.getElementById('next_service_date').value = next_service;

        // Clear and reset service tasks
        document.getElementById('service_group').value = '';
        document.getElementById('service_tasks').innerHTML = '';

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

    document.getElementById('service_group').addEventListener('change', function () {
        const groupId = this.value;
        console.log("Fetching tasks for group:", groupId);

        fetch('actions/get_service_tasks.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ service_group_id: groupId }),
        })
        .then(response => response.json())
        .then(tasks => {
            console.log("Received tasks:", tasks);
            let tasksContainer = document.getElementById('service_tasks');
            tasksContainer.innerHTML = '';

            tasks.forEach(task => {
                let checkbox = `<div class="form-check">
                    <input type="checkbox" id="task_${task.service_task_id}" name="service_tasks[]" value="${task.service_task_id}">
                    <label for="task_${task.service_task_id}">${task.service_task_name}</label>
                </div>`;
                tasksContainer.innerHTML += checkbox;
            });
        })
        .catch(error => console.error('Error fetching tasks:', error));
    });

    document.getElementById('submit-log-service').addEventListener('click', function () {
        const form = document.getElementById('logServiceForm');
        const formData = new FormData(form);

        fetch('actions/add_service_log.php', {
            method: 'POST',
            body: formData,
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Service logged successfully!');
                location.reload();
            } else {
                alert('Error: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('An error occurred. Please try again.');
        });
    });

    rome(next_service_date, {
        appendTo: document.body,
        autoClose: true,
        inputFormat: 'DD-MM-YYYY',
        time: false,
    });
});


document.getElementById('submit-log-service').addEventListener('click', function () {
    const form = document.getElementById('logServiceForm');
    const formData = new FormData(form);

    // Debug: Print form values before sending
    for (let pair of formData.entries()) {
        console.log(pair[0] + ": " + pair[1]); 
    }

    fetch('actions/add_service_log.php', {
        method: 'POST',
        body: formData,
    })
    .then(response => response.json())
    .then(data => {
        console.log("🚀 Server Response:", data); // Log response

        if (data.success) {
            alert('✅ Service logged successfully!');
            location.reload();
        } else {
            console.error("❌ Error from Server:", data.message); // Log error message
            alert('❌ Error: ' + data.message);
        }
    })
    .catch(error => {
        console.error("❌ Fetch Error:", error); // Log network errors
        alert('❌ An error occurred. Check console for details.');
    });
});


</script>
</body>
</html>
