<?php include('include/auth.php'); 
if (isset($_GET['vtype'])  && $_GET['vtype']!='0') {
    $vtype=$_GET['vtype'];}
    else {$vtype='0';}
    if (isset($_GET['cat'])  && $_GET['cat']!='0') {
        $cat=$_GET['cat'];}
        else {$cat='0';}
        if (isset($_GET['status'])  && $_GET['status']!='0') {
            $status=$_GET['status'];}
            else {$status='0';}

?>
<!doctype html>
<html class="fixed dark">
<?php 
	$pagerole="lists";
	include('include/head.php');
	// Source and destination directories
$source_dir = '/home/motorclub/wv-admin.motorclub.gr/motorclub-admin/carimages/';
$destination_dir = '/home/motorclub/public_html/carimages/';

// Fetch all images from the database
$image_query = "SELECT img FROM jostj_vikrentcar_cars WHERE img IS NOT NULL AND img != ''";
$image_result = mysqli_query($db2, $image_query);

if (!$image_result) {
    die("Query failed: " . mysqli_error($db2));
}

// Debug: Check if any images are found
if (mysqli_num_rows($image_result) === 0) {
    echo "No images found in the database.";
}

// Count untransferred images
$untransferred_count = 0;
while ($image_row = mysqli_fetch_assoc($image_result)) {
    $image_name = $image_row['img'];
    if (!file_exists($destination_dir . $image_name)) {
        $untransferred_count++;
    }
}
	
	?>
<style>
    .green {
        color: green !important;
    }

    .red {
        color: red !important;
    }
</style>

<body>
    <section class="body">

        <!-- start: header -->
        <header class="header">
            <div class="logo-container">
                <a href="index.php" class="logo">
                    <img src="img/logo-light.png" width="75" height="35" alt="Web Voyage" />
                </a>
                <div class="d-md-none toggle-sidebar-left" data-toggle-class="sidebar-left-opened" data-target="html"
                    data-fire-event="sidebar-left-opened">
                    <i class="fas fa-bars" aria-label="Toggle sidebar"></i>
                </div>
            </div>

            <!-- start: search & user box -->
            <div class="header-right">
                <?php include('include/search.php');?>


                <span class="separator"></span>
                <?php include('include/notifications.php');?>


                <span class="separator"></span>
                <?php include('include/userbox.php');?>

            </div>
            <!-- end: search & user box -->
        </header>
        <!-- end: header -->

        <div class="inner-wrapper">
            <!-- start: sidebar -->
            <?php include('include/nav.php');?>
            <!-- end: sidebar -->

            <section role="main" class="content-body">
                <header class="page-header">
                    <h2>Fleet Overview</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>Fleet Overview</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 {

?>
                  <h3>Filters</h3>
                <div class="row mb-0">

                    <div class="col-md-3"> <label>Vehicle Type</label>
                        <select class="form-control populate" onChange="window.location.href=this.value">
                        <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("vtype"=>0)))?>"
                                <?php if($vtype==0) { echo "selected";} ?>>
                                All</option>
                                <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("vtype"=>"1;")))?>"
                                <?php if($vtype=="1;") { echo "selected";} ?>>
                                Cars</option>
                                <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("vtype"=>"2;")))?>"
                                <?php if($vtype=="2;") { echo "selected";} ?>>
                                Bikes</option>
                               
                            </select>
                    </div>
                    <?php if($vtype!=0){?>
                    <div class="col-md-3"> <label>Category</label>
                        <select class="form-control populate" onChange="window.location.href=this.value">
                        <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("cat"=>0)))?>"
                                <?php if($cat==0) { echo "selected";} ?>>
                                All</option>
                                <?php $sqlin3 = $db->query("SELECT DISTINCT idcat FROM jos8r_vikrentcar_cars WHERE idcat LIKE '$vtype%' AND idcat!='$vtype' ") or die(mysql_error()); 
					 while($rowin3 = mysqli_fetch_array($sqlin3)) {
                         $idcat=$rowin3['idcat'];
                         $idcats=explode(";", $rowin3['idcat']);
                         $catid=$idcats[1];
                         $sql1 = $db->query("SELECT * FROM jos8r_vikrentcar_categories WHERE jos8r_vikrentcar_categories.id='$catid' ") or die(mysql_error());
                        $row1 = mysqli_fetch_array( $sql1 );
                         ?>
                                <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("cat"=>$idcat)))?>"
                                <?php if($cat==$idcat) { echo "selected";} ?>>
                                <?php echo $row1['name'];?></option>
                             <?php } ?>
                               
                            </select>
                    </div>
                  <?php }?>
                <div class="col-md-3">
                    
    <div class="col-md-12 text-right">
         <button class="btn btn-primary" onclick="openAddVehicleModal()">
            <i class="fas fa-plus"></i> Add New Vehicle
        </button>
   
