<?php 
// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Log errors to a file (optional)
ini_set('log_errors', 1);
ini_set('error_log', 'error_log.txt'); // Change 'error_log.txt' to your preferred path


include('include/auth.php'); 
 $dateTimeZone = new DateTimeZone("Europe/Athens");
 $dateTime = new DateTime("now", $dateTimeZone);
 $timeOffset = $dateTimeZone->getOffset($dateTime);
 $today = time() + $timeOffset;
if (isset($_GET['status'])  && $_GET['status']!='all') {
    $status=$_GET['status'];}
    else {$status='all';}
    if (isset($_GET['id'])  && $_GET['id']!='all') {
        $fid=$_GET['id'];}
        else {$fid='all';}

        if (isset($_GET['sold'])  && $_GET['sold']!='all') {
            $sold=$_GET['sold'];}
            else {$sold='all';} 
            if (isset($_GET['kteo'])  && $_GET['kteo']!='all') {
                $kteo=$_GET['kteo'];}
                else {$kteo='all';}  
                if (isset($_GET['ins'])  && $_GET['ins']!='all') {
                    $ins=$_GET['ins'];}
                    else {$ins='all';}  
                    
                    if (isset($_GET['tax'])  && $_GET['tax']!='all') {
                        $tax=$_GET['tax'];}
                        else {$tax='all';} 
                
$today3= strtotime("+3 months",$today);
$today6= strtotime("+6 months",$today);
?>
<!doctype html>
<html class="fixed dark">
<?php 
	$pagerole="lists";
	include('include/head.php');
	
    if ($fid=="all") {$fleet="All";}
    else{
    $sql8 = $db2->query("SELECT * FROM jostj_vikrentcar_cars WHERE jostj_vikrentcar_cars.id='$fid' ") or die(mysql_error());
$row8 = mysqli_fetch_array( $sql8 ); 
$fleet=$row8['name'];}

