<?php
// Ensure configuration is loaded
if (file_exists('../../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

// Fetch vehicle details using prepared statements
$stmt = $GLOBALS['con']->prepare("SELECT * FROM `vehicles` WHERE `id` = ?");
$stmt->bind_param("i", $_REQUEST['id']);
$stmt->execute();
$iv = $stmt->get_result();
$d = mysqli_fetch_array($iv);
$stmt->close();
?>

<div class="card" id="editBox">
    <div class="card-header">
        Edit Vehicle
        <a class="float-end btn btn-secondary btn-sm" href="javascript:void(0)" onclick="cancelNew()">
            <i class="fad fa-times"></i> cancel
        </a>
    </div>
    <div class="card-body">
        <form name="vehicleForm" id="vehicleForm" class="form-horizontal">

            <div class="row">
                <!-- Left Column -->
                <div class="col-md-6">
                    <!-- Registration Plate -->
                    <div class="form-group row mb-4">
                        <label for="reg" class="col-md-3">Registration Plate</label>
                        <div class="col-md-9">
                            <input type="text" class="form-control" name="reg" id="reg" style="text-transform:uppercase" value="<?= htmlspecialchars($d['reg']) ?>" />
                        </div>
                    </div>

                    <!-- Description -->
                    <div class="form-group row mb-4">
                        <label for="desc" class="col-md-3">Description</label>
                        <div class="col-md-9">
                            <input type="text" class="form-control" name="desc" placeholder="E.g. Blue Ford van" value="<?= htmlspecialchars($d['desc']) ?>" />
                        </div>
                    </div>

                    <!-- Engine Size -->
                    <div class="form-group row mb-4">
                        <label for="engine" class="col-md-3">Engine Size</label>
                        <div class="col-md-9">
                            <select name="engine" class="form-select" id="engine">
                                <option value="">Select</option>
                                <option value="petrol_u1400" <?= $d['engine'] == "petrol_u1400" ? 'SELECTED' : '' ?>>Petrol/Hybrid 1400cc or less</option>
                                <option value="petrol_u2000" <?= $d['engine'] == "petrol_u2000" ? 'SELECTED' : '' ?>>Petrol/Hybrid 1401cc to 2000cc</option>
                                <option value="petrol_02000" <?= $d['engine'] == "petrol_02000" ? 'SELECTED' : '' ?>>Petrol/Hybrid Over 2000cc</option>
                                <option value="diesel_u1600" <?= $d['engine'] == "diesel_u1600" ? 'SELECTED' : '' ?>>Diesel Under 1600cc</option>
                                <option value="diesel_u2000" <?= $d['engine'] == "diesel_u2000" ? 'SELECTED' : '' ?>>Diesel 1600cc to 2000cc</option>
                                <option value="diesel_o2000" <?= $d['engine'] == "diesel_o2000" ? 'SELECTED' : '' ?>>Diesel Over 2000cc</option>
                                <option value="lpg_u1400" <?= $d['engine'] == "lpg_u1400" ? 'SELECTED' : '' ?>>LPG 1400cc or less</option>
                                <option value="lpg_u2000" <?= $d['engine'] == "lpg_u2000" ? 'SELECTED' : '' ?>>LPG 1401cc to 2000cc</option>
                                <option value="lpg_02000" <?= $d['engine'] == "lpg_02000" ? 'SELECTED' : '' ?>>LPG Over 2000cc</option>
                                <option value="electric" <?= $d['engine'] == "electric" ? 'SELECTED' : '' ?>>Fully Electric</option>
                            </select>
                        </div>
                    </div>

                    <!-- Initial Mileage -->
                    <div class="form-group row mb-4">
                        <label for="miles" class="col-md-3">Initial Mileage</label>
                        <div class="col-md-9">
                            <input type="number" class="form-control" name="miles" value="<?= htmlspecialchars($d['mileage']) ?>" />
                        </div>
                    </div>
                </div>

                <!-- Right Column -->
                <div class="col-md-6">
                    <!-- Fuel Type -->
                    <div class="form-group row mb-4">
                        <label for="fuel" class="col-md-3">Fuel Type</label>
                        <div class="col-md-9">
                            <select name="fuel" class="form-select" id="fuel">
                                <option value="">Select</option>
                                <option value="Petrol/Hybrid" <?= $d['fuel'] == "Petrol/Hybrid" ? 'SELECTED' : '' ?>>Petrol/Hybrid</option>
                                <option value="Diesel" <?= $d['fuel'] == "Diesel" ? 'SELECTED' : '' ?>>Diesel</option>
                                <option value="LPG" <?= $d['fuel'] == "LPG" ? 'SELECTED' : '' ?>>LPG</option>
                                <option value="Electric" <?= $d['fuel'] == "Electric" ? 'SELECTED' : '' ?>>Electric</option>
                            </select>
                        </div>
                    </div>

                    <!-- Tax Due Date -->
                    <div class="form-group row mb-4">
                        <label for="tDate" class="col-md-3">Tax Due Date</label>
                        <div class="col-md-9 datepicker" data-mdb-datepicker-init data-mdb-input-init data-mdb-confirmDateOnSelect>
                            <input type="text" class="form-control" data-mdb-toggle="datepicker" id="tDate" name="tdate" value="<?= !empty($d['tax']) ? date('d-m-Y', $d['tax']) : '' ?>" />
                        </div>
                    </div>

                    <!-- Insurance Due Date -->
                    <div class="form-group row mb-4">
                        <label for="iDate" class="col-md-3">Insurance Due Date</label>
                        <div class="col-md-9 datepicker" data-mdb-datepicker-init data-mdb-input-init data-mdb-confirmDateOnSelect>
                            <input type="text" class="form-control" data-mdb-toggle="datepicker" id="iDate" name="idate" value="<?= !empty($d['insurance']) ? date('d-m-Y', $d['insurance']) : '' ?>" />
                        </div>
                    </div>

                    <!-- MOT Due Date -->
                    <div class="form-group row mb-4">
                        <label for="mot" class="col-md-3">MOT Due Date</label>
                        <div class="col-md-9 datepicker" data-mdb-datepicker-init data-mdb-input-init data-mdb-confirmDateOnSelect>
                            <input type="text" class="form-control" data-mdb-toggle="datepicker" id="mot" name="mot" value="<?= !empty($d['mot']) ? date('d-m-Y', $d['mot']) : '' ?>" />
                        </div>
                    </div>
                </div>
            </div>

            <input type="hidden" name="id" value="<?= htmlspecialchars($_REQUEST['id']) ?>">
            <input type="hidden" name="FUNCTION" value="updateVehicle">
            <input type="hidden" name="tenant" value="<?=TENANT_URL?>">
            <div class="text-center">
                <button type="submit" id="btnConfirm" class="btn btn-info">Update Vehicle</button>
            </div>
        </form>


    </div>
</div>

<script>
// Initialize datepickers
document.querySelectorAll('.datepicker').forEach((elem) => {
    new mdb.Datepicker(elem, {
        format: 'dd-mm-yyyy',
        disableFuture: false,
        toggleButton: false,
        confirmDateOnSelect: true
    });
});

// Combined form validation and submission
document.getElementById('btnConfirm').addEventListener('click', function(event) {
    event.preventDefault(); // Prevent default behavior of button

    // Validate the required fields
    const reg = document.getElementById('reg').value;
    const engine = document.getElementById('engine').value;
    const fuel = document.getElementById('fuel').value;

    if (reg === "" || engine === "" || fuel === "") {
        // Show error message if fields are not filled
        showResponse('danger', 'YOU MUST ENTER A VALID VEHICLE REGISTRATION, ENGINE SIZE, AND FUEL TYPE');
    } else {
        // If validation passes, handle form submission with AJAX
        const form = document.getElementById('vehicleForm');
        const formData = new FormData(form); // Create FormData object

        // Submit form data via fetch
        fetch(ROOT_URL + '/includes/vehicles/vehicle_functions.php', {
                method: 'POST',
                body: new URLSearchParams(formData)
            })
            .then(response => response.text())
            .then(result => {
                // Debugging: Log the actual result to see what it looks like
                console.log("Server response:", result);

                // Trim the response to remove any extra spaces or newlines
                const trimmedResult = result.trim();

                if (trimmedResult == "success") {
                    // If success, show success message and update vehicle list
                    showResponse('success', 'Your vehicle has been updated successfully');


                    getVehicles();
                } else {
                    // If error, handle accordingly
                    showResponse('danger', 'There was an issue updating the vehicle');
                }
            })
            .catch(error => {
                console.error('Error submitting form:', error);
                showResponse('danger', 'An error occurred while updating the vehicle');
            });
    }
});
</script>