<div id="EditStoreForm">



</div>
<script>storeUnavailabe = false;</script>
@php
    use App\Http\Controllers\UserManagement\CreateUserControllerUltimate;
@endphp



<script>

    InitDataPageFuncOBJ();
    LoadDataPageFunc = {};
    LoadDataPageFunc.URLs = {};
    LoadDataPageFunc.URLs.EditUrl = `/Store/Edit`;
    LoadDataPageFunc.URLs.CategoryDatalist = `/Store/New/Category/Datalist`;
    // LoadDataPageFunc.URLs.SubCategoryDatalist = `/Products/New/SubCategory/Datalist`;
    LoadDataPageFunc.URLs.PhotoUpload = `/File/Upload/Store`;

    LoadDataPageFunc.PageTitle = 'Edit Store';

    LoadDataPageFunc.ids = {};
    LoadDataPageFunc.ids.photodropzone = 'NewStorePhotos';
    LoadDataPageFunc.formclass = 'NewStoreMarket';


    try {
        StoreData = @json($current_data);
    } catch (error) {
        StoreData = {};
    }






    LoadDataPageFunc.LoadUI = function () {
        let finalhtml = '';
        const formclass = LoadDataPageFunc.formclass;
        const textbox = function (placeholder, label, id, required = false, datalist = '', textvalue = '') {
            return UIInputGroup(placeholder, 'text', id, label, formclass, spanclass = '', imginsteadofspan = '', required, textvalue, datalist, imgwidth = '', imgheight = '');
        };
        const name = textbox('Store Name', 'Name', 'name', true, '', StoreData.name);
        const description = UIInputGroupTEXTAREA(label = 'Description', 'description', required = true, textareacontent = StoreData.description, formclass);
        const category = textbox('Product Category', 'Category', 'category', true, 'NewStoreCategoryDataList', StoreData.category);
        const address = UIInputGroupTEXTAREA(label = 'Address', 'address', required = true, textareacontent = StoreData.address, formclass);
        const categorydatalist = ArraytoDatalist("NewStoreCategoryDataList", [], false) || '';
        const photoscontainer = UIInputGroupFileUploadDropzone(LoadDataPageFunc.ids.photodropzone, label = 'Photo', LoadDataPageFunc.URLs.PhotoUpload);
       

        //ADD Validator for Javascript Inputs to Prevent JS Code Injection on ALL

        const storeOwner = UIInputGroupSelect('owner', label = 'Store Owner', [['', 'Select User']], spanclass = '', imginsteadofspan = '', '', '', '', formclass);

        //TODO Add Support for storeManager and Cashier multiple accounts support

        const submitbutton = UIInputGroupButton('Submit', formclass, buttonid = '', onclick = 'LoadDataPageFunc.TryToSubmit();', buttonstyle = '');


        finalhtml = name + description + category + categorydatalist + address + photoscontainer + storeOwner + submitbutton;
        finalhtml = CreateCardSimple(false, finalhtml);

        document.getElementById('EditStoreForm').innerHTML = finalhtml;



        // QueryandReplaceDatalist("NewProductCategoryDataList", LoadDataPageFunc.URLs.CategoryDatalist, 'POST', datatosend = null, fromvarcache = true);
        // QueryandReplaceDatalist("NewProductSubCategoryDataList", LoadDataPageFunc.URLs.SubCategoryDatalist, 'POST', datatosend = null, fromvarcache = true);

        InitializeLoadDataPageFuncDropZonePhotoUpload(LoadDataPageFunc.URLs.PhotoUpload, LoadDataPageFunc.ids.photodropzone, ShowClearPhotoFUNC = '', clearphotosbuttonid = 'clearuploadbutton', acceptedfiles = '', maxsizeMB = 100);
        LoadDataPageFunc.InitializePhotoDropZone();

        // LoadDataPageFunc.UpdateSubCategoryDatalistasTyped();
        QueryandReplaceDatalist("NewStoreCategoryDataList", LoadDataPageFunc.URLs.CategoryDatalist, 'POST', null, fromvarcache = true);

        currentDropzone[LoadDataPageFunc.ids.photodropzone].functions.ReplaceDropzoneFiles(StorePhotosDropzone);

    };


    LoadDataPageFunc.RepopulateStoreOwnerList = function () {

        function UpdateSelectParentList(response) {
            const selectElement = $("#owner");

            response.forEach(element => {

                $("<option></option>")
                    .val(element.hashkey)
                    .text(`${element.name} (${element.mobile_number}) [${element.username}] ${element.fullname ?? ''}`)
                    .appendTo(selectElement);
            });
            selectElement.val(StoreData.owner_hashkey || 0);
        }

        @if ($FragmentOnly)
            AjaxDo('/admin/user/list/numbers/hash', {}, UpdateSelectParentList, null, reqtype = 'POST');
        @else
            let userdata = @json(CreateUserControllerUltimate::listAllUsersforParentSelectHTML(true));
            UpdateSelectParentList(userdata);
        @endif

    };


    LoadDataPageFunc.TryToSubmit = function () {

        const currentformdata = LoadDataPageFunc.ValidateForm();

        if (!currentformdata) {
            ModalQuickDismiss('Error', 'Name, Description, Category and Address are required fields.', modalid = '', modaltohide = '', functiontodo = '', conditiontrue = true, modalfooter = '');
            return false;
        }

        const errorModal = function (errorstring = '') {
            ModalQuickDismiss('Error', 'Unable Update Store. <br>' + errorstring, modalid = '', modaltohide = '', functiontodo = '', conditiontrue = true, modalfooter = '');
        };

        const successModal = function () {
            hideallmodals();
            ModalQuickDismiss('Success', 'New Store Updated');
        };

        const submitsuccess = function (response) {

            if (typeof response.success !== 'undefined' && response.success === true) {
                Preloaders.ViewStoreinMarket(currenttarget, false, function (response) {
                    successModal();
                    gotoPage('ViewStoreMarket', currenttarget);
                });

            } else {
                errorModal(response.message || 'An error occurred while updating the store.');
            }


            // responseOk = isResponseAHash(response);
            // if (!responseOk) {
            //     errorModal(response);
            //     return false;
            // }
            // if (responseOk) {
            //     // Preloaders.ViewProductinMarket(response);
            //     successModal();
            //     gotoPage('ViewStoreMarket', response);
            //     return true;
            // }

        };

        SendPostDataFormwithTARGETUPLOADEDFILES(LoadDataPageFunc.URLs.EditUrl, LoadDataPageFunc.formclass, submitsuccess);

    };


    LoadDataPageFunc.ValidateForm = function () {
        return validateInputForm(['name', 'description', 'address', 'category']);

        const isAnyoftheRequiredEmpty = !inputsArray['NewProductName'] || !inputsArray['NewProductDescription'] || !inputsArray['NewProductCategory'] || !inputsArray['NewProductSubCategory'] ||
            !inputsArray['NewProductPrice'] || !inputsArray['NewProductAvailable'] || !inputsArray['NewProductUnitName'] || Target_Uploaded_Files.length === 0;





        if (isAnyoftheRequiredEmpty || isBarcodeNumeric === false) {
            return false;
        }

        const IsBarcodeValid = IsStringBarcode12Digits(inputsArray['NewProductBarcode']);


        return true;
    };


    LoadDataPageFunc.AssignVariablesandLoadUI = function () {
        try {
            StorePhotosDropzone = StoreData.photourlDropzone;
        } catch (error) {
            StorePhotosDropzone = [];
        }
        try {
            ParentList = StoreData.ParentList; // TODO ParentListisNotUsed
        } catch (error) {
            ParentList = false;
        }
        LoadDataPageFunc.LoadUI();
        LoadDataPageFunc.RepopulateStoreOwnerList();
    };

    LoadDataPageFunc.FetchStoreData = function () {
        if (typeof StoreData.name !== 'undefined') {
            LoadDataPageFunc.AssignVariablesandLoadUI();
            return;
        }
        let Req = new RequestData(false);
        Req.url('/Edit/Store/Details/data').type('POST').fromVarCache(false).data({ target: currenttarget })
            .success((response) => {
                StoreData = response;
                LoadDataPageFunc.AssignVariablesandLoadUI();
            }).go();
    };



    LoadDataPageFunc.Main = function () {


        LoadDataPageFunc.FetchStoreData();

        changeTopbarTitle(LoadDataPageFunc.PageTitle);



    };

    LoadDataPageFunc.Main();

</script>