// Execute the query for vehicle statuses
$status_query = $db2->query("
    SELECT 
        f.fleet_id,
        f.active,
        vstat.vehicle_status_name AS latest_status,
        vstat.vehicle_status_color AS badge_color,
        MAX(vs.timestamp) AS status_timestamp
    FROM fleet f
    LEFT JOIN vehicle_status vs ON f.fleet_id = vs.veh_id
    LEFT JOIN vehicle_statuses vstat ON vs.status_id = vstat.vehicle_status_id
    WHERE f.active = 1
    GROUP BY f.fleet_id
    ORDER BY vs.timestamp DESC
");

if (!$status_query) {
    die("Vehicle Status Query Failed: " . $db2->error);
}

// Build a map for quick lookup
$vehicle_status_map = []; // Initialize map
while ($row = $status_query->fetch_assoc()) {
    $vehicle_status_map[$row['fleet_id']] = [
        'status' => $row['latest_status'] ?? 'Available',
        'badge_color' => $row['badge_color'] ?? 'success' // Default to success if no status
    ];
}

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

    .red {
        color: red !important;
    }
    .disabled {
    pointer-events: none;
    opacity: 0.5;
    cursor: not-allowed;
}
.rd-container {
       position: fixed !important;
    top: 50% !important;
    left: 50% !important;
    transform: translate(-50%, -50%) !important;
    z-index: 10002;
    zoom: 140%;
        
  
}

</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 -->
        <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>All <?php echo $fleet;?> Fleet</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>All <?php echo $fleet;?> Fleet</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 "Δεν έχετε Διακαιώματα για αυτή την λειτουργία";}
				else {

?>
<div class="row mb-3">
    <div class="col-md-12 text-right">
        <button class="btn btn-primary" id="add-vehicle-btn">+ Add Vehicle</button>
    </div>
</div>
                 <h3>Filters</h3>
                <div class="row mb-0">
                <div class="col-md-2"> <label>Vehicle</label>
                        <select class="form-control populate" onChange="window.location.href=this.value">
                        <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("id"=>"all")))?>"
                                <?php if($fid=="all") { echo "selected";} ?>>
                                All</option>
                                <?php $sqlin3 = $db2->query("SELECT * FROM jostj_vikrentcar_cars ") or die(mysql_error()); 
					 while($rowin3 = mysqli_fetch_array($sqlin3)) {
                        
                         ?>
                          <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("id"=>$rowin3['id'])))?>"
                                <?php if($fid==$rowin3['id']) { echo "selected";} ?>>
                                <?php echo $rowin3['name'];?></option>
                             <?php } ?>
                               
                            </select>
                    </div>
                    <div class="col-md-2"> <label>Status</label>
                        <select class="form-control populate" onChange="window.location.href=this.value">
                        <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("status"=>"all")))?>"
                                <?php if($status=="all") { echo "selected";} ?>>
                                All</option>
                                <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("status"=>"1;")))?>"
                                <?php if($status=="1;") { echo "selected";} ?>>
                                Active</option>
                                <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("status"=>"0;")))?>"
                                <?php if($status=="0;") { echo "selected";} ?>>
                                Inactive</option>
                               
                            </select>
                    </div>
                    <div class="col-md-2"> <label>Sold</label>
                        <select class="form-control populate" onChange="window.location.href=this.value">
                        <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("sold"=>"all")))?>"
                                <?php if($sold=="all") { echo "selected";} ?>>
                                All</option>
                                <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("sold"=>"1")))?>"
                                <?php if($sold=="1") { echo "selected";} ?>>
                                Sold</option>
                                <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("sold"=>"0")))?>"
                                <?php if($sold=="0") { echo "selected";} ?>>
                                Not Sold</option>
                               
                            </select>
                    </div>
                    <div class="col-md-2"> <label>KTEO</label>
                        <select class="form-control populate" onChange="window.location.href=this.value">
                        <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("kteo"=>"all")))?>"
                                <?php if($kteo=="all") { echo "selected";} ?>>
                                All</option>
                                <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("kteo"=>"2")))?>"
                                <?php if($kteo=="2") { echo "selected";} ?>>
                                Expired</option>
                                <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("kteo"=>"1")))?>"
                                <?php if($kteo=="1") { echo "selected";} ?>>
                                Active +3 months</option>
                                <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("kteo"=>"3")))?>"
                                <?php if($kteo=="3") { echo "selected";} ?>>
                                Active +6 months</option>
                                <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("kteo"=>"0")))?>"
                                <?php if($kteo=="0") { echo "selected";} ?>>
                               Due Soon +3 months</option>
                               
                            </select>
                    </div>
                    <div class="col-md-2"> <label>INSURANCE</label>
                        <select class="form-control populate" onChange="window.location.href=this.value">
                        <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("ins"=>"all")))?>"
                                <?php if($ins=="all") { echo "selected";} ?>>
                                All</option>
                                <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("ins"=>"4")))?>"
                                <?php if($ins=="4") { echo "selected";} ?>>
                                Insured</option>
                                <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("ins"=>"2")))?>"
                                <?php if($ins=="2") { echo "selected";} ?>>
                                Expired</option>
                                <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("ins"=>"1")))?>"
                                <?php if($ins=="1") { echo "selected";} ?>>
                                Active +3 months</option>
                                <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("ins"=>"3")))?>"
                                <?php if($ins=="3") { echo "selected";} ?>>
                                Active +6 months</option>
                                <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("ins"=>"0")))?>"
                                <?php if($ins=="0") { echo "selected";} ?>>
                               Due Soon +3 months</option>
                               
                            </select>
                    </div>
                    <div class="col-md-2"> <label>ROAD TAX</label>
                        <select class="form-control populate" onChange="window.location.href=this.value">
                        <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("tax"=>"all")))?>"
                                <?php if($tax=="all") { echo "selected";} ?>>
                                All</option>
                                <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("tax"=>"4")))?>"
                                <?php if($tax=="4") { echo "selected";} ?>>
                                Taxed</option>
                                <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("tax"=>"2")))?>"
                                <?php if($tax=="2") { echo "selected";} ?>>
                                Expired</option>
                                <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("tax"=>"1")))?>"
                                <?php if($tax=="1") { echo "selected";} ?>>
                                Active +3 months</option>
                                <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("tax"=>"3")))?>"
                                <?php if($tax=="3") { echo "selected";} ?>>
                                Active +6 months</option>
                                <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("tax"=>"0")))?>"
                                <?php if($tax=="0") { echo "selected";} ?>>
                               Due Soon +3 months</option>
                               
                            </select>
                    </div>
                     </div> 
                <div class="row">
                    <div class="col">
                        <section class="card">
                            <header class="card-header">
                                <div class="card-actions">
                                    <a href="#" class="card-action card-action-toggle" data-card-toggle></a>
                                    <a href="#" class="card-action card-action-dismiss" data-card-dismiss></a>
                                </div>

                                <h2 class="card-title">Fleet Overview</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 / Sold</th>
                                       <th>Rental Status</th>
                                       <th>KTEO</th>
                                       <th>Insurance</th>
                                       <th>Road Tax</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>

                                    <?php 
                                    $contracts_vehfleet_ids = [];

