<?php include '../header.php'; ?> 
<?php include '../sidemenu.php'; ?> 

<div class="page-header d-print-none">
    <div class="container-xl">
        <div class="row g-2 align-items-center">
            <div class="col d-flex justify-content-between">
                <h2 class="page-title">Vehicle</h2>
                <button class="btn btn-outline-success" id="btnCreateNew">Add Vehicle</button>
            </div>
        </div>
    </div>
</div>

<div class="container" id="alertContainer1"></div>
<div class="page-body">
    <div class="container-xl">
        <div class="row row-cards">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="myTable" class="table card-table table-vcenter text-nowrap datatable" >
                                <thead>
                                    <tr>
                                        <!-- <th class="w-1"><input class="form-check-input m-0 align-middle" type="checkbox" aria-label="Select all reservations"></th> -->
                                        <th class="w-1">License Plate</th>
                                        <th>Vehicle Category</th>
                                        <th>Vehicle Details</th>
                                        <th>Transmission</th>
                                        <th class="w-1">Seats</th>
                                        <th>Fuel</th>
                                        <th class="w-1">Odometer</th>
                                        <th>Note</th>
                                        <th class="w-1"></th>
                                    </tr>
                                </thead>
                                <tbody>

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

<div class="modal fade" id="createEntryModal" tabindex="-1" aria-labelledby="createEntryModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createEntryModalLabel">Vehicle Entry</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="container" id="alertContainer2"></div>
            <div class="modal-body">
                <form id="createEntryForm">
                    <input type="hidden" class="form-control" id="vehicleId">
                    <div class="row g-3">
                        <div class="col-md-6">
                        <label class="form-label">License Plate</label>
                        <input type="text" id="licensePlate" class="form-control" placeholder="Enter license plate">
                        </div>
                        <div class="col-md-6">
                        <label class="form-label">Vehicle Category</label>
                        <input type="text" id="vehicleCategory" class="form-control" placeholder="Enter vehicle category">
                        </div>
                        <div class="col-md-6">
                        <label class="form-label">Transmission</label>
                        <input type="text" id="transmission" class="form-control" placeholder="Enter transmission">
                        </div>
                        <div class="col-md-6">
                        <label class="form-label">Seats</label>
                        <input type="number" id="seats" class="form-control" placeholder="Enter seat count">
                        </div>
                        <div class="col-12">
                        <label class="form-label">Vehicle Details</label>
                        <input type="text" id="vehicleDetails" class="form-control" placeholder="e.g. Toyota Corolla 2022 White">
                        </div>
                        <div class="col-md-6">
                        <label class="form-label">Fuel Type</label>
                        <input type="text" id="fuelType" class="form-control" placeholder="Enter fuel type">
                        </div>
                        <div class="col-md-6">
                        <label class="form-label">Odometer (km)</label>
                        <input type="number" id="odometerKm" class="form-control" placeholder="Enter current odometer">
                        </div>
                        <div class="col-12">
                        <label class="form-label">Vehicle Note</label>
                        <textarea id="remark" class="form-control" placeholder="Enter vehicle note" data-bs-toggle="autosize"></textarea>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" id="btnSave" class="btn btn-outline-success" onclick="validateAndSave()">Create</button>
            </div>
        </div>
    </div>
</div>
 
<?php include '../footer.php'; ?>

<script>
$(function() {

    // $('#createEntryModal').modal({
    //     backdrop: 'static', // Prevents closing the modal by clicking outside it
    //     keyboard: false // Prevents closing the modal with the Escape key
    // });

    $("input[type='number']").on("input", function() {
        this.value = this.value.replace(/[^0-9]/g, ''); // Remove non-numeric characters
    });

    getAll();
});

function buildVehicleRemark() {
    return "CARRTL_VEH|" + JSON.stringify({
        details: $("#vehicleDetails").val().trim(),
        fuel_type: $("#fuelType").val().trim(),
        odometer: $("#odometerKm").val().trim(),
        note: $("#remark").val().trim()
    });
}

function resetVehicleMetaFields() {
    $("#vehicleDetails").val("");
    $("#fuelType").val("");
    $("#odometerKm").val("");
}

function getAll() {
    $('#myTable').DataTable().destroy();
    let table = $('#myTable').DataTable({
        ajax: {
            url: APP_URL + "api/vehicle/get_all_rows_datatable.php",
            method: "GET",
            dataType: "json",
            dataSrc: 'records' 
        },
        columns: [
            { data: 1 }, 
            { data: 2 },
            { data: 5 }, 
            { data: 3 },
            { data: 4 }, 
            { data: 6 },
            { data: 7 },
            { data: 8 },

            { 
                data: null, 
                render: function(data, type, row) {
                    return `
                        <div class="btn-group">
                            <button type="button" class="btn btn-outline-primary btn-sm dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                                Actions
                            </button>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item" href="#" onclick="edit('${row[0]}')">Edit</a></li>
                                <li><a class="dropdown-item" href="#" onclick="del('${row[0]}', this)">Delete</a></li>
                            </ul>
                        </div>
                    `;
                }
            }

        ],
        paging: true,
        language: {
            emptyTable: "No records found",
            info: "Showing _START_ to _END_ of _TOTAL_ entries",
            lengthMenu: "Show _MENU_ entries",
            search: "Search:",
            zeroRecords: "No records found"
        }
    });
}

