/*
Product Name: Windz App
Author: KodingStudio
Website: https://kodingstudio.com/
Contact: contact@kodingstudio.com
File: Agent Js File
*/

let fromLat = 0.0,
    fromLng = 0.0,
    toLat = 0.0,
    toLng = 0.0,
    zoneId = '' ;

let estimatedDistance,
     estimatedDuration,
     estimatedFare,
     returnFee,
     cancellationFee;

let fromLocationAutoComplete,
    toLocationAutoComplete;

let stepArrow1stStepTab = document.getElementById('steparrow-gen-info-tab');
let stepArrow1stStepContent = document.getElementById('steparrow-gen-info');

let stepArrow2ndStepTab = document.getElementById('steparrow-description-info-tab');
let stepArrow2ndStepContent = document.getElementById('steparrow-description-info');

let stepArrow3rdStepTab = document.getElementById('pills-experience-tab');
let stepArrow3rdStepContent = document.getElementById('pills-experience');

const inputFromLocation = document.getElementById("input-from-location"),
    inputSenderName = document.getElementById("input-sender-name"),
    inputSenderNumber = document.getElementById("input-sender-number"),
    inputToLocation = document.getElementById("input-to-location"),
    inputReceiverName = document.getElementById("input-receiver-name"),
    inputReceiverNumber = document.getElementById("input-receiver-number");

let inputWeight = document.getElementById("input-weight"),
    inputDuration = document.getElementById("input-duration"),
    inputDistance = document.getElementById("input-distance"),
    inputFare = document.getElementById("input-fare");

let layoutMessage = document.getElementById("layout-message"),
    txtTitle = document.getElementById("txt-title"),
    txtTagline = document.getElementById("txt-tagline");

inputDuration.disabled = true;
inputDistance.disabled = true;
inputFare.disabled = true;

let selectorBusiness = document.getElementById('choice-business');
let choiceBusiness = new Choices(selectorBusiness, {
    searchEnabled: true
});

/*let selectorGroup = document.getElementById('choice-group');
let choiceGroup = new Choices(selectorGroup, {
    searchEnabled: true
});*/

let selectorUser = document.getElementById('choice-user');
let choiceUser = new Choices(selectorUser, {
    searchEnabled: true
});

let selectorVehicle = document.getElementById('choice-vehicle');
let choiceVehicle = new Choices(selectorVehicle, {
    searchEnabled: false
});

let selectorPaymentMethod = document.getElementById('choice-payment-method');
let choicePaymentMethod = new Choices(selectorPaymentMethod, {
    searchEnabled: false,
    choices : [{
        value: 'business_wallet',
        label: 'Business Wallet'
    }]
});

let btnEstimate = document.getElementById('btn-estimate');
let btnNextStep = document.getElementById('btn-next-step');
let btnBookRide = document.getElementById('btn-book-ride');

selectorBusiness.addEventListener("change", function (evt) {
    getSpecificGroupUser();
});
/*selectorGroup.addEventListener("change", function (evt) {
    getSpecificGroupUser();
});*/

btnEstimate.addEventListener("click", function (e) {

    if (choicePaymentMethod.getValue(true) === '' ||
        choiceVehicle.getValue(true) === '' ||
        inputWeight.value === ''){

        alert('Select and fill required information');

        return;
    }

    let paymentMethod = choicePaymentMethod.getValue(true);
    let vehicleCategoryId = choiceVehicle.getValue(true);

    postRequest({
        zone_id : zoneId,
        from_lat : fromLat,
        from_lng : fromLng,
        pickup_address : inputFromLocation.value,
        to_lat : toLat,
        to_lng : toLng,
        destination_address : inputToLocation.value,
        weight : inputWeight.value,
        parcel_category_id : vehicleCategoryId
    },baseUrl + 'v1/web/parcel/get-fare-estimation')
        .then(response => JSON.parse(response.data))
        .then(data => {

            //console.log(JSON.stringify(data));

            inputDuration.disabled = false;
            inputDistance.disabled = false;
            inputFare.disabled = false;

             estimatedDistance = data.data.estimated_distance;
             estimatedDuration = data.data.estimated_duration;
             estimatedFare = data.data.estimated_fare;
             returnFee = data.data.return_fee;
             cancellationFee = data.data.cancellation_fee;

            inputDistance.value = estimatedDistance;
            inputDuration.value = estimatedDuration;
            inputFare.value = estimatedFare;

            inputDistance.disabled = true;
            inputDuration.disabled = true;
            inputFare.disabled = true;

        })
        .catch(error => {

            let data = JSON.parse(error.data);
            Swal.fire({
                position: 'center',
                icon: 'error',
                title: data.message,
                showConfirmButton: false,
                timer: 2000,
                showCloseButton: true
            });
            customerList.remove("id", '<a href="javascript:void(0);" class="fw-medium link-primary">#VZ2101</a>');

        });

});

