<div id="NewProductForm">

</div>



<script>

    InitDataPageFuncOBJ();
    LoadDataPageFunc = {};
    LoadDataPageFunc.URLs = {};
    LoadDataPageFunc.URLs.NewUrl = `{{ route('admin.products.new',[],false) }}`;
    LoadDataPageFunc.URLs.CategoryDatalist = `/Products/New/Category/Datalist`;
    LoadDataPageFunc.URLs.SubCategoryDatalist = `/Products/New/SubCategory/Datalist`;
    LoadDataPageFunc.URLs.PhotoUpload = `/File/Upload/Product`;

    LoadDataPageFunc.PageTitle = 'New Product';

    LoadDataPageFunc.ids = {};
    LoadDataPageFunc.ids.photodropzone = 'NewProductPhotos';
    LoadDataPageFunc.formclass = 'NewProductMarket';

    LoadDataPageFunc.UpdateSubCategoryDatalistasTyped = function () {

        document.getElementById("NewProductCategory").addEventListener("change", function (event) {
            const inputValue = event.target.value;
            const categoryinputvalue = document.getElementById("NewProductCategory").value;
            QueryandReplaceDatalist("NewProductSubCategoryDataList",
                LoadDataPageFunc.URLs.SubCategoryDatalist,
                'POST', { category: categoryinputvalue }, fromvarcache = true,
                function (response) {



                });
        });
    };


    LoadDataPageFunc.LoadUI = function () {
        let finalhtml = '';
        const formclass = LoadDataPageFunc.formclass;
        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('Product Name', 'Name', 'ProductName', true);
        const description = UIInputGroupTEXTAREA(label = 'Description', 'NewProductDescription', required = true, textareacontent = '', formclass);
        const category = textbox('Product Category', 'Category', 'ProductCategory', true, 'NewProductCategoryDataList');

        const categorydatalistData = @json((new App\Http\Controllers\Market\ProductController)->getCategories(false))

        const categorydatalist = ArraytoDatalist("NewProductCategoryDataList", categorydatalistData, false) || '';
        const subcategory = textbox('Product Subcategory', 'Subcategory', 'ProductSubCategory', true, 'NewProductSubCategoryDataList');


        const subcategorydatalist = ArraytoDatalist("NewProductSubCategoryDataList", [], false) || '';
        const photoscontainer = UIInputGroupFileUploadDropzone(LoadDataPageFunc.ids.photodropzone, label = 'Photo', LoadDataPageFunc.URLs.PhotoUpload);
        const price = UIInputGroupNumber('Price in Philippine Pesos', 'NewProductPrice', 'Price', formclass, 1, max = '', spanclass = '', imginsteadofspan = '', required = true, val = 1, datalist = '', imgwidth = '', imgheight = '');
        const unit = textbox('ex 25kg', 'Unit', 'ProductUnitName', true);
        const available = UIInputGroupNumber('Available Stock', 'NewProductAvailable', 'No of Stock', formclass, 1, max = '', spanclass = '', imginsteadofspan = '', required = true, val = 1, datalist = '', imgwidth = '', imgheight = '');
        let barcode = textbox('12 Digits Barcode Number', 'Barcode', 'ProductBarcode', false);
        barcode = $('<div>' + barcode + '</div>');
        barcodeinput = barcode.find('input');
        barcodeinput.attr('maxlength', 12).attr('pattern', '[0-9]*').on('input', function () {
            this.value = this.value.replace(/[^0-9]/g, '');
        });
        barcode = barcode.html();

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

        finalhtml = name + description + category + categorydatalist + subcategory + subcategorydatalist + photoscontainer + price + unit + available + barcode + submitbutton;
        finalhtml = CreateCardSimple(false, finalhtml);

        document.getElementById('NewProductForm').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();

    };


    LoadDataPageFunc.TryToSubmit = function () {

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

        const successModal = function () {
            hideallmodals();
            ModalQuickDismiss('Success', 'New Product Submitted');
        };

        const submitsuccess = function (response) {

            getResponseHashkeyOrErrorMessage(response, function (hashkey) {
                Preloaders.ViewProductinMarket(hashkey);
                successModal();
                gotoPage('BuyViewProductMarket', hashkey);
                return true;
            }, errorModal);

        };

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

    };


    LoadDataPageFunc.ValidateForm = function () {
        let inputsArray = getInputElementsValuesObjectbyCSSClassname(LoadDataPageFunc.formclass);
        if (isObjectEmpty(inputsArray)) { return false; }

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

        const isBarcodeNumeric = inputsArray['NewProductBarcode'] && isNumeric(inputsArray['NewProductBarcode']);

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

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


        return true;
    };



    LoadDataPageFunc.Main = function () {
        // if (!currenttarget || currenttarget === '0') {
        //     const modalbody = 'Unable to Load Store Details.';
        //     const modalfooter = buttonGOTOPage('Home', 'Home', 0, '', 'hideallmodals();');;
        //     ModalQuickDismiss(false, modalbody, modalid = '', modaltohide = '', functiontodo = '', conditiontrue = true, modalfooter);
        //     Backkey();
        //     return false;
        // }

        LoadDataPageFunc.LoadUI();
        changeTopbarTitle(LoadDataPageFunc.PageTitle);

    };

    LoadDataPageFunc.Main();


</script>