<style>
    .ListRowCard {
        margin-bottom: 5px;
    }

    .pdbottom {
        overflow: hidden;
        padding-bottom: 5px;
        text-align: center;
    }
</style>
<div id="MainView">

    <div class="row" id="MainRowContainer">
        <center>
            <h3>Loading...</h3>
        </center>
    </div>

</div>

</div>

<script>
    LoadDataPageFunc = {};
    LoadDataPageFunc.PageTitle = 'Product Details';
    LoadDataPageFunc.MainDetailsURL = '';
    LoadDataPageFunc.Details = {};
    LoadDataPageFunc.Settings = {};
    LoadDataPageFunc.Settings.ProductNotAvailableModalDismissed = false;

    LoadDataPageFunc.NewMainColumn = function (id, Cardtitle, CardContent, CardID) {
        return `<div class="col-md-12 pdbottom" style="" id="${id}Container">
      ${CreateCardSimple(Cardtitle, CardContent, CardID,)}
        </div>`;
    };

    LoadDataPageFunc.PopulateDetailsNow = function (obj) {
  
        const details = obj.details || '';
        const total = details.total || 'Unknown';
        const containerID = 'CardCartContainer';
        let cardhtmlArr = [];

        iterateArray(obj.cart, (item, key) => {
            cardhtmlArr.push(LoadDataPageFunc.CartProductRow(item, key, false) + '<br><br>');
        });

        const cardhtml = cardhtmlArr.join('');
        const CardCartColumn = LoadDataPageFunc.NewMainColumn('CardCartContainer', 'Items', cardhtml, 'CardCart')

        const TotalPricehtml = `
        <h1>Total Price: <h1>
        <h1 id="TotalPrice" style="text-align: center;color: red;">${formatCurrency(total)}</h1>`;
        const TotalPriceColumn = LoadDataPageFunc.NewMainColumn('TotalPriceCardContainer', false, TotalPricehtml, 'TotalPriceCard');

        const AddressHtml = `
        
        `;
        const AddressColumn = LoadDataPageFunc.NewMainColumn('AddressContainer', "Address", AddressHtml, 'AddressCard');


        const PurchaseHtml = buttonprimary(imgiconuserdefault("/assets/plus-cart.png") + 'Proceed Purchase', '', 'LoadDataPageFunc.ConfirmPurchase();');
        const ConfirmPurchaseColumn = LoadDataPageFunc.NewMainColumn('PurchaseContainer', false, PurchaseHtml, 'PurchaseCard');
        const finalhtml = CardCartColumn + TotalPriceColumn + AddressColumn + ConfirmPurchaseColumn;
        $('#MainRowContainer').html(finalhtml);

    };

    LoadDataPageFunc.Settings.Phototype = "ProductMarket";

    LoadDataPageFunc.CartProductRow = MarketUI.CartProductRow;

    LoadDataPageFunc.BuySuccess = function () {
        ModalQuickDismiss(false, 'Successfully Bought Product!', 'ModalConfirmBuySuccess');
        gotoPage('PendingBuysProductMarket');
        return;
    };

    LoadDataPageFunc.BuyFailed = function (response) {
        ModalQuickDismiss(false, 'Unable to Complete Purchase!<br>' + response, 'ModalConfirmBuyFailed');
        return;
    };

    LoadDataPageFunc.ConfirmPurchase = function () {
        if (!LoadDataPageFunc.CurrentSelectedAddress) {
            ModalQuickDismiss(false, 'Please select an address to proceed with purchase.', 'ModalConfirmBuy');
            return false;
        }
        let reqqpurchase = new RequestData(false);
        reqqpurchase.fromVarCache(false).data({ targetproduct: currenttarget }).url('/Buy/Complete/Purchase')
            .success((response) => {

                if (response !== true) { LoadDataPageFunc.BuyFailed(response); return false; }
                else { LoadDataPageFunc.BuySuccess(); return true; }

            }).go();
    };

    LoadDataPageFunc.BuyDetails = {};
    LoadDataPageFunc.AddressDetails = false;
    LoadDataPageFunc.CurrentSelectedAddress = false;

    LoadDataPageFunc.NewAddressValidate = function () {
        const name = $('#NewAddressName').val();
        const address = $('#NewAddress').val();
        const contactname = $('#NewContactName').val();
        const contactnumber = $('#NewContactNumber').val();
        const defaultaddress = $('#NewDefaultAddress').is(':checked');

        if (!name || !address || !contactname || !contactnumber) {
            return false;
        }
        return { 'name': name, 'address': address, 'contactname': contactname, 'contactnumber': contactnumber, 'default': defaultaddress };
    }

    LoadDataPageFunc.SubmitNewAddress = function () {
        const addressformdata = LoadDataPageFunc.NewAddressValidate();
        if (!addressformdata) {
            ModalQuickDismiss(false, 'Please fill in all fields!');
            return false;
        }

        let submitReq = new RequestData(false);
        submitReq.fromVarCache(false).type('POST').url('/User/My/Add/Address').data(addressformdata).success(
            (response) => {

                if (!response) {
                    ModalQuickDismiss(false, 'Unable to add address!<br>', 'ModalAddAddressSubmitFailed');
                    return false;
                }

                modaldestroy();
                hideallmodals();

                LoadDataPageFunc.fetchAddresses((response) => {
                    //modalhide('NewAddressModal');

                    if (addressformdata.default) {
                        LoadDataPageFunc.CurrentSelectedAddress = LoadDataPageFunc.FindDefaultAddressBasedonAddressDetails();
                        LoadDataPageFunc.UpdateAddressCard(response);
                    }

                    LoadDataPageFunc.ShowAddressesModal();

                });
            }
        ).go();


    };


    LoadDataPageFunc.NewAddressModal = function () {
        const textbox = function (placeholder, label, idsuffix, required = false, datalist = '') {
            return UIInputGroup(placeholder, 'text', 'New' + idsuffix, label, formclass = '', spanclass = '', imginsteadofspan = '', required, textvalue = '', datalist, imgwidth = '', imgheight = '');
        };
        const name = textbox('Address Name', 'Address Name', 'AddressName', true);
        const address = textbox('Address', 'Address', 'Address', true);
        const contactname = textbox('Recipient Name for the Address', 'Recipient Name', 'ContactName', true);
        const contactnumber = textbox('Recipient Number for the Address', 'Recipient Number', 'ContactNumber', true);
        const checkbox = `<input class="btn btn-primary" type="checkbox" id="NewDefaultAddress">Set As Default?`;

        const finalform = name + address + contactname + contactnumber + checkbox;
        const footerbuttons = buttonprimary('Submit Address', '', 'LoadDataPageFunc.SubmitNewAddress();');
        CreateAndShowModal('NewAddressModal', 'New Address', finalform, footerbuttons, false);
    };

    LoadDataPageFunc.SelectCurrentAddress = function () {
        const selectedaddress = LoadDataPageFunc.GetSelectAddressUIFields();
       LoadDataPageFunc.CurrentSelectedAddress= selectedaddress;

       LoadDataPageFunc.UpdateAddressCard([LoadDataPageFunc.CurrentSelectedAddress]);
        hideallmodals();
        modaldestroy();
        //capture select control value and index and all textbox inside
        //show confirm Address selection modal
        //update LoadDataPageFunc.CurrentSelectedAddress
        //Update Address Card
        //close ShowAddressesModal and other Modals


    };

    LoadDataPageFunc.SelectedKey = false;

    LoadDataPageFunc.SetAsDefault = function () {
        const defaultkey = $('#InputSelectedAddress').val();
        let addressui = LoadDataPageFunc.GetSelectAddressUIFields();
        const datatosend = {
            'name': addressui[1], 'address': addressui[0],
            'contactname': addressui[2],
            'contactnumber': addressui[3],
            'key': defaultkey
        };
        let setasDefaultFetch = new RequestData(false);
        setasDefaultFetch.url('/User/My/SetasDefault/Address/').type('POST').data(datatosend).fromVarCache(false)
            .success((response) => {
                if (!response) {
                    ModalQuickDismiss(false, 'Error Try Again Later');
                    return false;
                }
                ModalQuickDismiss(false, 'Success');
                
                LoadDataPageFunc.fetchAddresses((response) => { 
                    LoadDataPageFunc.AddressDetails = response;
                    LoadDataPageFunc.CurrentSelectedAddress = LoadDataPageFunc.FindDefaultAddressBasedonAddressDetails();
                    hideallmodals();
                    modaldestroy();
                    LoadDataPageFunc.ShowAddressesModal(); 
                
                });
   

            }).go();
    };


    LoadDataPageFunc.ShowAddressesModal = function () {

        const title = 'Select Address';
        let modalbody = '<div style="text-align:center;">No Address</div>';
        const selectbutton = buttonprimary('Select Address', '', 'LoadDataPageFunc.SelectCurrentAddress();');
        const Newbutton = buttonwarning('New Address', '', 'LoadDataPageFunc.NewAddressModal();');
        const setasdefaultbutton = buttonprimary('Set As Default', '', 'LoadDataPageFunc.SetAsDefault();');
        let footerbuttons = '';
        let selectarray = [];
        let selectedkey = -1;
        const CurrentSelectedAddress = LoadDataPageFunc.CurrentSelectedAddressOBJ();
        const selectedname = CurrentSelectedAddress['name'];
        const selectedaddress = CurrentSelectedAddress['address'];
        const selectedcontactname = CurrentSelectedAddress['contactname'];
        const selectedcontactnumber = CurrentSelectedAddress['contactnumber'];

        let UIAddressField = {};
        UIAddressField.name = '';
        UIAddressField.address = '';
        UIAddressField.contactname = '';
        UIAddressField.contactnumber = '';

        if (!LoadDataPageFunc.AddressDetails) {
            footerbuttons = Newbutton;
        } else {
            footerbuttons = selectbutton + setasdefaultbutton + Newbutton;
        }

        if (LoadDataPageFunc.AddressDetails) {
            selectarray = [];
            selectedkey = -1;

            iterateArray(LoadDataPageFunc.AddressDetails, (item, key) => {
                const name = item[1];
                const address = item[0];
                const contactname = item[2];
                const contactnumber = item[3];


                if (name === selectedname && address === selectedaddress && contactname === selectedcontactname && contactnumber === selectedcontactnumber) {
                    selectedkey = key;
                } else {

                }
                selectarray.push([key, name]);
            });
            if (selectedkey > -1) {
                LoadDataPageFunc.SelectedKey = selectedkey;
            } else {
                LoadDataPageFunc.SelectedKey = false;
            }

            const InputSelectHTML = UIInputGroupSelect('InputSelectedAddress', '', selectarray, '', '', selectedkey);
            //  UIArraytoOptionforSelect(selectarray,selectedkey);

            //iterateArray() and 
            // if LoadDataPageFunc.CurrentSelectedAddress  is present then find it in the obj and select it if not then show all addresses and default to obj.default
            //Load SEleect Control

            modalbody = InputSelectHTML + `
            <h4 id="InputSelectContent-Name">${selectedname}</h4>
            <h4 id="InputSelectContent-Address">${selectedaddress}</h4>
            <h4 id="InputSelectContent-ContactName">${selectedcontactname}</h4>
            <h4 id="InputSelectContent-ContactAddress">${selectedcontactnumber}</h4>
            `;

            footerbuttons = selectbutton + setasdefaultbutton + Newbutton;;

        }



        const finalmodal = CreateAndShowModal('ShowAddressesModal', 'Select Address', modalbody, footerbuttons, false);

        if (!LoadDataPageFunc.SelectedKey) {
            $('#InputSelectedAddress').val('');
        }

        const inputSelectedAddress = document.getElementById('InputSelectedAddress');
        inputSelectedAddress.addEventListener('change', function (event) {
            const value = event.target.value;
            LoadDataPageFunc.UpdateSelectAddressUIFields();

        });

    };

    LoadDataPageFunc.GetSelectAddressUIFields = function () {
        return [
            $('#InputSelectContent-Address').html(),
            $('#InputSelectContent-Name').html(),
            $('#InputSelectContent-ContactName').html(),
            $('#InputSelectContent-ContactAddress').html()];
    }
    LoadDataPageFunc.UpdateSelectAddressUIFields = function () {
        const currentselected = $('#InputSelectedAddress').val();

        if (currentselected === false || currentselected === null) { return false; }

        const SelectedData = LoadDataPageFunc.AddressDetails[currentselected];

        const selectedname = SelectedData[1];
        const selectedaddress = SelectedData[0];
        const selectedcontactname = SelectedData[2];
        const selectedcontactnumber = SelectedData[3];

        $('#InputSelectContent-Name').html(selectedname);
        $('#InputSelectContent-Address').html(selectedaddress);
        $('#InputSelectContent-ContactName').html(selectedcontactname);
        $('#InputSelectContent-ContactAddress').html(selectedcontactnumber);



    }

    LoadDataPageFunc.FindDefaultAddressBasedonAddressDetails = function () {
        let foundIndex = -1;
        let arrayofArrays = LoadDataPageFunc.AddressDetails;
        arrayofArrays.forEach((innerArray, index) => {
            if (innerArray.length >= 4) {
                if (typeof innerArray[4] !== 'undefined') {
                    const fourthElement = innerArray[4];
                    if (fourthElement === true) {
                        foundIndex = index;
                    }
                }
            }
        });

        if (foundIndex > -1) { return arrayofArrays[foundIndex]; } else { return false; }
    };

    LoadDataPageFunc.CurrentSelectedAddressOBJ = function () {
        if (Array.isArray(LoadDataPageFunc.CurrentSelectedAddress)) {

            const name = LoadDataPageFunc.CurrentSelectedAddress[1];
            const address = LoadDataPageFunc.CurrentSelectedAddress[0];
            const contactname = LoadDataPageFunc.CurrentSelectedAddress[2];
            const contactnumber = LoadDataPageFunc.CurrentSelectedAddress[3];
            const defaultaddress = LoadDataPageFunc.CurrentSelectedAddress[4];
            return { 'name': name, 'address': address, 'contactname': contactname, "contactnumber": contactnumber };
        } else { return false; }
    };

    LoadDataPageFunc.UpdateAddressCard = function (objAdd) {

        const btn = button('Select Address', '', 'LoadDataPageFunc.ShowAddressesModal();', '', 'btn');
       
        if (!LoadDataPageFunc.CurrentSelectedAddress) {
            LoadDataPageFunc.CurrentSelectedAddress = LoadDataPageFunc.FindDefaultAddressBasedonAddressDetails();
        }

        if (!objAdd || !LoadDataPageFunc.CurrentSelectedAddressOBJ()) {
            $('#card-body-AddressCard').html(btn);
            return false;
        }
        
        const AddressData = LoadDataPageFunc.CurrentSelectedAddressOBJ();

        const SelectaddressHTML = `<h6>${AddressData.name}</h6>
                                <h6>${AddressData.address}</h6>
                                <h6>${AddressData.contactname}</h6>
                                <h6>${AddressData.contactnumber}</h6>`;
        $('#card-body-AddressCard').html(SelectaddressHTML + btn);

        //FInd Default Address based on LoadDataPageFunc.CurrentSelectedAddress if false find in obj

    };

    LoadDataPageFunc.fetchAddresses = function (sucessfunc = false) {
        let fetchAddressesNow = new RequestData(false);

        fetchAddressesNow.fromVarCache(false).data(null).url('/User/My/Get/Addresses/data').type('POST')
            .success((response) => {

                LoadDataPageFunc.AddressDetails = response;
                if (typeof sucessfunc === 'function') {
                    sucessfunc(response);
                }

            }).go();

    };



    LoadDataPageFunc.PopulateDetails = function () {

        let description;
        let photosarray;

        let reqqW = new RequestData(false);



        reqqW.fromVarCache(false).data({ cart: currenttarget }).url(`/User/My/Cart/Compute/data/`).type('POST')
            .success((response) => {
                LoadDataPageFunc.BuyDetails = response;
                LoadDataPageFunc.PopulateDetailsNow(response);
            }).go();

        LoadDataPageFunc.fetchAddresses((response) => { LoadDataPageFunc.UpdateAddressCard(response); });




    };



    LoadDataPageFunc.ProductNotAvailable = function () {
        const modalfooter = `
            <button class="btn" onclick="Backkey();">Back</button>
            <button class="btn" onclick="ButtonGo('ListProductsMarket')">All Products</button>
            `;
        CreateAndShowModal('modal-buyconfirm-productunavailable', false, 'Product Not Available', modalfooter, false);
        $('#modal-buyconfirm-productunavailable').on('hidden.bs.modal', function () {
            LoadDataPageFunc.Settings.ProductNotAvailableModalDismissed = true;
            ButtonGo('ListProductsMarket');
        });
    };

    LoadDataPageFunc.Main = function () {
        //   if (!currenttarget  ||  currenttarget==='0'){   LoadDataPageFunc.ProductNotAvailable();return false;}
        changeTopbarTitle(LoadDataPageFunc.PageTitle);
        LoadDataPageFunc.PopulateDetails();
    };



    LoadDataPageFunc.Main();
</script>