btnNextStep.addEventListener("click", function (e) {

    if (inputFromLocation.value === '' ||
        inputSenderName.value === '' ||
        inputSenderNumber.value === '' ||
        inputToLocation.value === '' ||
        inputReceiverName.value === '' ||
        inputReceiverNumber.value === ''){


        alert('fill all of the required details');

        return;
    }

    stepArrow1stStepTab.classList.remove('active');
    stepArrow1stStepContent.classList.remove('active');
    stepArrow1stStepContent.classList.remove('show');

    stepArrow2ndStepTab.classList.add('active');
    stepArrow2ndStepContent.classList.add('active');
    stepArrow2ndStepContent.classList.add('show');

});
btnBookRide.addEventListener("click", function (e) {

    if (inputDistance.value ==='' ||
        inputWeight.value ==='' ||
        choiceBusiness.getValue(true) ==='' ||
        choiceUser.getValue(true) ===''){

        alert('kindly estimate the fare please.');

        return;
    }


    let paymentMethod = choicePaymentMethod.getValue(true);
    let vehicleCategoryId = choiceVehicle.getValue(true);

    postRequest({
        business_id : choiceBusiness.getValue(true),
        people_id : choiceUser.getValue(true),

        zone_id : zoneId,
        from_lat : fromLat,
        from_lng : fromLng,
        pickup_address : inputFromLocation.value,
        to_lat : toLat,
        to_lng : toLng,
        destination_address : inputToLocation.value,
        weight : inputWeight.value,
        parcel_category_id : vehicleCategoryId,
        payment_method : paymentMethod,

        estimated_distance : inputDistance.value,
        estimated_time : inputDuration.value,
        estimated_fare : inputFare.value,
        actual_fare : inputFare.value,
        return_fee : returnFee,
        cancellation_fee : cancellationFee,

        sender_name : inputSenderName.value,
        sender_phone : inputSenderNumber.value,
        receiver_name : inputReceiverName.value,
        receiver_phone : inputReceiverNumber.value

    },
        baseUrl + 'v1/web/parcel/create-booking')
        .then(response => JSON.parse(response.data))
        .then(data => {

            stepArrow1stStepTab.classList.remove('active');
            stepArrow1stStepContent.classList.remove('active');
            stepArrow1stStepContent.classList.remove('show');

            stepArrow2ndStepTab.classList.remove('active');
            stepArrow2ndStepContent.classList.remove('active');
            stepArrow2ndStepContent.classList.remove('show');

            stepArrow3rdStepTab.classList.add('active');
            stepArrow3rdStepContent.classList.add('active');
            stepArrow3rdStepContent.classList.add('show');

            ///console.log(JSON.stringify(data));

            if (data.data.current_status === 'pending'){

                layoutMessage.innerHTML = `<div class="text-center">
                                                  <lord-icon
                                                    src="https://cdn.lordicon.com/euaablbm.json"
                                                    trigger="hover"
                                                    stroke="bold"
                                                    style="width:70px;height:70px">
                                                </lord-icon>
                                           </div>`;

                txtTitle.innerText = 'Pending';
                txtTagline.innerText = 'Rider did not accept your request until yet';

                // Then call again every intervalMs milliseconds
                const intervalId = setInterval(() => {

                    postRequest({
                        zone_id : zoneId,
                        booking_id : data.data.id
                    },baseUrl + 'v1/web/parcel/get-ride-detail')
                        .then(response => JSON.parse(response.data))
                        .then(data => {

                            let currentStatus = data.data.current_status;
                            if ((currentStatus !== 'pending')){

                                clearInterval(intervalId);
                                layoutMessage.innerHTML = `<div class="avatar-title bg-light text-success display-4 rounded-circle">
                                                  <i class="ri-checkbox-circle-fill"></i>
                                           </div>`;
                                txtTitle.innerText = 'Book Successfully';
                                txtTagline.innerText = 'Ride is on the way';

                            }

                        })
                        .catch(error => {

                            let data = JSON.parse(error.data);
                            Swal.fire({
                                position: 'center',
                                icon: 'error',
                                title: data.message,
                                showConfirmButton: false,
                                timer: 2000,
                                showCloseButton: true
                            });
                            customerList.remove("id", '<a href="javascript:void(0);" class="fw-medium link-primary">#VZ2101</a>');

                        });


                }, 50000);

            }
            else {

                layoutMessage.innerHTML = `<div class="avatar-title bg-light text-success display-4 rounded-circle">
                                                  <i class="ri-checkbox-circle-fill"></i>
                                           </div>`;
                txtTitle.innerText = 'Book Successfully';
                txtTagline.innerText = 'Ride is on the way';

            }





        })
        .catch(error => {

            let data = JSON.parse(error.data);
            Swal.fire({
                position: 'center',
                icon: 'error',
                title: data.message,
                showConfirmButton: false,
                timer: 2000,
                showCloseButton: true
            });
            customerList.remove("id", '<a href="javascript:void(0);" class="fw-medium link-primary">#VZ2101</a>');

        });

});