$contract_query = "SELECT DISTINCT vehfleet_id FROM contracts ";
$contract_result = mysqli_query($db2, $contract_query);

while ($contract_row = mysqli_fetch_assoc($contract_result)) {
    $contracts_vehfleet_ids[] = $contract_row['vehfleet_id'];
}

			$sql = "SELECT fleet.*, jostj_vikrentcar_cars.name 
        FROM fleet 
        LEFT JOIN jostj_vikrentcar_cars ON jostj_vikrentcar_cars.id = fleet.veh_id 
        WHERE fleet.fleet_id > 0"; 

// Filter by vehicle ID
if ($fid != 'all') {
    $sql .= " AND fleet.veh_id = '$fid'";
}

// Filter by active/inactive status
if ($status != 'all') {
    $sql .= " AND fleet.active = '$status'";
}

// Filter by sold status
if ($sold != 'all') {
    $sql .= " AND fleet.fleet_sold = '$sold'";
}

// Filter by KTEO (MOT) expiration
if ($kteo != 'all') {
    if ($kteo == '1') {
        $sql .= " AND fleet.fleet_kteo > '$today3'";
    } elseif ($kteo == '0') {
        $sql .= " AND fleet.fleet_kteo < '$today3' AND fleet.fleet_kteo > '$today'";
    } elseif ($kteo == '2') {
        $sql .= " AND fleet.fleet_kteo < '$today'";
    } elseif ($kteo == '3') {
        $sql .= " AND fleet.fleet_kteo > '$today6'";
    }
}

// Filter by Insurance
if ($ins != 'all') {
    if ($ins == '1') {
        $sql .= " AND fleet.fleet_insurance_until > '$today3'";
    } elseif ($ins == '0') {
        $sql .= " AND fleet.fleet_insurance_until < '$today3' AND fleet.fleet_insurance_until > '$today'";
    } elseif ($ins == '4') {
        $sql .= " AND fleet.fleet_insurance_until > '$today'";
    } elseif ($ins == '2') {
        $sql .= " AND fleet.fleet_insurance_until < '$today'";
    } elseif ($ins == '3') {
        $sql .= " AND fleet.fleet_insurance_until > '$today6'";
    }
}

// Filter by Road Tax
if ($tax != 'all') {
    if ($tax == '1') {
        $sql .= " AND fleet.road_tax > '$today3'";
    } elseif ($tax == '0') {
        $sql .= " AND fleet.road_tax < '$today3' AND fleet.road_tax > '$today'";
    } elseif ($tax == '4') {
        $sql .= " AND fleet.road_tax > '$today'";
    } elseif ($tax == '2') {
        $sql .= " AND fleet.road_tax < '$today'";
    } elseif ($tax == '3') {
        $sql .= " AND fleet.road_tax > '$today6'";
    }
}

// Debugging
// echo "<pre>$sql</pre>";

// Execute query
$result = mysqli_query($db2, $sql) or die(mysqli_error($db2));

