<?php
ini_set('display_errors', 1); // Disable displaying errors
ini_set('log_errors', 1); // Log errors instead
ini_set('error_log', '/path/to/php-error.log'); // Specify the log file
include "include/auth.php"; 

?>
<!doctype html>
<html class="fixed dark"> <?php


$pagerole = "user";
include "include/head.php";

// Ensure `veh_id` is provided
if (!isset($_GET['veh_id'])) {
    die("❌ No vehicle selected.");
}
$veh_id = intval($_GET['veh_id']);

// Fetch vehicle details with model name and category ID
$sql = $db2->query("
    SELECT f.*, c.name AS model_name, c.idcat AS category_id
    FROM fleet f
    LEFT JOIN jostj_vikrentcar_cars c ON f.veh_id = c.id
    WHERE f.fleet_id = '$veh_id' 
    LIMIT 1
");

if ($sql->num_rows === 0) {
    die("❌ Vehicle not found.");
}
$vehicle = $sql->fetch_assoc();

// Fetch last service details
$last_service_query = $db2->query("
    SELECT fleet_last_service, fleet_next_service 
    FROM fleet 
    WHERE fleet_id = '$veh_id'
");
$last_service = $last_service_query->fetch_assoc();

// Fetch Service Logs history (WITHOUT username)
$service_logs_query = $db2->query("
    SELECT sl.*, sg.service_groups_name
    FROM service_logs sl
    LEFT JOIN service_groups sg ON sl.service_group_id = sg.service_groups_id
    WHERE sl.veh_id = '$veh_id' 
    ORDER BY sl.log_date DESC
");

// Initialize array to collect unique user IDs
$user_ids = [];

$service_logs = [];
while ($service = $service_logs_query->fetch_assoc()) {
    $service_logs[] = $service;
    if (!empty($service["userid"])) {
        $user_ids[] = intval($service["userid"]);
    }
}

// Remove duplicates
$user_ids = array_unique($user_ids);
// Fetch usernames from Joomla DB ($db)
$usernames_map = [];
if (!empty($user_ids)) {
    $user_ids_list = implode(',', $user_ids); // Convert array to comma-separated list
    $users_query = $db->query("SELECT id, username FROM motorclu_joom524.users WHERE id IN ($user_ids_list)");

    while ($user = $users_query->fetch_assoc()) {
        $usernames_map[$user["id"]] = $user["username"];
    }
}

// Fetch all service tasks as an associative array
$service_tasks_query = $db2->query("SELECT service_task_id, service_task_name FROM service_tasks");
$service_tasks_map = [];
while ($task = $service_tasks_query->fetch_assoc()) {
    $service_tasks_map[$task["service_task_id"]] = $task["service_task_name"];
}


?>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/rome/3.0.2/rome.css" integrity="sha512-TAAJeGIyqkrJ4o4ZkIPesmqNKH9zowoRBGHkHUf1s4vWeII8Dv3NayKIq8Hws02HWT3OpocxeSaOQEQo9SH7ZQ==" crossorigin="anonymous" />
  <style>
    .ecommerce-timeline:before {
      box-shadow: none !important;
    }

    .ecommerce-timeline:after {
      box-shadow: none !important;
    }

    .editbutton {
      position: absolute;
      right: 15px;
      top: 10px;
    }

    .editnotes {
      position: absolute;
      right: 15px;
      bottom: 10px;
    }

    .rd-container-attachment {
      z-index: 10002;
      zoom: 80%
    }

    .modal {
      max-width: 90%;
    }
  </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>New Service Log - <?php echo htmlspecialchars($vehicle["lic_num"]); ?> </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>New Service Log </span>
                </li>
              </ol>
              <a class="sidebar-right-toggle" data-open="sidebar-right">
                <i class="fas fa-chevron-left"></i>
              </a>
            </div>
          </header>
          <!-- start: page -->

                <div class="col-xl-12">
    <form class="order-details action-buttons-fixed" method="post" name="form1" id="logServiceForm" action="actions/add_service_log.php">
        <input type="hidden" name="veh_id" value="<?php echo $veh_id; ?>">
        <div class="card">
            <div class="card-header">
                <h2 class="card-title">Service Details</h2>
            </div>
            <div class="card-body">
                <div class="form-row">
                    <div class="form-group col-md-3  pt-0" style="border-top:none;">

                        <label>Vehicle</label>
                        <input type="text" class="form-control"
                            value="<?php echo htmlspecialchars($vehicle['model_name']); ?>" readonly>
                    </div>
                    <div class="form-group col-md-3 pt-0" style="border-top:none;">
                        <label>License Plate</label>
                        <input type="text" class="form-control"
                            value="<?php echo htmlspecialchars($vehicle['lic_num']); ?>" readonly>
                    </div>

                    <div class="form-group col-md-3 pt-0" style="border-top:none;">
                        <label>Last Service Date</label>
                        <input type="text" class="form-control"
                            value="<?php echo !empty($last_service["fleet_last_service"]) ? date("d/m/Y", $last_service["fleet_last_service"]) : "Not Set"; ?>"
                            readonly>
                    </div>
                    <div class="form-group col-md-3  pt-0" style="border-top:none;">
                        <label>Next Service Due Date</label>
                        <input type="text" class="form-control"
                            value="<?php echo !empty($last_service["fleet_next_service"]) ? date("d/m/Y", $last_service["fleet_next_service"]) : "Not Set"; ?>"
                            readonly>
                    </div>
                </div>
            </div>

        </div>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">New Service Log</h2>
    </div>
    <div class="card-body">
        <div class="form-row">
            <div class="form-group col-4 mb-3 pt-0" style="border-top:none;">
                <label>Current KM</label>
                <input type="number" class="form-control" name="current_km" required>
            </div>
            <div class="form-group col-4 mb-3 pt-0" style="border-top:none;">
                <label>Next Servie KM</label>
                <input type="number" class="form-control" name="next_km" required>
            </div>
            <div class="form-group col-4 mb-3 pt-0" style="border-top:none;">
                <label>Next Service date</label>
                <input type="text" data-plugin-datepicker data-plugin-options='{"format": "dd/mm/yyyy"}' class="form-control" name="nextservice" >
            </div>
        </div>
        <!-- Select Service Group -->
        <div class="form-row">
            <div class="form-group col-12 mb-3 pt-0" style="border-top:none;">
                <label>Service Group</label>
                <select class="form-control" id="service_group" name="service_group" required>
                    <option value="">Select Group</option>
                    <?php
                                        
                                        $groups_query = $db2->query("SELECT * FROM service_groups ");
                                        while ($group = $groups_query->fetch_assoc()) {
                                            echo "<option value='{$group['service_groups_id']}'>" . htmlspecialchars($group['service_groups_name']) . "</option>";
                                        }
                                        ?>
                </select>
            </div>
        </div>

        <!-- Select Service Tasks -->
        <div class="form-row">
            <div class="form-group col-12 mb-3 pt-0" style="border-top:none;">
                <label>Service Tasks</label>
                <div id="service_tasks"></div>
            </div>
        </div>
        <div class="form-row">
            <div class="form-group col-6 mb-3 pt-0" style="border-top:none;">
                <label>Additional Info</label>
                <textarea class="form-control" name="info" rows="3"></textarea>
            </div>
            <div class="form-group col-6 mb-3 pt-0" style="border-top:none;">
                <label>Damages</label>
                <textarea class="form-control" name="damages" rows="3"></textarea>
            </div>
        </div>
        <!-- Hidden fields to pass user data -->
<input type="hidden" name="userid" value="<?php echo $userid; ?>">
<input type="hidden" name="username" value="<?php echo $_SESSION['username'] ?? 'Unknown User'; ?>">
        <div class="text-right">
                <button type="submit" class="btn btn-primary">Save</button>
                <a href="vehicle.php?id=<?php echo $veh_id; ?>" class="btn btn-danger">Cancel</a>
            </div>
    </div>


</div>
</div>

</form>

<!-- Collapsible Card for Service Logs History -->
<div class="card card-collapsed">
    <header class="card-header">
        <h2 class="card-title">Service Logs History</h2>
        <div class="card-actions">
            <a href="#" class="card-action card-action-toggle" data-card-toggle></a>
        </div>
    </header>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Current KM</th>
                        <th>Service Group</th>
                        <th>Tasks</th>
                        <th>Damages</th>
                        <th>Additional Info</th>
                        <th>Logged By</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    if (!empty($service_logs)) {
                        foreach ($service_logs as $service) { ?>
                            <tr>
                                <td><?php echo date("d/m/Y H:i", strtotime($service["log_date"])); ?></td>
                                <td><?php echo $service["current_km"]; ?> km</td>
                                <td><?php echo htmlspecialchars($service["service_groups_name"] ?? "Unknown"); ?></td>
                                <td>
                                    <?php 
                                    // Decode JSON, handle both JSON array & comma-separated values
                                    $task_ids = json_decode($service["service_tasks"], true);
                                    if (!is_array($task_ids)) {
                                        $task_ids = explode(',', $service["service_tasks"]); // If not JSON, assume CSV
                                    }

                                    // Convert task IDs to task names
                                    $task_names = [];
                                    foreach ($task_ids as $task_id) {
                                        $task_id = trim($task_id);
                                        if (isset($service_tasks_map[$task_id])) {
                                            $task_names[] = $service_tasks_map[$task_id];
                                        }
                                    }

                                    echo !empty($task_names) ? implode(", ", $task_names) : "No Tasks Logged";
                                    ?>
                                </td>
                                <td><?php echo !empty($service["damages"]) ? htmlspecialchars($service["damages"]) : "None"; ?></td>
                                <td><?php echo !empty($service["info"]) ? htmlspecialchars($service["info"]) : "None"; ?></td>
                                <td><?php echo htmlspecialchars($usernames_map[$service["userid"]] ?? "Unknown User"); ?></td>
                            </tr>
                        <?php } 
                    } else { ?>
                        <tr>
                            <td colspan="7" class="text-center">No service history available.</td>
                        </tr>
                    <?php } ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
</div>
</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/pnotify/pnotify.custom.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>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css" />
    <!-- Examples -->
    <script src="js/examples/examples.header.menu.js"></script>
    <script src="js/examples/examples.ecommerce.orders.detail.js"></script>
    <script src="js/examples/examples.modals.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>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/rome/3.0.2/rome.standalone.min.js" integrity="sha512-cJ4aSZY0xBXrcH65MOwCloQAiTNCBm2F8/KlcBTlczgn4txZkT7h3YSXULN06pkUnsySMEg5BU4QCHAr97U7ng==" crossorigin="anonymous"></script>




    <script>
       
        
document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('service_group').addEventListener('change', function () {
        const groupId = this.value;
        if (!groupId) {
            document.getElementById('service_tasks').innerHTML = `<div class="text-danger">Please select a group.</div>`;
            return;
        }

        fetch('actions/get_service_tasks.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `service_group_id=${encodeURIComponent(groupId)}`,
        })
        .then(response => response.json())
        .then(tasks => {
            let tasksContainer = document.getElementById('service_tasks');
            tasksContainer.innerHTML = '';

            console.log("🚀 Received Service Tasks:", tasks); // Debugging output

            // Handle errors
            if (!Array.isArray(tasks)) {
                console.error("❌ Error: Response is not an array", tasks);
                tasksContainer.innerHTML = `<div class="text-danger">${tasks.error || 'Error loading service tasks.'}</div>`;
                return;
            }

            // Populate checkboxes
            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("❌ Fetch Error:", error);
            document.getElementById('service_tasks').innerHTML = `<div class="text-danger">Failed to load tasks.</div>`;
        });
    });
});


</script>


    
    
  </body>
</html> <?php include "include/footer.php"; ?>