$("#btnCreateNew").click(function() {
    // $("#createEntryForm").trigger("reset");
    $("#vehicleId").val("");
    $("#licensePlate").prop("disabled", false);
    $("#createEntryForm").trigger("reset");
    resetVehicleMetaFields();
    $('#createEntryModal').modal('show');
    $("#btnSave").text("Create").removeClass("btn-outline-primary").addClass("btn-outline-success");
});


function validateAndSave() {

    let isValid = true;

    $("#licensePlate").removeClass("is-invalid");
    $("#vehicleCategory").removeClass("is-invalid");
    $("#transmission").removeClass("is-invalid");
    $("#seats").removeClass("is-invalid");

    if ($("#licensePlate").val() === null || $("#licensePlate").val().trim() === "") {
        $("#licensePlate").addClass("is-invalid");
        isValid = false; 
    }

    if ($("#vehicleCategory").val() === null || $("#vehicleCategory").val().trim() === "") {
        $("#vehicleCategory").addClass("is-invalid");
        isValid = false;
    }

    if ($("#transmission").val() === null || $("#transmission").val().trim() === "") {
        $("#transmission").addClass("is-invalid");
        isValid = false; 
    }

    if ($("#seats").val() === null || $("#seats").val().trim() === "") {
        $("#seats").addClass("is-invalid");
        isValid = false; 
    }

    if (isValid) {

        // $(this).prop("disabled", true).text("Loading...");

        var vehicleEntry = {
            "id": $("#vehicleId").val(),
            "license_plate": $("#licensePlate").val(),
            "vehicle_category": $("#vehicleCategory").val(),
            "transmission": $("#transmission").val(),
            "seats": $("#seats").val(),
            "remark": buildVehicleRemark(),
        };

        $.ajax({
            type: "POST",
            url: APP_URL + "api/vehicle/create_update.php",
            data: JSON.stringify(vehicleEntry),
            success: function(data) {
                if (data.message === "created" || data.message === "updated") {
                    // $("#createEntryForm").trigger("reset");
                    $('#createEntryModal').modal('hide');
                    $("#licensePlate").val("");
                    showAlert("Vehicle " + (data.message === "created" ? "created" : "updated") + " successfully!", "success");
                    getAll();

                } else if (data.message === "duplicate") {
                    showAlert("Vehicle already exists!", "warning");
                } else {
                    showAlert("An error occurred on the server!", "error");
                }
            },
            error: function() {
                showAlert("An error occurred while saving!", "error");
            },
            complete: function() {
                // $("#btnSave").prop("disabled", false).text(button.innerText);
            }
        });
    }
}



function edit(id) {
    $("#createEntryForm").trigger("reset");
    $("#btnSave").text("Update").removeClass("btn-outline-success").addClass("btn-outline-primary");
    $('#createEntryModal').modal('show');
    $("#vehicleId").val(id);
    $.ajax({
        url: APP_URL + "api/vehicle/get_one_row.php",
        type: "POST",
        data: JSON.stringify({ id: id })
    }).done(function(data) {
        if (data) {
            $("#licensePlate").prop("disabled", true);
            $("#licensePlate").val(data.license_plate);
            $("#vehicleCategory").val(data.vehicle_category); 
            $("#transmission").val(data.transmission);
            $("#seats").val(data.seats);
            $("#remark").val(data.remark);
            if (data.vehicle_meta) {
                $("#vehicleDetails").val(data.vehicle_meta.details || [
                    data.vehicle_meta.brand,
                    data.vehicle_meta.model,
                    data.vehicle_meta.year,
                    data.vehicle_meta.color
                ].filter(Boolean).join(" "));
                $("#fuelType").val(data.vehicle_meta.fuel_type || "");
                $("#odometerKm").val(data.vehicle_meta.odometer || "");
            } else {
                resetVehicleMetaFields();
            }
        } else {
            console.log(data);
        }
    });
}

function del(id, obj) {
    $('#modal-delete').modal('show');
    $('#confirm-delete').off('click').on('click', function() {
        // $(this).prop("disabled", true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Deleting...');

        $.ajax({
            type: "POST",
            url: APP_URL + "api/vehicle/delete.php",
            data: JSON.stringify({ id: id }),
            success: function(data) {
                if (data.message === "deleted") {
                    getAll();
                    // $(obj).closest("tr").remove();
                    showAlert("Vehicle deleted successfully!", "success");
                } else {
                    showAlert("An error occurred on the server!", "error");
                }
            },
            error: function() {
                showAlert("An error occurred while saving!", "error");
            },
            complete: function() {
                $('#modal-delete').modal('hide');
                // $('#confirm-delete').prop("disabled", false).text("Delete");
            }
        });
    });
}


function showAlert(message, type) {
    Swal.fire({
        title: type === 'success' ? 'Success!' : 'Oops!',
        text: message,
        icon: type,
        timer: 1000,
        timerProgressBar: true, 
        willClose: () => {
            console.log('Alert closed');
        }
    });
}
</script>