if ($result->num_rows > 0) {
    // output data of each row
   // echo "<p>Total Rows: " . mysqli_num_rows($result) . "</p>";
// echo "<pre>"; print_r($contracts_vehfleet_ids); echo "</pre>";
   while($row = mysqli_fetch_array($result)) {
    if ($row["active"]=="0"){$sty="red";} else {$sty="green";}
     ?>
                                        <tr>
    <td><?php echo $row["fleet_id"]; ?></td>
    <td><?php echo $row["name"]; ?></td>
    <td><?php echo $row["lic_num"]; ?></td>
    <td><?php echo $row["color"] ? $row["color"] : "Not Set"; ?></td>
      <!-- Active / Sold Status -->
    <td class="<?php echo ($row["active"] == "1") ? "green" : "red"; ?>">
        <?php echo ($row["active"] == "1") ? "Yes" : "No"; ?> /
        <?php echo ($row["fleet_sold"] == "1") ? "SOLD " . date('d/m/Y', $row['fleet_sold_date']) : "Not Sold"; ?>
    </td>

    <!-- Rental Status -->
    <td>
        <?php
        $fleet_id = $row['fleet_id'];

        if ($row['active'] == "0") {
            echo "<span class='badge badge-danger'>Inactive</span>";
        } elseif (isset($rental_status_map[$fleet_id])) {
            $status = $rental_status_map[$fleet_id]['status'];
            $return_date = $rental_status_map[$fleet_id]['return_date'] ?? null;
            
            echo "<span class='badge badge-warning'>$status</span><br>";
            if ($return_date) {
                echo "<small>Return: " . date('d/m/Y H:i', strtotime($return_date)) . "</small>";
            }
        } else {
            $latest_status = $vehicle_status_map[$fleet_id]['status'] ?? 'Available';
            $badge_color = $vehicle_status_map[$fleet_id]['badge_color'] ?? 'success';
            echo "<span class='badge badge-$badge_color'>$latest_status</span>";
        }
        ?>
    </td>

    <!-- KTEO -->
    <td><?php echo ($row['fleet_kteo'] == 0) ? "Not Set" : date('d/m/Y', $row['fleet_kteo']); ?></td>

    <!-- Insurance -->
    <td>
        <?php echo ($row['fleet_insurance_from'] == NULL) ? "Not Set" : date('d/m/Y', $row['fleet_insurance_from']); ?>
        -
        <?php echo ($row['fleet_insurance_until'] == NULL) ? "Not Set" : date('d/m/Y', $row['fleet_insurance_until']); ?>
        <br>
        (<?php echo ($row['fleet_ins_company'] == "0") ? "Not Set" : $row['fleet_ins_company']; ?>)
    </td>

    <!-- Road Tax -->
    <td>
        <?php echo ($row['road_tax'] == 0) ? "Not Set" : date('d/m/Y', $row['road_tax']); ?> -
        <?php echo ($row['lic_loc'] == 1) ? "ON" : "OFF"; ?>
    </td>

    <!-- Action Buttons -->
    <td class="actions">
    <!-- Edit Button -->
     <a href="vehicle.php?id=<?php echo $row["fleet_id"] ?? ''; ?>" class="on-default edit-row">
       <i class="fa fa-eye"></i>
    </a>
    <a href="#" class="on-default edit-row"
       onclick="openEditVehicleModal('<?php echo addslashes($row['fleet_id'] ?? ''); ?>', 
                                     '<?php echo addslashes($row['veh_id'] ?? ''); ?>', 
                                     '<?php echo addslashes($row['lic_num'] ?? ''); ?>', 
                                     '<?php echo addslashes($row['color'] ?? ''); ?>', 
                                     '<?php echo addslashes($row['notes'] ?? ''); ?>', 
                                     '<?php echo addslashes($row['active'] ?? ''); ?>')">
        <i class="fas fa-pencil-alt"></i>
    </a>

    <!-- Contract Button -->
    <a href="contracts.php?veh=<?php echo $row["fleet_id"] ?? ''; ?>&rtype=0" class="on-default edit-row">
        <i class="fas fa-file-signature"></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>
    <!-- Update Vehicle Button 
    <a href="#" class="on-default edit-row"
       onclick="openUpdateVehicleModal('<?php echo addslashes($row['fleet_id'] ?? ''); ?>', 
                                       '<?php echo addslashes($row['fleet_kteo'] ?? ''); ?>', 
                                       '<?php echo addslashes($row['fleet_insurance_from'] ?? ''); ?>', 
                                       '<?php echo addslashes($row['fleet_insurance_until'] ?? ''); ?>', 
                                       '<?php echo addslashes($row['fleet_ins_company'] ?? ''); ?>', 
                                       '<?php echo addslashes($row['fleet_sold'] ?? ''); ?>', 
                                       '<?php echo addslashes($row['fleet_sold_date'] ?? ''); ?>', 
                                       '<?php echo addslashes($row['road_tax'] ?? ''); ?>')">
        <i class="fas fa-tools"></i>
    </a>-->

    <!-- Delete Button (Disable if vehicle has contracts) -->
  <a href="#" 
   class="on-default delete-row 
   <?php echo (!empty($contracts_vehfleet_ids) && in_array($row['fleet_id'], $contracts_vehfleet_ids)) ? 'disabled' : ''; ?>" 
   onclick="<?php echo (!empty($contracts_vehfleet_ids) && in_array($row['fleet_id'], $contracts_vehfleet_ids)) ? 'return false;' : 'openDeleteVehicleModal(\'' . addslashes($row['fleet_id']) . '\')'; ?>">
    <i class="fas fa-trash-alt"></i>