</div>
                </div>
                
    <div class="col-md-3 text-right">
        <div class="d-flex align-items-center justify-content-between">
            <h5 class="m-0">Untransferred Images: <span id="untransferred-counter"><?php echo $untransferred_count; ?></span></h5>
            <?php if ($untransferred_count > 0): ?>
                <button class="btn btn-warning" id="transfer-images-button">
                    Transfer Images
                </button>
            <?php endif; ?>
        </div>
    </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>ID</th>
                                            <th>Name</th>
                                            <th>Units</th>
                                            <th>Plates</th>
                                            <th>Active</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>

                                        <?php 
                                                    $sql = "SELECT * FROM jostj_vikrentcar_cars ";
                                                    
                                                    if ($vtype!='0' && $cat==0){
                                                        $sql .=" WHERE jostj_vikrentcar_cars.idcat LIKE '$vtype%' ";
                                                        }
                                                        elseif($cat!=0){
                                                            $sql .=" WHERE jostj_vikrentcar_cars.idcat LIKE '$cat%' ";
                                                        }   
                                                        
                                        $result = mysqli_query($db2,$sql);

                                        if ($result->num_rows > 0) {
                                            // output data of each row
                                        while($row = mysqli_fetch_array($result)) {
                                                    $vid=$row["id"]; $resultf = $db2->query("SELECT COUNT(*) FROM `fleet` WHERE fleet.veh_id =$vid  ");
                                        $rowf = $resultf->fetch_row();
                                        $resultf2 = $db2->query("SELECT COUNT(*) FROM `fleet` WHERE fleet.veh_id =$vid AND fleet.active=1 ");
                                        $rowf2 = $resultf2->fetch_row();	
                                            if ($rowf[0]!==$row["units"]){$sty="red";} else {$sty="green";}
                                            if ($rowf2[0]!==$row["units"]){$sty2="red";} else {$sty2="green";}
									 ?>

                                        <tr>
                                            <td><?php echo $row["id"]; ?></td>
                                            <td class="text-center"><?php echo $row["name"]; ?></td>
                                            <td class="text-center"><?php echo $row["units"]; ?></td>

                                            <td class="text-center <?php echo $sty;?>">
                                                <?php echo $rowf[0]; ?></td>
                                                <td class="text-center <?php echo $sty2;?>" ><?php echo $rowf2[0];; ?></td>
                                            <td class="actions">
                                                <a href="editfleet-units.php?id=<?php echo $row["id"];?>"
                                                    class="on-default edit-row"><i class="fa fa-exchange-alt"></i></a><a
                                                    href="fleet-details.php?id=<?php echo $row["id"];?>"
                                                    class="on-default edit-row"><i class=" fa fa-eye"></i></a>
 <a href="#" class="on-default edit-row" 
       onclick="openEditVehicleModal(
           '<?php echo $row['id']; ?>', 
           '<?php echo addslashes($row['name']); ?>', 
           '<?php echo explode(';', $row['idcat'])[1]; ?>', 
           '<?php echo substr($row['idcat'], 0, 2); ?>', 
           '<?php echo addslashes($row['idcarat']); ?>', 
           '<?php echo file_exists("/home/motorclub/public_html/carimages/" . $row["img"]) ? "https://www.motorclub.gr/carimages/" . $row["img"] : "/carimages/" . $row["img"]; ?>', 
           '<?php echo addslashes($row['info']); ?>', 
           '<?php echo file_exists("/home/motorclub/public_html/carimages/" . $row["img"]) ? "live" : "preview"; ?>')">
        <i class="fas fa-pencil-alt"></i>
    </a>   
     <?php
    // Check if the vehicle is in any reservation
    $reservation_check_query = "SELECT COUNT(*) AS reservation_count FROM jostj_vikrentcar_orders WHERE idcar = " . intval($row['id']);
    $reservation_check_result = mysqli_query($db2, $reservation_check_query);
    $reservation_check_row = mysqli_fetch_assoc($reservation_check_result);

    if ($reservation_check_row['reservation_count'] > 0) {
        // Vehicle cannot be deleted
        echo '<a href="#" class="on-default delete-row disabled-link" title="Cannot delete reserved vehicle">
                <i class="fas fa-trash-alt text-muted"></i>
              </a>';
    } else {
        // Vehicle can be deleted
        echo '<a href="#" class="on-default delete-row" 
                onclick="confirmDeleteVehicle(' . intval($row['id']) . ', \'' . addslashes($row['name']) . '\')">
                <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>


    <!--(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>
        (function ($) {

            'use strict';

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


                var table = $table.dataTable({
                    "order": [
                        [3, "desc"]
                    ],
                    sDom: '<"text-right mb-md"T><"row"<"col-lg-6"l><"col-lg-6"f>><"table-responsive"t>p',
                    buttons: [{
                            extend: 'print',
                            text: 'Print'
                        },
                        {
                            extend: 'excel',
                            text: 'Excel'
                        },
                        {
                            extend: 'pdf',
                            text: 'PDF',
                            customize: function (doc) {
                                var colCount = new Array();
                                $('#datatable-tabletools').find('tbody tr:first-child td').each(
                                    function () {
                                        if ($(this).attr('colspan')) {
                                            for (var i = 1; i <= $(this).attr(
                                                    'colspan'); $i++) {
                                                colCount.push('*');
                                            }
                                        } else {
                                            colCount.push('*');
                                        }
                                    });
                                doc.content[1].table.widths = colCount;
                            }
                        }
                    ]
                });

                $('<div />').addClass('dt-buttons mb-2 pb-1 text-right').prependTo(
                    '#datatable-tabletools_wrapper');

                $table.DataTable().buttons().container().prependTo('#datatable-tabletools_wrapper .dt-buttons');

                $('#datatable-tabletools_wrapper').find('.btn-secondary').removeClass('btn-secondary').addClass(
                    'btn-default');
            };

            $(function () {
                datatableInit();
            });

        }).apply(this, [jQuery]);
    </script>

<!-- 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>
        </header>
        <div class="card-body">
            <form method="post" action="actions/add_vehicle_basic.php" enctype="multipart/form-data">
                <div class="modal-wrapper">
                    <div class="modal-icon">
                        <i class="fas fa-plus"></i>
                    </div>
                    <div class="modal-text">
                        <div class="row">
                            <!-- Vehicle Name -->
                            <div class="col-md-6">
                                <div class="form-group mb-3 pt-0" style="border-top: none;">
                                    <label for="vehicle_name">Vehicle Name</label>
                                    <input type="text" class="form-control" name="vehicle_name" id="vehicle_name" required>
                                </div>
                            </div>

                            <!-- Category -->
                            <div class="col-md-6">
                                <div class="form-group mb-3 pt-0" style="border-top: none;">
                                    <label for="vehicle_category">Category</label>
                                    <select class="form-control" name="vehicle_category" id="vehicle_category" required>
                                        <option value="">Select Category</option>
                                        <?php
                                        $categories_query = "SELECT id, name, type FROM jostj_vikrentcar_categories";
                                        $categories_result = mysqli_query($db2, $categories_query);
                                        while ($category = mysqli_fetch_assoc($categories_result)) {
                                            echo "<option value='{$category['id']}' data-type='{$category['type']}'>
                                                    {$category['name']} ({$category['type']})
                                                  </option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <!-- Characteristics -->
                   <div class="form-group mb-3 pt-0" style="border-top: none;">
    <label for="vehicle_characteristics">Characteristics</label>
    <div id="vehicle_characteristics" style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px;">
        <?php
        $characteristics_query = "SELECT id, name, icon FROM jostj_vikrentcar_caratteristiche ORDER BY ordering";
        $characteristics_result = mysqli_query($db2, $characteristics_query);
        while ($char = mysqli_fetch_assoc($characteristics_result)) {
            $icon_path = "https://www.motorclub.gr/res/administrator/components/com_vikrentcar/resources/" . $char['icon'];
            echo "<div class='form-check'>
                    <input type='checkbox' class='form-check-input' name='vehicle_characteristics[]' id='char_{$char['id']}' value='{$char['id']}'>
                    <label class='form-check-label' for='char_{$char['id']}'>
                        <img src='{$icon_path}' alt='{$char['name']}' width='24'> {$char['name']}
                    </label>
                  </div>";
        }
        ?>
    </div>
</div>

                        <!-- Image Upload -->
                        <div class="form-group mb-3 pt-0" style="border-top: none;">
                            <label for="vehicle_image">Vehicle Image (600x400, jpg/png/webp)</label>
                            <div class="thumbnail-container mb-3">
                                <img id="vehicle_image_thumb" src="https://via.placeholder.com/600x400?text=No+Image" 
                                     alt="Vehicle Thumbnail" 
                                     style="max-width: 100%; height: auto; border: 1px solid #ddd;">
                            </div>
                            <input type="file" class="form-control" name="vehicle_image" id="vehicle_image" accept=".jpg,.jpeg,.png,.webp">
                        </div>
<!-- Info Field -->
<div class="form-group mb-3 pt-0" style="border-top: none;">
    <label for="vehicle_info">Info</label>
    <textarea class="form-control" name="vehicle_info" id="vehicle_info" rows="4"></textarea>
</div>
                        <input type="hidden" name="idcat_prefix" id="idcat_prefix">
                    </div>
                </div>
        </div>
        <footer class="card-footer">
            <div class="row">
                <div class="col-md-12 text-right">
                    <button class="btn btn-primary" type="submit">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>
        </header>
        <div class="card-body">
            <form method="post" action="actions/edit_vehicle_basic.php" enctype="multipart/form-data">
                <div class="modal-wrapper">
                    <div class="modal-icon">
                        <i class="fas fa-edit"></i>
                    </div>
                    <div class="modal-text">
                        <div class="row">
                            <!-- Vehicle Name -->
                            <div class="col-md-6">
                                <div class="form-group mb-3 pt-0" style="border-top: none;">
                                    <label for="vehicle_name_edit">Vehicle Name</label>
                                    <input type="text" class="form-control" name="vehicle_name" id="vehicle_name_edit" required>
                                </div>
                            </div>

                            <!-- Category -->
                            <div class="col-md-6">
                                <div class="form-group mb-3 pt-0" style="border-top: none;">
                                    <label for="vehicle_category_edit">Category</label>
                                    <select class="form-control" name="vehicle_category" id="vehicle_category_edit" required>
                                        <option value="">Select Category</option>
                                        <?php
                                        $categories_query = "SELECT id, name, type FROM jostj_vikrentcar_categories";
                                        $categories_result = mysqli_query($db2, $categories_query);
                                        while ($category = mysqli_fetch_assoc($categories_result)) {
                                            echo "<option value='{$category['id']}' data-type='{$category['type']}'>
                                                    {$category['name']} ({$category['type']})
                                                  </option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <!-- Characteristics -->
                        <div class="form-group mb-3 pt-0" style="border-top: none;">
                            <label for="vehicle_characteristics_edit">Characteristics</label>
                            <div id="vehicle_characteristics_edit" style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px;">
                                <?php
                                $characteristics_query = "SELECT id, name, icon FROM jostj_vikrentcar_caratteristiche ORDER BY ordering";
                                $characteristics_result = mysqli_query($db2, $characteristics_query);
                                while ($char = mysqli_fetch_assoc($characteristics_result)) {
                                    $icon_path = "https://www.motorclub.gr/res/administrator/components/com_vikrentcar/resources/" . $char['icon'];
                                    echo "<div class='form-check'>
                                            <input type='checkbox' class='form-check-input' name='vehicle_characteristics[]' id='edit_char_{$char['id']}' value='{$char['id']}'>
                                            <label class='form-check-label' for='edit_char_{$char['id']}'>
                                                <img src='{$icon_path}' alt='{$char['name']}' width='24'> {$char['name']}
                                            </label>
                                          </div>";
                                }
                                ?>
                            </div>
                        </div>

                        <!-- Image Upload -->
                        <div class="form-group mb-3 pt-0" style="border-top: none;">
    <label for="vehicle_image_edit">Vehicle Image (600x400, jpg/png/webp)</label>
    <div class="thumbnail-container mb-3">
        <img id="vehicle_image_thumb_edit" src="https://via.placeholder.com/600x400?text=No+Image" 
             alt="Vehicle Thumbnail" 
             style="max-width: 100%; height: auto; border: 1px solid #ddd;">
        <div id="vehicle_image_status" class="mt-2"></div> <!-- Status Label -->
    </div>
    <input type="file" class="form-control" name="vehicle_image" id="vehicle_image_edit" accept=".jpg,.jpeg,.png,.webp">
</div>
   
<!-- Info Field -->
<div class="form-group mb-3 pt-0" style="border-top: none;">
    <label for="vehicle_info_edit">Info</label>
    <textarea class="form-control" name="vehicle_info" id="vehicle_info_edit" rows="4"></textarea>
</div>
                        <input type="hidden" name="vehicle_id" id="vehicle_id_edit">
                        <input type="hidden" name="idcat_prefix" id="idcat_prefix_edit">
                    </div>
                </div>
        </div>
        <footer class="card-footer">
            <div class="row">
                <div class="col-md-12 text-right">
                    <button class="btn btn-primary" type="submit">Save Changes</button>
                </div>
            </div>
        </footer>
        </form>
    </section>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        // Open Add Vehicle Modal
        function openAddVehicleModal() {
            // Clear all fields
            document.getElementById('vehicle_name').value = '';
            document.getElementById('vehicle_category').value = '';
            document.getElementById('idcat_prefix').value = '';
             document.getElementById('vehicle_info').value = ''; // Reset info field
            document.querySelectorAll('#vehicle_characteristics input[type="checkbox"]').forEach(checkbox => {
                checkbox.checked = false;
            });

            // Reset thumbnail to placeholder
            document.getElementById('vehicle_image_thumb').src = 'https://via.placeholder.com/600x400?text=No+Image';

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

        // Update idcat prefix dynamically when selecting a category
        const vehicleCategory = document.getElementById('vehicle_category');
        if (vehicleCategory) {
            vehicleCategory.addEventListener('change', function () {
                const selectedOption = this.options[this.selectedIndex];
                const type = selectedOption.getAttribute('data-type');
                document.getElementById('idcat_prefix').value = type === 'CAR' ? '1;' : type === 'BIKE' ? '2;' : '';
            });
        }

        // Update thumbnail when a new image is selected
        const vehicleImage = document.getElementById('vehicle_image');
        if (vehicleImage) {
            vehicleImage.addEventListener('change', function (event) {
                const file = event.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function (e) {
                        document.getElementById('vehicle_image_thumb').src = e.target.result;
                    };
                    reader.readAsDataURL(file);
                }
            });
        }

        // Expose the function globally
        window.openAddVehicleModal = openAddVehicleModal;
    });
</script>
<script>
function openEditVehicleModal(vehicleId, vehicleName, categoryId, idcatPrefix, currentCharacteristics, imgUrl, vehicleInfo, imageStatus) {
    // Populate fields
    document.getElementById('vehicle_id_edit').value = vehicleId;
    document.getElementById('vehicle_name_edit').value = vehicleName;
    document.getElementById('vehicle_category_edit').value = categoryId;
    document.getElementById('idcat_prefix_edit').value = idcatPrefix;
    document.getElementById('vehicle_info_edit').value = vehicleInfo;

    // Clear all checkboxes
    document.querySelectorAll('#vehicle_characteristics_edit input[type="checkbox"]').forEach(checkbox => {
        checkbox.checked = false;
    });

    // Pre-select current characteristics
    if (currentCharacteristics) {
        const selectedCharacteristics = currentCharacteristics.split(';');
        selectedCharacteristics.forEach(charId => {
            const checkbox = document.getElementById(`edit_char_${charId}`);
            if (checkbox) checkbox.checked = true;
        });
    }

    // Set thumbnail image based on status
    const thumb = document.getElementById('vehicle_image_thumb_edit');
    thumb.src = imgUrl || 'https://via.placeholder.com/600x400?text=No+Image';

    // Update image status label
    const statusLabel = document.getElementById('vehicle_image_status');
    if (imageStatus === 'live') {
        statusLabel.innerHTML = '<span class="badge badge-success">Live</span>';
    } else {
        statusLabel.innerHTML = '<span class="badge badge-warning">Preview</span>';
    }

    // Open the modal
    $.magnificPopup.open({
        items: {
            src: '#modalEditVehicle'
        },
        type: 'inline'
    });
}
function confirmDeleteVehicle(vehicleId, vehicleName) {
    if (confirm(`Are you sure you want to delete the vehicle "${vehicleName}"? This action cannot be undone.`)) {
        // Redirect to delete action
        window.location.href = `actions/delete_vehicle.php?id=${vehicleId}`;
    }
}

console.log({
    vehicleId, 
    vehicleName, 
    categoryId, 
    idcatPrefix, 
    currentCharacteristics, 
    imgUrl, 
    vehicleInfo
});
</script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const transferButton = document.getElementById('transfer-images-button');
        if (transferButton) {
            transferButton.addEventListener('click', function () {
                if (confirm('Are you sure you want to transfer untransferred images?')) {
                    // Disable the button to prevent multiple clicks
                    transferButton.disabled = true;
                    transferButton.innerHTML = 'Transferring...';

                    // Make an AJAX call to the transfer script
                    fetch('scripts/transfer_images.php')
                        .then(response => response.text())
                        .then(data => {
                            alert('Image transfer complete!');
                            location.reload(); // Reload the page to update the counter
                        })
                        .catch(error => {
                            console.error('Error transferring images:', error);
                            alert('Error transferring images. Please check the logs.');
                            transferButton.disabled = false;
                            transferButton.innerHTML = 'Transfer Images';
                        });
                }
            });
        }
    });
</script>
</body>

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