/*function getSpecificBusinessGroup(edit = false, groupId = 0){

    /!*choiceGroup.destroy();
    choiceGroup.init();*!/

    fetchSpecificBusinessGroupsEndpoint(baseUrl + 'v1/web/group/specific/business/'+choiceBusiness.getValue(true))
        .then(response => JSON.parse(response.data))
        .then(data => {

            let dataList = [];
            Array.from(data.data).forEach(raw => {

                const param = {
                    label: raw.name,
                    value: raw.id
                };
                dataList.push(param);

            });

            choiceGroup.setChoices(
                dataList,
                'value',
                'label',
                false,
            );


            if (edit)
                choiceGroup.setChoiceByValue(groupId);


        })
        .catch(error => {

            let data = JSON.parse(error.data);
            Swal.fire({
                position: 'center',
                icon: 'error',
                title: data.message,
                showConfirmButton: false,
                timer: 2000,
                showCloseButton: true
            });
            customerList.remove("id", '<a href="javascript:void(0);" class="fw-medium link-primary">#VZ2101</a>');

        });


}*/
function getSpecificGroupUser(edit = false, userId = 0){

    choiceUser.destroy();
    choiceUser.init();

    fetchSpecificBusinessPeopleEndpoint(baseUrl + 'v1/web/people/specific/business/'+choiceBusiness.getValue(true))
        .then(response => JSON.parse(response.data))
        .then(data => {

            let dataList = [];
            Array.from(data.data).forEach(raw => {

                const param = {
                    label: raw.name,
                    value: raw.id
                };
                dataList.push(param);

            });

            choiceUser.setChoices(
                dataList,
                'value',
                'label',
                false,
            );


            if (edit)
                choiceUser.setChoiceByValue(userId);


        })
        .catch(error => {

            let data = JSON.parse(error.data);
            Swal.fire({
                position: 'center',
                icon: 'error',
                title: data.message,
                showConfirmButton: false,
                timer: 2000,
                showCloseButton: true
            });
            customerList.remove("id", '<a href="javascript:void(0);" class="fw-medium link-primary">#VZ2101</a>');

        });


}