</a>

</td>

</tr>
                                        <?php } ?>
                                    </tbody>
                                </table>
                            </div>

                        </section>

                    </div>
                </div>
                <?php } }?>
                <!-- end: page -->
            </section>
        </div>

        <?php include('include/aside.php');?>

    </section>


    <!-- Vendor -->
    <script src="vendor/jquery/jquery.js"></script>
    <script src="vendor/jquery-browser-mobile/jquery.browser.mobile.js"></script>
    <script src="vendor/popper/umd/popper.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.js"></script>
    <script src="vendor/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
    <script src="vendor/common/common.js"></script>
    <script src="vendor/nanoscroller/nanoscroller.js"></script>
    <script src="vendor/magnific-popup/jquery.magnific-popup.js"></script>
    <script src="vendor/jquery-placeholder/jquery.placeholder.js"></script>

    <!-- Specific Page Vendor -->
    <script src="vendor/select2/js/select2.js"></script>
    <script src="vendor/datatables/media/js/jquery.dataTables.min.js"></script>
    <script src="vendor/datatables/media/js/dataTables.bootstrap4.min.js"></script>
    <script src="vendor/datatables/extras/TableTools/Buttons-1.4.2/js/dataTables.buttons.min.js"></script>
    <script src="vendor/datatables/extras/TableTools/Buttons-1.4.2/js/buttons.bootstrap4.min.js"></script>
    <script src="vendor/datatables/extras/TableTools/Buttons-1.4.2/js/buttons.html5.min.js"></script>
    <script src="vendor/datatables/extras/TableTools/Buttons-1.4.2/js/buttons.print.min.js"></script>
    <script src="vendor/datatables/extras/TableTools/JSZip-2.5.0/jszip.min.js"></script>
    <script src="vendor/datatables/extras/TableTools/pdfmake-0.1.32/pdfmake.min.js"></script>
    <script src="vendor/datatables/extras/TableTools/pdfmake-0.1.32/vfs_fonts.js"></script>
 <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>
    <!-- Add Vehicle Modal -->
<div id="modalAddVehicle" class="modal-block modal-block-primary mfp-hide">
    <section class="card">
        <header class="card-header">
            <h2 class="card-title">Add Vehicle</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="addVehicleForm">
                <div class="modal-wrapper">
                    <div class="modal-icon">
                        <i class="fas fa-plus-circle"></i>
                    </div>
                    <div class="modal-text">
                        <!-- Vehicle -->
                        <div class="form-group">
                            <label for="veh_id">Vehicle</label>
                            <select class="form-control" id="veh_id" name="veh_id" required>
                                <option value="">Select Vehicle</option>
                                <?php
                                $vehicles_query = "SELECT id, name FROM jostj_vikrentcar_cars";
                                $vehicles_result = mysqli_query($db2, $vehicles_query);
                                while ($vehicle = mysqli_fetch_assoc($vehicles_result)) {
                                    echo "<option value='{$vehicle['id']}'>{$vehicle['name']}</option>";
                                }
                                ?>
                            </select>
                        </div>

                        <!-- License Plate -->
                        <div class="form-group">
                            <label for="lic_num">License Plate</label>
                            <input type="text" class="form-control" id="lic_num" name="lic_num" maxlength="8" required>
                        </div>

                        <!-- Color -->
                        <div class="form-group">
                            <label for="color">Color</label>
                            <input type="text" class="form-control" id="color" name="color" maxlength="15" required>
                        </div>

                        <!-- Notes -->
                        <div class="form-group">
                            <label for="notes">Notes</label>
                            <textarea class="form-control" id="notes" name="notes" rows="3"></textarea>
                        </div>

                        <!-- Active -->
                        <div class="form-group">
                            <label>Active</label><br>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="active" id="active_yes" value="1" required>
                                <label class="form-check-label" for="active_yes">Yes</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="active" id="active_no" value="0">
                                <label class="form-check-label" for="active_no">No</label>
                            </div>
                        </div>
                    </div>
                </div>
        </div>
        <footer class="card-footer">
            <div class="row">
                <div class="col-md-12 text-right">
                    <button type="button" class="btn btn-primary" id="submit-add-vehicle">Add Vehicle</button>
                </div>
            </div>
        </footer>
            </form>
    </section>
