<?php
$priceRanges = [
    [
        'text' => 'All Prices',
        'value' => [10000, 80000],
    ],
    [
        'text' => 'Under $10,000',
        'value' => [0, 10000],
    ],
    [
        'text' => '$10,000 - $19,999',
        'value' => [10000, 19000],
    ],
    [
        'text' => '$20,000 - $29,999',
        'value' => [20000, 29000],
    ],
    [
        'text' => '$30,000 - $39,999',
        'value' => [30000, 39000],
    ],
    [
        'text' => '$40,000 - $49,999',
        'value' => [40000, 49000],
    ],
    [
        'text' => '$50,000 - $59,999',
        'value' => [50000, 59000],
    ],
    [
        'text' => '$60,000 - $69,999',
        'value' => [60000, 69000],
    ],
    [
        'text' => '$70,000 - $79,999',
        'value' => [70000, 80000],
    ],
];


$startYear = 2012;
$endYear = (int)date('Y');
$years = range($startYear, $endYear);
array_unshift($years, 'All Years');
// Transform the array into an array of objects
$years = array_map(function ($year) use ($startYear, $endYear) {
    if ($year == 'All Years') {
        return ['text' => $year, 'value' => [$startYear, $endYear]];
    } else {
        return ['text' => $year, 'value' => [$year, $year]];
    }
}, $years);
$carMakes = [
    "All Makes", "Acura", "Audi", "BMW", "Ford", "GMC",
    "Honda", "Hyundai", "Jaguar", "Jeep", "Kia",
    "Lexus", "Mazda", "Mercedes-Benz", "Tesla", "Toyota", "Volkswagen"
];

?>