function fetchSpecificBusinessPeopleEndpoint(url ) {
    return new Promise(function (resolve, reject) {

        const xhttp = new XMLHttpRequest();
        xhttp.onload = function () {

            var status = xhttp.status;
            if (status === 200 || status === 201 || 204) {
                resolve({code: status, data: this.responseText});
            } else {
                reject({code: status, data: this.responseText});
            }

        };
        xhttp.open("GET", url, true);
        for (let i = 0; i < listOfHeaders.length; i++) {
            xhttp.setRequestHeader(listOfHeaders[i]['key'], listOfHeaders[i]['value']);
        }

        xhttp.send();

    });
}
function fetchBusinessEndpoint(url= baseUrl + 'v1/web/business/active') {
    return new Promise(function (resolve, reject) {

        const xhttp = new XMLHttpRequest();
        xhttp.onload = function () {

            var status = xhttp.status;
            if (status === 200 || status === 201 || 204) {
                resolve({code: status, data: this.responseText});
            } else {
                reject({code: status, data: this.responseText});
            }

        };
        xhttp.open("GET", url, true);
        for (let i = 0; i < listOfHeaders.length; i++) {
            xhttp.setRequestHeader(listOfHeaders[i]['key'], listOfHeaders[i]['value']);
        }

        xhttp.send();

    });

}
function postRequest(jsonParam, url) {
    return new Promise(function (resolve, reject) {

        const xhttp = new XMLHttpRequest();
        xhttp.onload = function () {

            var status = xhttp.status;
            if (status === 200 || status === 201 || 204) {
                resolve({code: status, data: this.responseText});
            } else {
                reject({code: status, data: this.responseText});
            }

        };
        xhttp.open("POST", url, true);
        for (let i = 0; i < listOfHeaders.length; i++) {
            xhttp.setRequestHeader(listOfHeaders[i]['key'], listOfHeaders[i]['value']);
        }

        xhttp.send(JSON.stringify(jsonParam));

    });

}
function getRequest(url) {
    return new Promise(function (resolve, reject) {

        const xhttp = new XMLHttpRequest();
        xhttp.onload = function () {

            var status = xhttp.status;
            if (status === 200 || status === 201 || 204) {
                resolve({code: status, data: this.responseText});
            } else {
                reject({code: status, data: this.responseText});
            }

        };
        xhttp.open("GET", url, true);
        for (let i = 0; i < listOfHeaders.length; i++) {
            xhttp.setRequestHeader(listOfHeaders[i]['key'], listOfHeaders[i]['value']);
        }

        xhttp.send();

    });

}

function initAutocomplete() {

    if (fromLocationAutoComplete == null || toLocationAutoComplete == null){

        fromLocationAutoComplete = new google.maps.places.Autocomplete(inputFromLocation);
        toLocationAutoComplete = new google.maps.places.Autocomplete(inputToLocation);

    }

    fromLocationAutoComplete.addListener("place_changed", () => {
        const fromPlace = fromLocationAutoComplete.getPlace();

        let fromGeometry = fromPlace.geometry;
        let fromLocation = fromGeometry.location;

        fromLat = fromLocation.lat();
        fromLng = fromLocation.lng();

        console.log("From Place selected : ", "Latitude = "+fromLat+" Longitude = "+fromLng);

        postRequest({
            lat : fromLat,
            lng : fromLng
        },baseUrl + 'v1/web/parcel/get-zone-id')
            .then(response => JSON.parse(response.data))
            .then(data => {

                zoneId = data.data.id;
                postRequest({
                    zone_id : zoneId
                },baseUrl + 'v1/web/parcel/get-vehicle-ctg')
                    .then(response => JSON.parse(response.data))
                    .then(data => {

                        choiceVehicle.destroy();
                        choiceVehicle.init();

                        let dataList = [];
                        Array.from(data.data).forEach(raw => {

                            const param = {
                                label: raw.name,
                                value: raw.id
                            };
                            dataList.push(param);

                        });
                        choiceVehicle.setChoices(
                            dataList,
                            'value',
                            'label',
                            false,
                        );

                    })
                    .catch(error => {

                        let data = JSON.parse(error.data);
                        Swal.fire({
                            position: 'center',
                            icon: 'error',
                            title: data.message,
                            showConfirmButton: false,
                            timer: 2000,
                            showCloseButton: true
                        });
                        customerList.remove("id", '<a href="javascript:void(0);" class="fw-medium link-primary">#VZ2101</a>');

                    });

            })
            .catch(error => {

                let data = JSON.parse(error.data);
                Swal.fire({
                    position: 'center',
                    icon: 'error',
                    title: data.message,
                    showConfirmButton: false,
                    timer: 2000,
                    showCloseButton: true
                });
                customerList.remove("id", '<a href="javascript:void(0);" class="fw-medium link-primary">#VZ2101</a>');

            });


    });
    toLocationAutoComplete.addListener("place_changed", () => {
        const toPlace = toLocationAutoComplete.getPlace();

        let toGeometry = toPlace.geometry;
        let toLocation = toGeometry.location;

        toLat = toLocation.lat();
        toLng = toLocation.lng();

        //console.log("To Place selected : ", "Latitude = "+toLat+" Longitude = "+toLong);

    });

}

fetchBusinessEndpoint()
    .then(response => JSON.parse(response.data))
    .then(data => {

        let dataList = [];
        Array.from(data.data).forEach(raw => {

            const param = {
                label: raw.name,
                value: raw.id
            };
            dataList.push(param);

        });

        choiceBusiness.setChoices(
            dataList,
            'value',
            'label',
            false,
        );


    })
    .catch(error => {

        let data = JSON.parse(error.data);
        Swal.fire({
            position: 'center',
            icon: 'error',
            title: data.message,
            showConfirmButton: false,
            timer: 2000,
            showCloseButton: true
        });
        customerList.remove("id", '<a href="javascript:void(0);" class="fw-medium link-primary">#VZ2101</a>');

    });