</div>
<!-- Edit Vehicle Modal -->
<div id="modalEditVehicle" class="modal-block modal-block-primary mfp-hide">
    <section class="card">
        <header class="card-header">
            <h2 class="card-title">Edit Vehicle</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="editVehicleForm">
                <input type="hidden" id="edit_fleet_id" name="fleet_id">
                <div class="modal-wrapper">
                    <div class="modal-icon">
                        <i class="fas fa-edit"></i>
                    </div>
                    <div class="modal-text">
                        <!-- Vehicle -->
                        <div class="form-group">
                            <label for="edit_veh_id">Vehicle</label>
                            <select class="form-control" id="edit_veh_id" name="veh_id" required>
                                <option value="">Select Vehicle</option>
                                <?php
                                $vehicles_query = "SELECT id, name FROM jostj_vikrentcar_cars";
                                $vehicles_result = mysqli_query($db2, $vehicles_query);
                                while ($vehicle = mysqli_fetch_assoc($vehicles_result)) {
                                    echo "<option value='{$vehicle['id']}'>{$vehicle['name']}</option>";
                                }
                                ?>
                            </select>
                        </div>

                        <!-- License Plate -->
                        <div class="form-group">
                            <label for="edit_lic_num">License Plate</label>
                            <input type="text" class="form-control" id="edit_lic_num" name="lic_num" maxlength="8" required>
                        </div>

                        <!-- Color -->
                        <div class="form-group">
                            <label for="edit_color">Color</label>
                            <input type="text" class="form-control" id="edit_color" name="color" maxlength="15" required>
                        </div>

                        <!-- Notes -->
                        <div class="form-group">
                            <label for="edit_notes">Notes</label>
                            <textarea class="form-control" id="edit_notes" name="notes" rows="3"></textarea>
                        </div>

                        <!-- Active -->
                        <div class="form-group">
                            <label>Active</label><br>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="active" id="edit_active_yes" value="1" required>
                                <label class="form-check-label" for="edit_active_yes">Yes</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="active" id="edit_active_no" value="0">
                                <label class="form-check-label" for="edit_active_no">No</label>
                            </div>
                        </div>
                    </div>
                </div>
        </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">Save Changes</button>
                </div>
            </div>
        </footer>
            </form>
    </section>
</div>
<!-- Update Vehicle Details Modal -->
<div id="modalUpdateVehicleDetails" class="modal-block modal-block-primary mfp-hide">
    <section class="card">
        <header class="card-header">
            <h2 class="card-title">Update 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="updateVehicleDetailsForm">
                <input type="hidden" id="update_fleet_id" name="fleet_id">
                <div class="modal-wrapper">
                    <div class="modal-icon">
                        <i class="fas fa-tools"></i>
                    </div>
                    <div class="modal-text">
                        <!-- KTEO -->
                  <div class="form-group">
    <label for="update_fleet_kteo">MOT (KTEO) Due Date</label>
    <input type="text" class="form-control" id="update_fleet_kteo" name="fleet_kteo" placeholder="Select a date" data-lpignore="true">
</div>

                        <!-- Insurance -->
                     <div class="form-group">
    <label for="update_fleet_insurance_from">Insurance From</label>
    <input type="text" class="form-control" id="update_fleet_insurance_from" name="fleet_insurance_from" placeholder="Select a date" data-lpignore="true">
</div>
                       <div class="form-group">
    <label for="update_fleet_insurance_until">Insurance Until</label>
    <input type="text" class="form-control" id="update_fleet_insurance_until" name="fleet_insurance_until" placeholder="Select a date" data-lpignore="true">
</div>
                        <div class="form-group">
                            <label for="update_fleet_ins_company">Insurance Company</label>
                            <input type="text" class="form-control" id="update_fleet_ins_company" name="fleet_ins_company" data-lpignore="true" >
                        </div>

                        <!-- Sold Status -->
                        <div class="form-group">
                            <label for="update_fleet_sold">Sold</label>
                            <select class="form-control" id="update_fleet_sold" name="fleet_sold">
                                <option value="1">Yes</option>
                                <option value="0">No</option>
                            </select>
                        </div>
                      <div class="form-group">
    <label for="update_fleet_sold_date">Sold Date</label>
    <input type="text" class="form-control" id="update_fleet_sold_date" name="fleet_sold_date" placeholder="Select a date" data-lpignore="true">