<form id="vehicle-search-form" name="vehicle-search-form" method="get" action="<?php echo esc_url(home_url('/index.php/autocart-results')); ?>" class="w-full bg-white px-6 lg:px-8 py-10 rounded-md">
    <h2 class="text-xl lg:text-3xl font-bold mb-2 uppercase">Find your vehicle</h2>
    <div class="sm:grid sm:grid-cols-2 gap-4">


        <div>
            <label class="block mb-2 text-sm font-medium text-gray-700" for="vehicle_search_make">Make</label>
            <select class="w-full px-3 py-2 border rounded-md text-gray-700 focus:outline-none focus:border-red-500" id="vehicle_search_make" name="vehicle_search_make">
                <?php foreach ($carMakes as $index => $make) : ?>
                    <option value="<?= strtolower(str_replace(' ', '', $make)); ?>" <?= $index === 0 ? 'selected' : ''; ?>>
                        <?= $make; ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div>
            <label class="block mb-2 text-sm font-medium text-gray-700" for="vehicle_search_model">Model</label>
            <select class="w-full px-3 py-2 border rounded-md text-gray-700 focus:outline-none focus:border-red-500" id="vehicle_search_model" name="vehicle_search_model">
                <option value="" disabled="" selected="">All Models</option>
                <!-- <option value="Camry">Camry</option>
                <option value="Accord">Accord</option>
                <option value="F-150">F-150</option>
                <option value="Silverado">Silverado</option>
                <option value="Altima">Altima</option> -->
            </select>
        </div>

        <div>
            <label class="block mb-2 text-sm font-medium text-gray-700" for="vehicle_search_year">Year</label>
            <select class="w-full px-3 py-2 border rounded-md text-gray-700 focus:outline-none focus:border-red-500" id="vehicle_search_year" name="vehicle_search_year">
                <?php foreach ($years as $index => $year) : ?>
                    <option value="<?= htmlspecialchars(json_encode($year['value'])); ?>" <?= $index === 0 ? 'selected' : ''; ?>>
                        <?= $year['text']; ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div>
            <label class="block mb-2 text-sm font-medium text-gray-700" for="vehicle_search_body_type">Body Type</label>
            <select class="w-full px-3 py-2 border rounded-md text-gray-700 focus:outline-none focus:border-red-500" id="vehicle_search_body_type" name="vehicle_search_body_type">
                <option value="" disabled="" selected="">All Body Types</option>
                <!-- <option value="Sedan">Sedan</option>
                <option value="SUV">SUV</option>
                <option value="Truck">Truck</option>
                <option value="Hatchback">Hatchback</option>
                <option value="Coupe">Coupe</option> -->
            </select>
        </div>

        <div>
            <label class="block mb-2 text-sm font-medium text-gray-700" for="vehicle_search_transmission">Transmission</label>
            <select class="w-full px-3 py-2 border rounded-md text-gray-700 focus:outline-none focus:border-red-500" id="vehicle_search_transmission" name="vehicle_search_transmission">
                <option value="" disabled="" selected="">All Transmissions</option>
                <!-- <option value="Automatic">Automatic</option>
                <option value="Manual">Manual</option>
                <option value="CVT">CVT</option> -->
            </select>
        </div>

        <div>
            <label class="block mb-2 text-sm font-medium text-gray-700" for="vehicle_search_trim">Trim</label>
            <select class="w-full px-3 py-2 border rounded-md text-gray-700 focus:outline-none focus:border-red-500" id="vehicle_search_trim" name="vehicle_search_trim">
                <option value="" disabled="" selected="">All Trims</option>
                <!-- <option value="LE">LE</option>
                <option value="EX">EX</option>
                <option value="XLT">XLT</option>
                <option value="LT">LT</option>
                <option value="SV">SV</option> -->
            </select>
        </div>

        <div class="flex flex-col col-span-2">
            <div>
                <label class="block mb-2 text-sm font-medium text-gray-700" for="autocart-kilometres-range-field">Kilometers</label>
                <!-- <input class="w-full px-3 py-2 border rounded-md text-gray-700 focus:outline-none focus:border-red-500" type="hidden" id="autocart-kilometres-range-field" name="autocart-kilometres-range-field" min="16000" max="200000"> -->
            </div>
            <div class="range-container">
                <div class="mdc-slider mdc-slider--range" id="autocart-kilometres-range-field">
                    <input class="mdc-slider__input" type="range" min="19000" max="222000" value="19000" name="rangeStart" aria-label="Continuous range slider demo">
                    <input class="mdc-slider__input" type="range" min="19000" max="222000" value="222000" name="rangeEnd" aria-label="Continuous range slider demo">
                    <div class="mdc-slider__track">
                        <div class="mdc-slider__track--inactive"></div>
                        <div class="mdc-slider__track--active">
                            <div class="mdc-slider__track--active_fill"></div>
                        </div>
                    </div>
                    <div class="mdc-slider__thumb">
                        <div class="mdc-slider__thumb-knob"></div>
                    </div>
                    <div class="mdc-slider__thumb">
                        <div class="mdc-slider__thumb-knob"></div>
                    </div>
                </div>
                <label class="block mb-2 text-sm font-medium text-white-700 range-label" for="autocart-kilometres-range-field">19000 to 222000</label>

            </div>
            <div>
                <label class="block mb-2 text-sm font-medium text-gray-700" for="autocart-price-range-field">Price</label>
                <!-- <input class="w-full px-3 py-2 border rounded-md text-gray-700 focus:outline-none focus:border-red-500" type="hidden" id="vehicle_search_price" name="vehicle_search_price" min="5000" max="70000"> -->
            </div>
            <div class="range-container">

                <?php
                $minPrice = $priceRanges[0]['value'][0];
                $maxPrice = $priceRanges[count($priceRanges) - 1]['value'][1]; ?>
                <div class="mdc-slider mdc-slider--range" id="autocart-price-range-field">
                    <input class="mdc-slider__input" type="range" min="<?php echo $minPrice; ?>" max="<?php echo $maxPrice; ?>" value="<?php echo isset($minPrice) ? $minPrice : 10000; ?>" name="rangeStart" aria-label="Continuous range slider demo">
                    <input class="mdc-slider__input" type="range" min="<?php echo $minPrice; ?>" max="<?php echo $maxPrice; ?>" value="<?php echo isset($maxPrice) ? $maxPrice : 80000; ?>" name="rangeEnd" aria-label="Continuous range slider demo">
                    <div class="mdc-slider__track">
                        <div class="mdc-slider__track--inactive"></div>
                        <div class="mdc-slider__track--active">
                            <div class="mdc-slider__track--active_fill"></div>
                        </div>
                    </div>
                    <div class="mdc-slider__thumb">
                        <div class="mdc-slider__thumb-knob"></div>
                    </div>
                    <div class="mdc-slider__thumb">
                        <div class="mdc-slider__thumb-knob"></div>
                    </div>
                </div>
                <label class="block mb-2 text-sm font-medium text-white-700 range-label" for="autocart-price-range-field"><?php echo '$' . number_format($minPrice) . ' to $' . number_format($maxPrice) ?></label>
            </div>
        </div>
        <input type="hidden" name="maxPrice" id="autocart-max-price-field-input" />
        <input type="hidden" name="minPrice" id="autocart-min-price-field-input" />
        <input type="hidden" name="maxYear" id="autocart-max-year-field-input" />
        <input type="hidden" name="minYear" id="autocart-min-year-field-input" />
        <input type="hidden" name="make" id="autocart-make-field-input" />

        <?php wp_nonce_field('autocart_nonce', 'autocart_nonce'); ?>

        <div class="lg:col-span-2">
            <button type="submit" aria-label="Find Your Vehicle Search" class="w-full bg-red-500 hover:bg-red-800 transition-colors duration-300 text-white font-medium py-2 px-4 flex flex-row flex-wrap content-around justify-center items-center rounded" id="inventory-search-button">
                <i class="bi-search mr-2"></i>
                <span id="button-content" >Search </span>
                <span class="btn-ring hidden"></span>

            </button>
        </div>
    </div>