inputFromLocation.addEventListener("focus", function() {
    initAutocomplete();
});
inputToLocation.addEventListener("focus", function() {
    initAutocomplete();
});

// --- Debug log ---
    Pusher.logToConsole = true;

    // --- Initialize ---
    const pusher = new Pusher('drivemond', {
      wsHost: 'areye.app',        // e.g. areye.app
       wsPort: 6001,
        wssPort: 6001,
        forceTLS: false,        // important → disables https/wss
        encrypted: false,
        enabledTransports: ['ws'], // avoid wss, use ws only
        disableStats: true,    
      cluster: "mt1",// skip pusher analytics
    });

    // --- Subscribe ---
    /*const channel = pusher.subscribe('private-customer-trip-request'); 
    // if no auth used, still can try private name

    channel.bind('new-trip', function (data) {
      console.log('📦 Event received:', data);
      //document.getElementById('status').innerText = 'Event: ' + JSON.stringify(data);
    });*/

    // --- Connection status ---
    pusher.connection.bind('connected', () => {
      //document.getElementById('status').innerText = '✅ Connected to WebSocket';
      console.log('Connected');
    });

    pusher.connection.bind('error', err => {
      //document.getElementById('status').innerText = '❌ Connection error';
      console.error('Error:', err);
    });

if (document.querySelectorAll(".form-steps"))
    Array.from(document.querySelectorAll(".form-steps")).forEach(function (form) {

        // next tab
        /*if (form.querySelectorAll(".nexttab")){
            Array.from(form.querySelectorAll(".nexttab")).forEach(function (nextButton) {
                var tabEl = form.querySelectorAll('button[data-bs-toggle="pill"]');
                Array.from(tabEl).forEach(function (item) {
                    item.addEventListener('show.bs.tab', function (event) {
                        event.target.classList.add('done');
                    });
                });
                nextButton.addEventListener("click", function () {
                    ///form.classList.add('was-validated');
                    form.querySelectorAll(".tab-pane.show .form-control").forEach(function(elem){
                        var validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
                        if(elem.value.length > 0 /!*&& elem.value.match(validRegex)*!/){
                            var nextTab = nextButton.getAttribute('data-nexttab');
                            document.getElementById(nextTab).click();
                            form.classList.remove('was-validated');
                        }
                    })
                })
            });
        }*/

        //Pervies tab
        if (form.querySelectorAll(".previestab"))
            Array.from(form.querySelectorAll(".previestab")).forEach(function (prevButton) {

                prevButton.addEventListener("click", function () {
                    var prevTab = prevButton.getAttribute('data-previous');
                    var totalDone = prevButton.closest("form").querySelectorAll(".custom-nav .done").length;
                    for (var i = totalDone - 1; i < totalDone; i++) {
                        (prevButton.closest("form").querySelectorAll(".custom-nav .done")[i]) ? prevButton.closest("form").querySelectorAll(".custom-nav .done")[i].classList.remove('done'): '';
                    }
                    document.getElementById(prevTab).click();
                });
            });

        // Step number click
        var tabButtons = form.querySelectorAll('button[data-bs-toggle="pill"]');
        if (tabButtons)
            Array.from(tabButtons).forEach(function (button, i) {
                button.setAttribute("data-position", i);
                button.addEventListener("click", function () {
                    form.classList.remove('was-validated');

                    var getProgressBar = button.getAttribute("data-progressbar");
                    if (getProgressBar) {
                        var totalLength = document.getElementById("custom-progress-bar").querySelectorAll("li").length - 1;
                        var current = i;
                        var percent = (current / totalLength) * 100;
                        document.getElementById("custom-progress-bar").querySelector('.progress-bar').style.width = percent + "%";
                    }
                    (form.querySelectorAll(".custom-nav .done").length > 0) ?
                        Array.from(form.querySelectorAll(".custom-nav .done")).forEach(function (doneTab) {
                            doneTab.classList.remove('done');
                        }): '';
                    for (var j = 0; j <= i; j++) {
                        tabButtons[j].classList.contains('active') ? tabButtons[j].classList.remove('done') : tabButtons[j].classList.add('done');
                    }
                });
            });
    });