</div>

                        <!-- Road Tax -->
                        <div class="form-group">
    <label for="update_road_tax">Road Tax Until</label>
    <input type="text" class="form-control" id="update_road_tax" name="road_tax" placeholder="Select a date" data-lpignore="true">
</div>
                    </div>
                </div>
        </div>
        <footer class="card-footer">
            <div class="row">
                <div class="col-md-12 text-right">
                    <button type="button" class="btn btn-primary" id="submit-update-vehicle-details">Save Changes</button>
                </div>
            </div>
        </footer>
            </form>
    </section>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        // Open the Add Vehicle Modal
        document.getElementById('add-vehicle-btn').addEventListener('click', function () {
            $.magnificPopup.open({
                items: {
                    src: '#modalAddVehicle'
                },
                type: 'inline'
            });
        });

        // Submit the Add Vehicle Form
        document.getElementById('submit-add-vehicle').addEventListener('click', function () {
            const form = document.getElementById('addVehicleForm');
            const formData = new FormData(form);

            fetch('actions/add_vehicle_to_fleet.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Vehicle added successfully!');
                    location.reload(); // Reload the page to update the table
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred. Please try again.');
            });
        });
    });
</script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        // Open the Edit Vehicle Modal
        window.openEditVehicleModal = function (fleet_id, veh_id, lic_num, color, notes, active) {
            document.getElementById('edit_fleet_id').value = fleet_id;
            document.getElementById('edit_veh_id').value = veh_id;
            document.getElementById('edit_lic_num').value = lic_num;
            document.getElementById('edit_color').value = color;
            document.getElementById('edit_notes').value = notes;
            document.getElementById('edit_active_yes').checked = active === "1";
            document.getElementById('edit_active_no').checked = active === "0";

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

        // Submit the Edit Vehicle Form
        document.getElementById('submit-edit-vehicle').addEventListener('click', function () {
            const form = document.getElementById('editVehicleForm');
            const formData = new FormData(form);

            fetch('actions/edit_vehicle_in_fleet.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Vehicle updated successfully!');
                    location.reload(); // Reload the page to update the table
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred. Please try again.');
            });
        });
    });
</script>
<script>
    function openDeleteVehicleModal(fleet_id) {
        if (confirm('Are you sure you want to delete this vehicle? This action cannot be undone.')) {
            fetch('actions/delete_vehicle_from_fleet.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ fleet_id: fleet_id })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Vehicle deleted successfully!');
                    location.reload(); // Refresh the table
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred. Please try again.');
            });
        }
    }
</script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        // Open the Update Vehicle Details Modal
        window.openUpdateVehicleModal = function (fleet_id, kteo, insurance_from, insurance_until, ins_company, sold, sold_date, road_tax) {
            document.getElementById('update_fleet_id').value = fleet_id;
            document.getElementById('update_fleet_kteo').value = kteo ? new Date(kteo * 1000).toISOString().slice(0, 10) : '';
            document.getElementById('update_fleet_insurance_from').value = insurance_from ? new Date(insurance_from * 1000).toISOString().slice(0, 10) : '';
            document.getElementById('update_fleet_insurance_until').value = insurance_until ? new Date(insurance_until * 1000).toISOString().slice(0, 10) : '';
            document.getElementById('update_fleet_ins_company').value = ins_company || '';
            document.getElementById('update_fleet_sold').value = sold;
            document.getElementById('update_fleet_sold_date').value = sold_date ? new Date(sold_date * 1000).toISOString().slice(0, 10) : '';
            document.getElementById('update_road_tax').value = road_tax ? new Date(road_tax * 1000).toISOString().slice(0, 10) : '';

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

        // Submit the Update Vehicle Details Form
        document.getElementById('submit-update-vehicle-details').addEventListener('click', function () {
            const form = document.getElementById('updateVehicleDetailsForm');
            const formData = new FormData(form);

            fetch('actions/update_vehicle_details.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Vehicle details updated successfully!');
                    location.reload(); // Refresh the table
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred. Please try again.');
            });
        });
    });
</script>
<script>
 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(update_fleet_kteo, options);
    rome(update_fleet_insurance_from, options);
    rome(update_fleet_insurance_until, options);
    rome(update_fleet_sold_date, options);
    rome(update_road_tax, options);
    
    


</script>
<script>
    // Output the rental status map to the console
    console.log("Rental Status Map:", <?php echo json_encode($rental_status_map, JSON_PRETTY_PRINT); ?>);
</script>
</body>

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