<?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"; 

if (isset($_SESSION['success_message'])) {
    echo "<script>alert('" . $_SESSION['success_message'] . "');</script>";
    unset($_SESSION['success_message']); // Clear the message after displaying
}
?>
<!doctype html>
<html class="fixed dark"> <?php
$fid = $_GET["id"];

$pagerole = "user";
include "include/head.php";
($sql2 = $db2->query("SELECT * FROM fleet WHERE fleet.fleet_id='$fid' ")) or
    die(mysql_error());
$row = mysqli_fetch_array($sql2);
$idcar = $row["veh_id"];
($sql2 = $db2->query(
    "SELECT * FROM jostj_vikrentcar_cars WHERE jostj_vikrentcar_cars.id=$idcar "
)) or die(mysql_error());
$row2 = mysqli_fetch_array($sql2);
($sql3 = $db2->query(
    "SELECT * FROM fleet_rtax WHERE fleet_rtax.vfleet_id='$fid' "
)) or die(mysql_error());
$row3 = mysqli_fetch_array($sql3);
$disfunct = "disabled";
// Fetch group from `jostj_vikrentcar_cars`
$car_group = $row2['name'] ?? "Not Set";

$vehicle_id = $row['veh_id']; // From the fleet table

// Query to fetch availability group
$availability_group_query = $db2->query("
    SELECT ag.name AS availability_group_name
    FROM car_availability_groups cag
    JOIN availability_groups ag ON cag.avail_group = ag.id
    WHERE cag.car_id = '$vehicle_id'
");

$fleet_id_for_insurance = $row['fleet_id']; // Correct fleet_id reference for fleet_insurance table

$history_query = $db2->query("
    SELECT * 
    FROM fleet_insurance 
    WHERE vfleet_id = '$fleet_id_for_insurance' 
    ORDER BY ins_until DESC
");
// Fetch KTEO history
$kteo_history_query = $db2->query("
    SELECT * 
    FROM fleet_kteo 
    WHERE vfleet_id = '$fleet_id_for_insurance' 
    ORDER BY kteo_date DESC
");
// Fetch Road Tax history
$road_tax_history_query = $db2->query("
    SELECT * 
    FROM fleet_rtax 
    WHERE vfleet_id = '$fleet_id_for_insurance' 
    ORDER BY road_tax_date DESC
");
// 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 = '$fleet_id_for_insurance' 
    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"];
}


// Fetch result
$availability_group_name = $availability_group_query->num_rows 
    ? $availability_group_query->fetch_assoc()['availability_group_name'] 
    : "Not Set";
?>
  <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>Vehicle Overview - <?php echo $row["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>Vehicle Overview </span>
                </li>
              </ol>
              <a class="sidebar-right-toggle" data-open="sidebar-right">
                <i class="fas fa-chevron-left"></i>
              </a>
            </div>
          </header>
          <!-- start: page -->
          <form class="order-details action-buttons-fixed" method="post" name="form1">
<div class="row">
  <div class="col-xl-12 mb-3 ">
    <div class="card">
      <div class="card-header">
        <h2 class="card-title">Vehicle Details</h2>
        <span class="editbutton">
          <a class="modal-basic btn btn-warning" href="#modalEditVehicleDetails">
            <i class="fas fa-pencil-alt"></i>
          </a>
        </span>
      </div>
      <div class="card-body">
        <div class="form-row">
          <div class="form-group col-2 mb-3 pt-0" style="border-top:none;">
            <label>Model</label>
            <input type="text" class="form-control form-control-modern"
              value="<?php echo $row2["name"] ?? "Not Set"; ?>" readonly />
          </div>
          <div class="form-group col-2 mb-3 pt-0" style="border-top:none;">
            <label>License Plate</label>
            <input type="text" class="form-control form-control-modern"
              value="<?php echo $row["lic_num"] ?? "Not Set"; ?>" readonly />
          </div>
          <div class="form-group col-1 mb-3 pt-0" style="border-top:none;">
            <label>Color</label>
            <input type="text" class="form-control form-control-modern"
              value="<?php echo $row["color"] ?? "Not Set"; ?>" readonly />
          </div>
          <div class="form-group col-2 mb-3 pt-0" style="border-top:none;">
            <label>Group</label>
            <input type="text" class="form-control form-control-modern" value="<?php echo $car_group; ?>" readonly />
          </div>

          <div class="form-group col-2 mb-3 pt-0" style="border-top:none;">
            <label>Availability Group</label>
            <input type="text" class="form-control form-control-modern" value="<?php echo $availability_group_name; ?>"
              readonly />
          </div>
          <div class="form-group col-1 mb-3 pt-0" style="border-top:none;">
            <label>Active</label>
            <input type="text" class="form-control form-control-modern"
              value="<?php echo $row["active"] == 1 ? "Yes" : "No"; ?>" readonly />
          </div>
          <div class="form-group col-2 mb-3 pt-0" style="border-top:none;">
            <label>Sold</label>
            <input type="text" class="form-control form-control-modern"
              value="<?php echo $row["fleet_sold"] == 1 ? "Yes - " . date("d/m/Y", $row["fleet_sold_date"]) : "No"; ?>"
              readonly />
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<div class="row">
  <!-- changes -->
  <div class="col-xl-4 mb-3 ">
  <div class="card">
      <div class="card-header">
        <h2 class="card-title">Insurance
          <span class="editbutton">
            <a class="modal-basic btn btn-warning" href="#modalEditInsurance">
              <i class="fas fa-pencil-alt"></i>
            </a>
          </span>
        </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>Insurance Company</label>
            <input type="text" class="form-control form-control-modern"
              value="<?php echo $row["fleet_ins_company"] ?? "Not Set"; ?>" readonly />
          </div>
        
          <div class="form-group col-4 mb-3 pt-0" style="border-top:none;">
            <label>Insurance From</label>
            <input type="text" class="form-control form-control-modern"
              value="<?php echo !empty($row["fleet_insurance_from"]) ? date("d/m/Y H:i", $row["fleet_insurance_from"]) : "Not Set"; ?>"
              readonly />
          </div>
          <div class="form-group col-4 mb-3 pt-0" style="border-top:none;">
            <label>Insurance Until</label>
            <input type="text" class="form-control form-control-modern" name="fleet_insurance_until"
              value="<?php echo !empty($row["fleet_insurance_until"]) ? date("d/m/Y H:i", $row["fleet_insurance_until"]) : "Not Set"; ?>"
              readonly />
          </div>
        </div>
      </div>
    </div>
   
<!-- Collapsible Card for Insurance History -->
<div class="card card-collapsed">
    <header class="card-header">
        <h2 class="card-title">Insurance 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>Insurance Company</th>
                        <th>Start Date</th>
                        <th>End Date</th>
                        <th>Cost (€)</th>
                    </tr>
                </thead>
          <tbody>
    <?php 
    if ($history_query->num_rows > 0) {
        while ($history = $history_query->fetch_assoc()) { 
            $isCostZero = ($history["ins_cost"] == 0.00); ?>
            <tr>
                <td><?php echo htmlspecialchars($history["ins_company"]); ?></td>
                <td><?php echo date("d/m/Y", $history["ins_from"]); ?></td>
                <td><?php echo date("d/m/Y", $history["ins_until"]); ?></td>
                <td>
                    <?php if ($isCostZero) { ?>
                        <!-- Show Add Cost Button -->
                        <button class="btn btn-success btn-sm add-cost-btn"
                            data-ins-id="<?php echo $history["fleet_ins_id"]; ?>">
                            +
                        </button>
                    <?php } else { ?>
                        <!-- Show Cost Without Edit Button -->
                        <span class="cost-value">
                            <?php echo number_format($history["ins_cost"], 2); ?> €
                        </span>
                    <?php } ?>
                </td>
            </tr>
        <?php } 
    } else { ?>
        <tr>
            <td colspan="4" class="text-center">No insurance history available.</td>
        </tr>
    <?php } ?>
</tbody>

            </table>
        </div>
    </div>
</div>


  </div>

  <div class="col-xl-4">
  
    <div class="card">
      <div class="card-header">
        <h2 class="card-title">KTEO <span class="editbutton">
            <a class="modal-basic btn btn-warning" href="#modalEditKTEO">
              <i class="fas fa-pencil-alt"></i>
            </a>
          </span>
        </h2>
      </div>
      <div class="card-body">
        <div class="form-row">
          <div class="form-group col-12 mb-3 pt-0" style="border-top:none;">
            <label>KTEO Until</label>
            <input type="text" name="fleet_kteo" class="form-control form-control-modern"
              value="<?php echo !empty($row["fleet_kteo"]) ? date("d/m/Y", $row["fleet_kteo"]) : "Not Set"; ?>"
              readonly />
          </div>
        </div>
      </div>
    </div>
<!-- Collapsible Card for KTEO History -->
<div class="card card-collapsed">
    <header class="card-header">
        <h2 class="card-title">KTEO 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>Passed Date</th>
                        <th>Next Due Date</th>
                        <th>Center</th>
                        <th>Cost (€)</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    if ($kteo_history_query->num_rows > 0) {
                        while ($kteo = $kteo_history_query->fetch_assoc()) { 
                            $isCostZero = ($kteo["kteo_cost"] == 0.00);
                            ?>
                            <tr>
                                <td><?php echo date("d/m/Y", $kteo["kteo_passed_date"]); ?></td>
                                <td><?php echo date("d/m/Y", $kteo["kteo_date"]); ?></td>
                                <td><?php echo htmlspecialchars($kteo["kteo_center"]); ?></td>
                                <td>
                                    <?php if ($isCostZero) { ?>
                                        <!-- Show Add Cost Button -->
                                        <button class="btn btn-success btn-sm add-kteo-cost-btn"
                                            data-kteo-id="<?php echo $kteo["fleet_kteo_id"]; ?>">
                                            +
                                        </button>
                                    <?php } else { ?>
                                        <!-- Show Cost Without Edit Button -->
                                        <span class="kteo-cost-value">
                                            <?php echo number_format($kteo["kteo_cost"], 2); ?> €
                                        </span>
                                    <?php } ?>
                                </td>
                            </tr>
                        <?php } 
                    } else { ?>
                        <tr>
                            <td colspan="4" class="text-center">No KTEO history available.</td>
                        </tr>
                    <?php } ?>
                </tbody>
            </table>
        </div>
    </div>
</div>


  </div>
  <div class="col-xl-4">
   <div class="card">
      <div class="card-header">
        <h2 class="card-title">Road Tax <span class="editbutton">
            <a class="modal-basic btn btn-warning" href="#modalEditRoadTax">
              <i class="fas fa-pencil-alt"></i>
            </a>
          </span>
        </h2>
      </div>
      <div class="card-body">
        <div class="form-row">
          <div class="form-group col-12 mb-3 pt-0" style="border-top:none;">
            <label>Road Tax Until</label>
            <input type="text" name="road_tax" class="form-control form-control-modern"
              value="<?php echo !empty($row["road_tax"]) ? date("d/m/Y", $row["road_tax"]) : "Not Set"; ?>" readonly />
          </div>
        </div>
      </div>
    </div>
    <!-- Collapsible Card for Road Tax History -->
<div class="card card-collapsed">
    <header class="card-header">
        <h2 class="card-title">Road Tax 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>Year</th>
                        <th>Paid Date</th>
                        <th>Cost (€)</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    if ($road_tax_history_query->num_rows > 0) {
                        while ($road_tax = $road_tax_history_query->fetch_assoc()) { 
                            $isCostZero = ($road_tax["fleet_rtax_cost"] == 0.00);
                            ?>
                            <tr>
                                <td><?php echo date("Y", $road_tax["road_tax"]); ?></td>
                                <td><?php echo date("d/m/Y", $road_tax["road_tax_date"]); ?></td>
                                <td>
                                    <?php if ($isCostZero) { ?>
                                        <!-- Show Add Cost Button -->
                                        <button class="btn btn-success btn-sm add-road-tax-cost-btn"
                                            data-road-tax-id="<?php echo $road_tax["fleet_rtax_id"]; ?>">
                                            +
                                        </button>
                                    <?php } else { ?>
                                        <!-- Show Cost Without Edit Button -->
                                        <span class="road-tax-cost-value">
                                            <?php echo number_format($road_tax["fleet_rtax_cost"], 2); ?> €
                                        </span>
                                    <?php } ?>
                                </td>
                            </tr>
                        <?php } 
                    } else { ?>
                        <tr>
                            <td colspan="3" class="text-center">No Road Tax history available.</td>
                        </tr>
                    <?php } ?>
                </tbody>
            </table>
        </div>
    </div>
</div>


  </div>
  <div class="col-xl-12 mb-3 mt-3">
  <div class="card">
      <div class="card-header">
        <h2 class="card-title">Service <span class="editbutton">
            <a class=" btn btn-success" href="log_service.php?veh_id=<?php echo $fleet_id_for_insurance; ?>">
            <i class="fas fa-plus"></i>
            </a>
          </span>

</h2>
      </div>
      <div class="card-body">
        <div class="form-row">
          <div class="form-group col-3 mb-3 pt-0" style="border-top:none;">
            <label>Last Service Date</label>
            <input type="text" class="form-control form-control-modern" value="<?php echo !empty($row["fleet_last_service"]) ? date("d/m/Y", $row["fleet_last_service"])
              : "Not Set"; ?>" readonly />
          </div>
          <div class="form-group col-3 mb-3 pt-0" style="border-top:none;">
            <label>Last Service KM</label>
            <input type="text" class="form-control form-control-modern"
              value="<?php echo $row["fleet_last_serv_km"] ?? "Not Set"; ?>" readonly />
          </div>
       
          <div class="form-group col-3 mb-3 pt-0" style="border-top:none;">
            <label>Next Service Date</label>
            <input type="text" class="form-control form-control-modern" name="fleet_next_service"
              value="<?php echo !empty($row["fleet_next_service"]) ? date("d/m/Y", $row["fleet_next_service"]) : "Not Set"; ?>"
              readonly />
          </div>
          <div class="form-group col-3 mb-3 pt-0" style="border-top:none;">
            <label>Next Service KM</label>
            <input type="text" class="form-control form-control-modern"
              value="<?php echo $row["fleet_next_serv_km"] ?? "Not Set"; ?>" readonly />
          </div>
        </div>
      </div>
    </div>
<!-- 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 number_format($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 class="col-xl-12 mb-3 mt-3">
      <div class="card card">
      <div class="card-header">
        <h2 class="card-title">Notes
          <span class="editbutton">
            <a class="modal-basic btn btn-warning" href="#modalEditNotes"
              onclick="openEditNotesModal('<?php echo $row['fleet_id']; ?>', '<?php echo addslashes($row['notes']); ?>')">
              <i class="fas fa-pencil-alt"></i>
            </a>

          </span>
        </h2>
      </div>
      <div class="card-body">
        <div class="form-row">
          <div class="form-group col-xl-12 mb-3">
            <label>Vehicle Notes</label>
            <textarea rows="10" class="form-control" name="fleet_notes" id="fleet_notes" readonly>
                    <?php echo $row["notes"] ?? "No Notes Available"; ?>
                </textarea>
          </div>
        </div>
      </div>
    </div>
  </div>
  </div>
  <div class="col-xl-12 mb-3 mt-3">

<div class="card card">
    <div class="card-header">
        <h2 class="card-title">Vehicle Action Log</h2>
    </div>
    <div class="card-body">
        <div class="ecommerce-timeline mb-3">
            <div class="ecommerce-timeline-items-wrapper">
                <?php
                // Fetch action logs for this vehicle
                $sqllog = "SELECT * FROM action_logs WHERE details LIKE '%fleet_id=$fid%' ORDER BY timestamp DESC";
                $result = mysqli_query($db2, $sqllog);

                while ($rowlog = mysqli_fetch_array($result)) {
                    $username = $rowlog["user"]; // Username stored directly in action_logs

                    ?>
                    <div class="ecommerce-timeline-item">
                        <small>Added on
                            <?php echo date("d/m/Y", strtotime($rowlog["timestamp"])); ?> at
                            <?php echo date("H:i", strtotime($rowlog["timestamp"])); ?> by
                            <?php echo $username; ?>
                        </small>
                        <p>
                            <?php echo $rowlog["action"]; ?> - 
                            <strong><?php echo $rowlog["details"]; ?></strong>
                        </p>
                    </div>
                    <?php
                }
                ?>
            </div>
        </div>
    </div>
</div>



  </div>

          </form>
          <!-- 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 () {
    // Function to parse DD/MM/YYYY HH:mm into a Date object
    function parseDate(input) {
      const parts = input.split(' '); // Split date and time
      const dateParts = parts[0].split('/'); // Split DD/MM/YYYY

      if (dateParts.length === 3) {
        const timeParts = parts[1] ? parts[1].split(':') : ['00', '00']; // Default to 00:00 if no time
        return new Date(
          parseInt(dateParts[2]),  // Year
          parseInt(dateParts[1]) - 1,  // Month (0-based)
          parseInt(dateParts[0]),  // Day
          parseInt(timeParts[0]),  // Hours
          parseInt(timeParts[1])   // Minutes
        );
      }
      return null; // Invalid date format
    }

    // Get all the relevant date input fields
    const dateFields = [{
      id: 'fleet_insurance_until',
      label: 'Insurance Until'
    }, {
      id: 'fleet_next_service',
      label: 'Next Service Date'
    }, {
      id: 'fleet_kteo',
      label: 'KTEO Until'
    }, {
      id: 'road_tax',
      label: 'Road Tax Until'
    }];

    // Get the current date
    const currentDate = new Date();
    console.log('Current Date:', currentDate); // Debugging log

    // Iterate through each field and check the date
    dateFields.forEach(field => {
      const inputElement = document.querySelector(`[name="${field.id}"]`);
      if (inputElement) {
        console.log(`Checking field: ${field.label}`); // Debugging log
        console.log(`Input Value: ${inputElement.value}`); // Debugging log

        // Parse the date using the updated function
        const inputDate = parseDate(inputElement.value);
        console.log(`Parsed Date for ${field.label}:`, inputDate); // Debugging log

        // Check if the input date is in the past
        if (inputElement.value && inputDate && inputDate < currentDate) {
          console.log(`The date for ${field.label} is past due.`); // Debugging log
          // Highlight the input border in red
          inputElement.style.border = '2px solid red';
        } else {
          console.log(`The date for ${field.label} is not past due.`); // Debugging log
        }
      } else {
        console.log(`Field ${field.label} not found.`); // Debugging log
      }
    });
  });
</script>

   
   <div id="modalEditNotes" class="modal-block modal-block-primary mfp-hide">
    <section class="card">
        <header class="card-header">
            <h2 class="card-title">Edit Vehicle Notes</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="editNotesForm">
                <div class="form-group">
                    <input type="hidden" id="fleet_id" name="fleet_id">
                    <label for="fleet_notes_edit">Notes</label>
                    <textarea class="form-control" id="fleet_notes_edit" name="notes" rows="5"></textarea>
                </div>
            </form>
        </div>
        <footer class="card-footer">
            <div class="row">
                <div class="col-md-12 text-right">
                    <button type="button" class="btn btn-primary" id="submit-edit-notes">Save Changes</button>
                </div>
            </div>
        </footer>
    </section>
</div>
<!--NEW-->
<div id="modalEditVehicleDetails" class="modal-block modal-block-primary mfp-hide">
    <section class="card">
        <header class="card-header">
            <h2 class="card-title">Edit Vehicle Details</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="editVehicleDetailsForm">
                <input type="hidden" name="fleet_id" value="<?php echo $row["fleet_id"]; ?>" />

                <div class="form-group">
                    <label>Active</label>
                    <select class="form-control" name="fleet_active">
                        <option value="1" <?php echo $row["active"] == 1 ? "selected" : ""; ?>>Yes</option>
                        <option value="0" <?php echo $row["active"] == 0 ? "selected" : ""; ?>>No</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>Sold</label>
                    <select class="form-control" id="fleet_sold" name="fleet_sold" onchange="toggleSoldDate(this)">
                        <option value="1" <?php echo $row["fleet_sold"] == 1 ? "selected" : ""; ?>>Yes</option>
                        <option value="0" <?php echo $row["fleet_sold"] == 0 ? "selected" : ""; ?>>No</option>
                    </select>
                </div>

                <div class="form-group" id="soldDateField" style="display: <?php echo $row["fleet_sold"] == 1 ? 'block' : 'none'; ?>;">
                    <label>Sold Date</label>
                    <input type="text" class="form-control" id="fleet_sold_date" name="fleet_sold_date" 
                        value="<?php echo !empty($row["fleet_sold_date"]) ? date("d/m/Y", $row["fleet_sold_date"]) : ""; ?>" />
                </div>
            </form>
        </div>
        <footer class="card-footer">
            <div class="row">
                <div class="col-md-12 text-right">
                    <button type="button" class="btn btn-primary" id="submit-edit-vehicle-details">Save Changes</button>
                </div>
            </div>
        </footer>
    </section>
</div>
 <div id="modalEditRoadTax" class="modal-block modal-block-primary mfp-hide">
    <section class="card">
        <header class="card-header">
            <h2 class="card-title">Edit Road Tax</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="editRoadTaxForm">
                <input type="hidden" name="fleet_id" value="<?php echo $row["fleet_id"]; ?>" />

                <div class="form-group">
                    <label for="road_tax_year">Road Tax Year</label>
                    <input type="number" class="form-control" id="road_tax_year" name="road_tax_year" placeholder="Enter Year (e.g., 2024)" required />
                </div>

                <div class="form-group">
                    <label for="road_tax_date">Taxed On (Date Paid)</label>
                    <input type="text" class="form-control" id="road_tax_date" name="road_tax_date" placeholder="Select Date" required />
                </div>

                <div class="form-group">
                    <label for="fleet_rtax_cost">Road Tax Cost (€)</label>
                    <input type="text" class="form-control" id="fleet_rtax_cost" name="fleet_rtax_cost" placeholder="Enter Cost with .00" required />
                </div>
            </form>
        </div>
        <footer class="card-footer">
            <div class="row">
                <div class="col-md-12 text-right">
                    <button type="button" class="btn btn-primary" id="submit-edit-road-tax">Save Changes</button>
                </div>
            </div>
        </footer>
    </section>
</div>

<div id="modalEditInsurance" class="modal-block modal-block-primary mfp-hide">
    <section class="card">
        <header class="card-header">
            <h2 class="card-title">Edit Insurance</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="editInsuranceForm">
                <input type="hidden" name="fleet_id" value="<?php echo $row["fleet_id"]; ?>" />

                <div class="form-group">
                    <label for="ins_company">Insurance Company</label>
                    <input type="text" class="form-control" id="ins_company" name="ins_company" required />
                </div>

                <div class="form-group">
                    <label for="ins_from">Insurance From</label>
                    <input type="text" class="form-control" id="ins_from" name="ins_from" required />
                </div>

                <div class="form-group">
                    <label for="ins_until">Insurance Until</label>
                    <input type="text" class="form-control" id="ins_until" name="ins_until" required />
                </div>

                <div class="form-group">
                    <label for="ins_cost">Insurance Cost (€)</label>
                    <input type="text" class="form-control" id="ins_cost" name="ins_cost" required />
                </div>
            </form>
        </div>
        <footer class="card-footer">
            <div class="row">
                <div class="col-md-12 text-right">
                    <button type="button" class="btn btn-primary" id="submit-edit-insurance">Save Changes</button>
                </div>
            </div>
        </footer>
    </section>
</div>
<div id="modalEditKTEO" class="modal-block modal-block-primary mfp-hide">
    <section class="card">
        <header class="card-header">
            <h2 class="card-title">Edit KTEO</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="editKTEOForm">
                <input type="hidden" name="fleet_id" value="<?php echo $row["fleet_id"]; ?>" />

                <div class="form-group">
                    <label for="kteo_passed_date">KTEO Passed Date</label>
                    <input type="text" class="form-control" id="kteo_passed_date" name="kteo_passed_date" required />
                </div>

                <div class="form-group">
                    <label for="kteo_date">Next KTEO Date</label>
                    <input type="text" class="form-control" id="kteo_date" name="kteo_date" required />
                </div>

                <div class="form-group">
                    <label for="kteo_center">KTEO Center</label>
                    <input type="text" class="form-control" id="kteo_center" name="kteo_center" required />
                </div>

                <div class="form-group">
                    <label for="kteo_cost">KTEO Cost (€)</label>
                    <input type="text" class="form-control" id="kteo_cost" name="kteo_cost" required />
                </div>
            </form>
        </div>
        <footer class="card-footer">
            <div class="row">
                <div class="col-md-12 text-right">
                    <button type="button" class="btn btn-primary" id="submit-edit-kteo">Save Changes</button>
                </div>
            </div>
        </footer>
    </section>
</div>



    <script>
     
    document.addEventListener('DOMContentLoaded', function () {
        // Initialize Rome.js for date inputs
        const options = {
        "appendTo": document.body,
        "autoClose": false,
        "autoHideOnBlur": true,
        "autoHideOnClick": false,
        "date": true,
        "dateValidator": Function.prototype,
        "dayFormat": "DD",
        "initialValue": null,
        "inputFormat": "DD-MM-YYYY HH:mm",
        "invalidate": true,
        "max": null,
        "min": null,
        "monthFormat": "MMMM YYYY",
        "monthsInCalendar": 1,
        "required": false,
        "strictParse": false,
        "styles": {
          "back": "rd-back",
          "container": "rd-container",
          "date": "rd-date",
          "dayBody": "rd-days-body",
          "dayBodyElem": "rd-day-body",
          "dayConcealed": "rd-day-concealed",
          "dayDisabled": "rd-day-disabled",
          "dayHead": "rd-days-head",
          "dayHeadElem": "rd-day-head",
          "dayRow": "rd-days-row",
          "dayTable": "rd-days",
          "month": "rd-month",
          "next": "rd-next",
          "positioned": "rd-container-attachment",
          "selectedDay": "rd-day-selected",
          "selectedTime": "rd-time-selected",
          "time": "rd-time",
          "timeList": "rd-time-list",
          "timeOption": "rd-time-option"
        },
        "time": true,
        "timeFormat": "HH:mm",
        "timeInterval": 900,
        "timeValidator": Function.prototype,
        "weekdayFormat": "min",
        "weekStart": moment().weekday(0).day()
      }
        rome(road_tax_date, options);
       </script>
       <script>

    
document.addEventListener('DOMContentLoaded', function () {
    // Function to open the modal with preloaded data
    window.openEditNotesModal = function (fleetId, notes) {
        console.log('Fleet ID:', fleetId); // Debugging log
        console.log('Notes:', notes); // Debugging log

        // Set the fleet ID in the hidden input
        const fleetIdInput = document.getElementById('fleet_id');
        if (fleetIdInput) {
            fleetIdInput.value = fleetId || '';
        }

        // Set the notes in the textarea
        const notesTextarea = document.getElementById('fleet_notes_edit');
        if (notesTextarea) {
            notesTextarea.value = notes || ''; // Use empty string if notes are null
        }

        // Open the modal
        $.magnificPopup.open({
            items: {
                src: '#modalEditNotes'
            },
            type: 'inline'
        });
    };

    // Handle form submission
    document.getElementById('submit-edit-notes').addEventListener('click', function () {
        const form = document.getElementById('editNotesForm');
        const formData = new FormData(form);

        fetch('actions/update_notes.php', {
            method: 'POST',
            body: formData,
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Notes updated 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.');
            });
    });
});

//NEW

    function toggleSoldDate(select) {
        var soldDateField = document.getElementById('soldDateField');
        if (select.value == "1") {
            soldDateField.style.display = "block";
        } else {
            soldDateField.style.display = "none";
        }
    }

    document.addEventListener('DOMContentLoaded', function () {
        rome(fleet_sold_date, { inputFormat: "DD-MM-YYYY" });

        document.getElementById('submit-edit-vehicle-details').addEventListener('click', function () {
            const form = document.getElementById('editVehicleDetailsForm');
            const formData = new FormData(form);

            fetch('actions/fleet/update_vehicle_details.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Vehicle details updated successfully!');
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'Unknown error occurred.'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred. Please try again.');
            });
        });
    });
    
       //ROAD TAX
    document.addEventListener('DOMContentLoaded', function () {
        rome(road_tax_date, { inputFormat: "DD-MM-YYYY" });

        document.getElementById('submit-edit-road-tax').addEventListener('click', function () {
            const form = document.getElementById('editRoadTaxForm');
            const formData = new FormData(form);

            fetch('actions/fleet/update_road_tax.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Road Tax updated successfully!');
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'Unknown error occurred.'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred. Please try again.');
            });
        });
    });
   //ROAD TAX
   //insurance

    document.addEventListener('DOMContentLoaded', function () {
        // Rome.js configuration to prevent closing when selecting a month
        const romeOptions = {
            inputFormat: "DD-MM-YYYY",
            time: false, // No time selection
            autoClose: true, // Prevent closing on selection
            autoHideOnBlur: false, // Keep it open when clicking outside
            autoHideOnClick: false, // Prevent closing when selecting months
        };

        // Apply Rome.js to insurance date fields
        rome(ins_from, romeOptions);
        rome(ins_until, romeOptions);

        // Submit form when clicking save
        document.getElementById('submit-edit-insurance').addEventListener('click', function () {
            const form = document.getElementById('editInsuranceForm');
            const formData = new FormData(form);

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


   //insurance
   
   //kteo
   

    document.addEventListener('DOMContentLoaded', function () {
        // Rome.js configuration for KTEO Date Fields
        const romeOptions = {
            inputFormat: "DD-MM-YYYY",
            time: false, // No time selection
            autoClose: true, // Prevent closing on selection
            autoHideOnBlur: false, // Keep it open when clicking outside
            autoHideOnClick: false, // Prevent closing when selecting months
        };

        // Function to initialize Rome.js for KTEO fields
        function initRomePickers() {
            let passedDateField = document.getElementById('kteo_passed_date');
            let nextDateField = document.getElementById('kteo_date');

            if (passedDateField && !passedDateField.dataset.romeAttached) {
                rome(passedDateField, romeOptions);
                passedDateField.dataset.romeAttached = "true"; // Prevent multiple initializations
            }

            if (nextDateField && !nextDateField.dataset.romeAttached) {
                rome(nextDateField, romeOptions);
                nextDateField.dataset.romeAttached = "true"; // Prevent multiple initializations
            }
        }

        // Listen for modal opening to reinitialize Rome.js
        let kteoEditButton = document.querySelector('[href="#modalEditKTEO"]');
        if (kteoEditButton) {
            kteoEditButton.addEventListener('click', function () {
                setTimeout(initRomePickers, 200); // Delay initialization to ensure modal is rendered
            });
        }

        // Submit KTEO form when clicking save
        let submitButton = document.getElementById('submit-edit-kteo');
        if (submitButton) {
            submitButton.addEventListener('click', function () {
                const form = document.getElementById('editKTEOForm');
                if (!form) return;

                const formData = new FormData(form);

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


   //kteo
  // inline cost
document.addEventListener("DOMContentLoaded", function () {
    // When clicking the "+ Add Cost" button
   
    document.querySelectorAll(".add-cost-btn").forEach(button => {
        button.addEventListener("click", function () {
            let insId = this.getAttribute("data-ins-id");
            let newCost = prompt("Enter insurance cost (€):").trim();
            
            if (newCost === "" || isNaN(newCost) || parseFloat(newCost) < 0) {
                alert("❌ Please enter a valid insurance cost.");
                return;
            }
            
            updateInsuranceCost(insId, parseFloat(newCost));
        });
    });

    // When clicking the "✎" Edit button
    document.querySelectorAll(".edit-cost-btn").forEach(button => {
        button.addEventListener("click", function () {
            let insId = this.getAttribute("data-ins-id");
            let currentCost = this.getAttribute("data-current-cost");
            let newCost = prompt("Update insurance cost (€):", currentCost).trim();
            
            if (newCost === "" || isNaN(newCost) || parseFloat(newCost) < 0) {
                alert("❌ Please enter a valid insurance cost.");
                return;
            }
            
            updateInsuranceCost(insId, parseFloat(newCost));
        });
    });

    // Function to update insurance cost via AJAX
function updateInsuranceCost(insId, cost) {
    console.log(`🚀 Sending Update: fleet_ins_id=${insId}, ins_cost=${cost}`);

    fetch("actions/fleet/update_insurance_cost.php", {  
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: `fleet_ins_id=${encodeURIComponent(insId)}&ins_cost=${encodeURIComponent(cost)}`
    })
    .then(response => response.json())
    .then(data => {
        console.log("🚀 Server Response:", data); // Log full server response

        if (data.success) {
            alert("✅ Insurance cost updated successfully!");
            location.reload(); 
        } else {
            alert("❌ Error: " + (data.message || "Unknown error occurred."));
        }
    })
    .catch(error => {
        console.error("❌ Fetch Error:", error); // Log fetch error
        alert("❌ An error occurred. Check console for details.");
    });
}

});
document.addEventListener("DOMContentLoaded", function () {
    // When clicking the "+ Add Cost" button for KTEO
    document.querySelectorAll(".add-kteo-cost-btn").forEach(button => {
        button.addEventListener("click", function () {
            let kteoId = this.getAttribute("data-kteo-id");
            let newCost = prompt("Enter KTEO cost (€):").trim();
            
            if (newCost === "" || isNaN(newCost) || parseFloat(newCost) < 0) {
                alert("❌ Please enter a valid KTEO cost.");
                return;
            }
            
            updateKTEOCost(kteoId, parseFloat(newCost));
        });
    });

    // Function to update KTEO cost via AJAX
    function updateKTEOCost(kteoId, cost) {
        fetch("actions/fleet/update_kteo_cost.php", {  
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: `fleet_kteo_id=${encodeURIComponent(kteoId)}&kteo_cost=${encodeURIComponent(cost)}`
        })
        .then(response => response.json())
        .then(data => {
            console.log("🚀 Server Response:", data); // Log full server response

            if (data.success) {
                alert("✅ KTEO cost updated successfully!");
                location.reload(); 
            } else {
                alert("❌ Error: " + (data.message || "Unknown error occurred."));
            }
        })
        .catch(error => {
            console.error("❌ Fetch Error:", error); // Log fetch error
            alert("❌ An error occurred. Check console for details.");
        });
    }
});
document.addEventListener("DOMContentLoaded", function () {
    // When clicking the "+ Add Cost" button for Road Tax
    document.querySelectorAll(".add-road-tax-cost-btn").forEach(button => {
        button.addEventListener("click", function () {
            let roadTaxId = this.getAttribute("data-road-tax-id");
            let newCost = prompt("Enter Road Tax cost (€):").trim();
            
            if (newCost === "" || isNaN(newCost) || parseFloat(newCost) < 0) {
                alert("❌ Please enter a valid Road Tax cost.");
                return;
            }
            
            updateRoadTaxCost(roadTaxId, parseFloat(newCost));
        });
    });

    // Function to update Road Tax cost via AJAX
    function updateRoadTaxCost(roadTaxId, cost) {
        fetch("actions/fleet/update_road_tax_cost.php", {  
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: `fleet_rtax_id=${encodeURIComponent(roadTaxId)}&fleet_rtax_cost=${encodeURIComponent(cost)}`
        })
        .then(response => response.json())
        .then(data => {
            console.log("🚀 Server Response:", data); // Log full server response

            if (data.success) {
                alert("✅ Road Tax cost updated successfully!");
                location.reload(); 
            } else {
                alert("❌ Error: " + (data.message || "Unknown error occurred."));
            }
        })
        .catch(error => {
            console.error("❌ Fetch Error:", error); // Log fetch error
            alert("❌ An error occurred. Check console for details.");
        });
    }
});

// inline cost


</script>


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