</form>
<script>
    let priceWidget;
    document.addEventListener('DOMContentLoaded', function() {
        priceWidget = new mdc.slider.MDCSlider(document.querySelector('#autocart-price-range-field'));
        priceWidget.listen('MDCSlider:input', updatePiceWidget);


        kilometresWidget = new mdc.slider.MDCSlider(document.querySelector('#autocart-kilometres-range-field'));
        kilometresWidget.listen('MDCSlider:input', updateMileageWidget);

        const year = document.querySelector('#vehicle_search_year');
        const make = document.querySelector('#vehicle_search_make');
        const model = document.querySelector('#vehicle_search_model');

        // Initial AJAX request on document ready
        handleFieldChange([{
                property: 'body_type',
                name: 'Body Type',
                selector: '#vehicle_search_body_type'
            },
            {
                property: 'transmission_type',
                name: 'Transmission',
                selector: '#vehicle_search_transmission'
            },
            {
                property: 'make',
                name: 'Make',
                selector: '#vehicle_search_make'
            },
            {
                property: 'model',
                name: 'Model',
                selector: '#vehicle_search_model'
            }
        ]);


        year.addEventListener('change', function() {
            debouncedHandleFieldChange([{
                    property: 'body_type',
                    name: 'Body Type',
                    selector: '#vehicle_search_body_type'
                },
                {
                    property: 'transmission_type',
                    name: 'Transmission',
                    selector: '#vehicle_search_transmission'
                },
                {
                    property: 'make',
                    name: 'Make',
                    selector: '#vehicle_search_make'
                },
                {
                    property: 'model',
                    name: 'Model',
                    selector: '#vehicle_search_model'
                }
            ])
        });
        make.addEventListener('change', function() {
            debouncedHandleFieldChange([{
                    property: 'model',
                    name: 'Model',
                    selector: '#vehicle_search_model'
                },
                {
                    property: 'body_type',
                    name: 'Body Type',
                    selector: '#vehicle_search_body_type'
                },
                {
                    property: 'transmission_type',
                    name: 'Transmission',
                    selector: '#vehicle_search_transmission'
                },
            ])
        });
        model.addEventListener('change', function() {
            debouncedHandleFieldChange([{
                property: 'trim',
                name: 'Tim',
                selector: '#vehicle_search_trim'
            }])
        });

        const btns = document.getElementsByClassName("ripple-effect");

        for (const btn of btns) {
            btn.addEventListener("click", rippleEffect);
        }
    });


    function updateMileageWidget() {
        document.querySelector('label.range-label[for="autocart-kilometres-range-field"]').textContent = `${kilometresWidget.getValueStart()} to ${kilometresWidget.getValue()}`;
        debouncedHandleFieldChange();
    }

    function updatePiceWidget() {
        document.querySelector('label.range-label[for="autocart-price-range-field"]').textContent = `${priceWidget.getValueStart()} to ${priceWidget.getValue()}`;
        debouncedHandleFieldChange();
    }


    function debounce(func, delay) {
        let timeout;
        return function() {
            const context = this;
            const args = arguments;
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(context, args), delay);
        };
    }


    const debouncedHandleFieldChange = debounce(
        function(inputs) {
            handleFieldChange(inputs);
        }, 300);





    function handleFieldChange(inputs = []) {
        // const price = document.querySelector('#autocart-price-field');
        const year = document.querySelector('#vehicle_search_year');
        const make = document.querySelector('#vehicle_search_make');
        const loading = document.querySelector('.btn-ring');

        // let priceRange = JSON.parse(priceWidget.value);
        // let minPrice = priceRange[0];
        // let maxPrice = priceRange[1];

        let yearRange = JSON.parse(year.value);
        console.log('yearRange', yearRange)
        let minYear = yearRange[0];
        let maxYear = yearRange[1];

        document.getElementById('autocart-max-price-field-input').value = priceWidget.getValue();;
        document.getElementById('autocart-min-price-field-input').value = priceWidget.getValueStart();
        document.getElementById('autocart-max-year-field-input').value = maxYear;
        document.getElementById('autocart-min-year-field-input').value = minYear;
        document.getElementById('autocart-make-field-input').value = make.value;

        // var formData = {
        //     'action': 'handle_autocart_form',
        //     'minPrice': priceWidget.getValueStart(),
        //     'maxPrice': priceWidget.getValue(),
        //     'make': make.value,
        //     'minYear':  minYear,
        //     'maxYear':  maxYear,
        //     'autocart_nonce': jQuery('#autocart_nonce').val(),
        // };

        var formData = {
            'action': 'handle_autocart_form',
            'minPrice': priceWidget.getValueStart(),
            'maxPrice': priceWidget.getValue(),
            'minKilometres': kilometresWidget.getValueStart(),
            'maxKilometres': kilometresWidget.getValue(),
            'minYear': minYear,
            'maxYear': maxYear,
            'make': make.value,
            'autocart_nonce': jQuery('#autocart_nonce').val(),
        };
        jQuery(" #button-content").text("Loading...");
        loading.classList.remove('hidden'); 

        jQuery.ajax({
            type: 'POST',
            url: ajax_object.ajax_url,
            data: formData,
            success: function(response) {
                loading.classList.add('hidden'); // Hide the btn-ring on success

                if(response.success){
                    const vehicles = response.data.vehicles;
                    if (inputs) {
                        inputs.forEach(element => {
                            createOptions(vehicles, element);
                        });
                    }
                    jQuery(" #button-content").text("Search (" + vehicles.length + ")");
                }else{
                    alert(response.data.message);
                    jQuery(" #button-content").text("Search");

                }
                
            },
            error: function(xhr, status, error) {
                loading.classList.add('hidden'); // Hide the btn-ring on error
                console.log(xhr.responseText);
                console.log('Status: ' + status);
                console.log('Error: ' + error);
                // jQuery("").text("Error");
            }
        });
    }

    function rippleEffect(event) {
        const btn = event.currentTarget;
        btn.classList.add("overflow-hidden", "shadow", "relative");

        const circle = document.createElement("span");
        const rect = btn.getBoundingClientRect();
        const diameter = Math.max(btn.clientWidth, btn.clientHeight);
        const radius = diameter / 2;

        const offsetX = event.clientX - rect.left;
        const offsetY = event.clientY - rect.top;

        circle.style.width = circle.style.height = `${diameter}px`;
        circle.style.left = `${offsetX - radius}px`;
        circle.style.top = `${offsetY - radius}px`;
        circle.classList.add("ripple");

        const ripple = btn.getElementsByClassName("ripple")[0];

        if (ripple) {
            ripple.remove();
        }
        btn.appendChild(circle);
    }

    function createOptions(vehicles, input) {
        if (vehicles.length) {
            const element = document.querySelector(input.selector);

            // Remove existing options only
            const existingOptions = element.querySelectorAll('option');
            existingOptions.forEach(option => option.remove());

            const counts = vehicles.reduce((acc, vehicle) => {
                const value = vehicle[input.property];
                acc[value] = (acc[value] || 0) + 1;
                return acc;
            }, {});

            // Sort the property values alphabetically
            const sortedValues = Object.keys(counts).sort();

            // Add "All" at the beginning
            sortedValues.unshift(`All ${input.name}s`);

            // Create and append options
            sortedValues.forEach(value => {
                var option = document.createElement("option");
                option.text = value;
                option.value = value;
                option.style.textTransform = "capitalize";
                element.appendChild(option);
            });
        }

    }
</script>