<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_Marketplace
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */

/** @var $block \Webkul\Marketplace\Block\Product\Create */

$helper = $this->helper(\Webkul\Marketplace\Helper\Data::class);
$product_hint_status = $helper->getProductHintStatus();
$currency_code = $helper->getCurrentCurrencyCode();
$currency_symbol = $helper->getCurrencySymbol();
$set=$this->getRequest()->getParam('set');
$type=$this->getRequest()->getParam('type');
$skuType = $helper->getSkuType();
$skuPrefix = $helper->getSkuPrefix();
$data = $block->getPersistentData();
$weightUnit = $helper->getWeightUnit();
if (!empty($data['set'])) {
    $set = $data['set'];
}
?>
<form action="<?= $block->escapeUrl($block->getUrl('marketplace/product/save', ['_secure' => $this->getRequest()->isSecure()])) ?>" enctype="multipart/form-data" method="post" id="edit-product" data-form="edit-product" data-mage-init='{"validation":{}}'>
    <div class="wk-mp-design" id="wk-bodymain">
        <fieldset class="fieldset info wk-mp-fieldset">
            <div data-mage-init='{"formButtonAction": {}}' class="wk-mp-page-title legend">
                <span><?= $block->escapeHtml(__('Add Product')) ?></span>
                <button class="button wk-mp-btn" title="<?= $block->escapeHtml(__('Save')) ?>" type="submit" id="save-btn">
                    <span><span><?= $block->escapeHtml(__('Save')) ?></span></span>
                </button>
                <button class="button wk-mp-btn" title="<?= $block->escapeHtml(__('Save & Duplicate')) ?>" type="button" id="wk-mp-save-duplicate-btn">
                    <span><span><?= $block->escapeHtml(__('Save & Duplicate')) ?></span></span>
                </button>
            </div>
            <?= $block->getBlockHtml('formkey')?>
            <?= $block->getBlockHtml('seller.formkey')?>
            <input id="product_type_id" name="type" type="hidden" value="<?= $block->escapeHtml($type)?>" value="<?= $block->escapeHtml($data['type'])?>">
            <?php if (count($helper->getAllowedSets()) > 1): ?>
                <div class="field required">
                    <label class="label"><?= $block->escapeHtml(__('Attribute Set')) ?>:</label>
                    <div class="control">
                        <select name="set" id="attribute-set-id" class="required-entry">
                        <?php foreach ($helper->getAllowedSets() as $setval): ?>
                            <option value="<?= $block->escapeHtml($setval['value']) ?>" <?php if ($set==$setval['value']) { ?> selected="selected" <?php } ?>>
                                <?= $block->escapeHtml($setval['label'])?>
                            </option>
                        <?php endforeach; ?>
                        </select>
                    </div>
                </div>
            <?php else: ?>
                <?php $allowedSets = $helper->getAllowedSets(); ?>
                <input type="hidden" name="set" id="attribute-set-id" value="<?= $block->escapeHtml($allowedSets[0]['value']) ?>" />
            <?php endif; ?>

            <div class="field">
                <label class="label"><?= $block->escapeHtml(__('Product Category')) ?>:</label>
                <?php if ($product_hint_status && $helper->getProductHintCategory()): ?>
                    <img src="<?= $block->escapeUrl($this->getViewFileUrl('Webkul_Marketplace::images/quest.png')); ?>" class='questimg' title="<?= $block->escapeHtml($helper->getProductHintCategory()) ?>"/>
                <?php endif; ?>
                <?php if ($helper->getIsAdminViewCategoryTree()) { ?>
                    <div data-bind="scope: 'sellerCategory'">
                        <!-- ko template: getTemplate() --><!-- /ko -->
                    </div>
                    <script type="text/x-magento-init">
                        {
                            "*": {
                                "Magento_Ui/js/core/app": {
                                    "components": {
                                        "sellerCategory": {
                                            "component": "Webkul_Marketplace/js/product/seller-category-tree",
                                            "template" : "Webkul_Marketplace/seller-category-tree",
                                            "filterOptions": true,
                                            "levelsVisibility": "1",
                                            "options": <?= /* @noEscape */ $block->getCategoriesTree()?>,
                                            "value": <?= /* @noEscape */ json_encode($data['product']['category_ids'])?>
                                        }
                                    }
                                }
                            }
                        }
                    </script>
                <?php } else { ?>
                    <div class="wk-field wk-category">
                        <div class="wk-for-validation">
                            <div id="wk-category-label"><?= $block->escapeHtml(__("CATEGORIES")); ?></div>
                            <?php
                            $categories = $data['product']['category_ids'];
                            foreach ($categories as $value) { ?>
                                <input type="hidden" name="product[category_ids][]" value="<?= $block->escapeHtml($value); ?>" id="wk-cat-hide<?= $block->escapeHtml($value); ?>"/>
                            <?php } ?>
                            <?php
                            if ($helper->getAllowedCategoryIds()) {
                                $storeconfig_catids = explode(',', trim($helper->getAllowedCategoryIds()));
                                foreach ($storeconfig_catids as $storeconfig_catid) {
                                    $cat_model = $block->getCategory()->load($storeconfig_catid);
                                    if (isset($cat_model["entity_id"]) && $cat_model["entity_id"]) {
                                        ?>
                                        <div class="wk-cat-container">
                                            </span><span class="wk-foldersign"></span>
                                            <span class="wk-elements wk-cat-name"><?= $block->escapeHtml($cat_model->getName()) ?></span>
                                            <?php
                                            if (in_array($cat_model["entity_id"], $categories)) {?>
                                                <input class="wk-elements" type="checkbox" name="product[category_ids][]" value=<?= $block->escapeHtml($cat_model['entity_id']) ?> checked />
                                                <?php
                                            } else { ?>
                                                <input class="wk-elements" type="checkbox" name="product[category_ids][]" value='<?= $block->escapeHtml($cat_model['entity_id']) ?>'/>
                                                <?php
                                            } ?>
                                        </div>
                                        <?php
                                    }
                                }
                            } else {
                                $count = 0;
                                $category_helper = $this->helper(\Magento\Catalog\Helper\Category::class);
                                $category_model = $block->getCategory();
                                $_categories = $category_helper->getStoreCategories();
                                foreach ($_categories as $_category) {
                                    $count++;
                                    if (count($category_model->getAllChildren($category_model->load($_category['entity_id'])))-1 > 0) { ?>
                                        <div class="wk-cat-container" style="margin-left:0px;">
                                            <span class="wk-plus">
                                            </span><span class="wk-foldersign"></span>
                                            <span class="wk-elements wk-cat-name"><?= $block->escapeHtml($_category->getName()) ?></span>
                                            <?php
                                            if (in_array($_category["entity_id"], $categories)) {?>
                                                <input class="wk-elements" type="checkbox" name="product[category_ids][]" value=<?= $block->escapeHtml($_category['entity_id']) ?> checked />
                                                <?php
                                            } else { ?>
                                                <input class="wk-elements" type="checkbox" name="product[category_ids][]" value='<?= $block->escapeHtml($_category['entity_id']) ?>'/>
                                                <?php
                                            } ?>
                                        </div>
                                        <?php
                                    } else { ?>
                                        <div class="wk-cat-container">
                                            </span><span class="wk-foldersign"></span>
                                            <span class="wk-elements wk-cat-name"><?= $block->escapeHtml($_category->getName()) ?></span>
                                            <?php
                                            if (in_array($_category["entity_id"], $categories)) {?>
                                                <input class="wk-elements" type="checkbox" name="product[category_ids][]" value=<?= $block->escapeHtml($_category['entity_id']) ?> checked />
                                                <?php
                                            } else { ?>
                                                <input class="wk-elements" type="checkbox" name="product[category_ids][]" value='<?= $block->escapeHtml($_category['entity_id']) ?>'/>
                                                <?php
                                            } ?>
                                        </div>
                                        <?php
                                    }
                                }
                            } ?>
                        </div>
                    </div>
                <?php } ?>
            </div>
            <div class="field required">
                <label class="label"><?= $block->escapeHtml(__('Product Name')) ?>:</label>
                <?php
                if ($product_hint_status && $helper->getProductHintName()) {?>
                    <img src="<?= $block->escapeUrl($this->getViewFileUrl('Webkul_Marketplace::images/quest.png')); ?>" class='questimg' title="<?= $block->escapeHtml($helper->getProductHintName()) ?>"/>
                    <?php
                } ?>
                <div class="control">
                    <input type="text" class="required-entry input-text" name="product[name]" id="name" value="<?= $block->escapeHtml($data['product']['name'])?>"/>
                </div>
            </div>
            <div class="field required">
                <label class="label"><?= $block->escapeHtml(__('Description')) ?>:</label>
                <?php
                if ($product_hint_status && $helper->getProductHintDesc()) {?>
                    <img src="<?= $block->escapeUrl($this->getViewFileUrl('Webkul_Marketplace::images/quest.png')); ?>" class='questimg' title="<?=  $block->escapeHtml($helper->getProductHintDesc()) ?>"/>
                    <?php
                } ?>
                <div class="control wk-border-box-sizing">
                    <textarea name="product[description]" class="required-entry input-text" id="description" rows="5" cols="75" ><?= /* @noEscape */  $data['product']['description']?></textarea>
                    <?php if ($helper->isWysiwygEnabled()): ?>
                        <script>
                            require([
                                "jquery",
                                "mage/translate",
                                "mage/adminhtml/events",
                                "mage/adminhtml/wysiwyg/tiny_mce/setup"
                            ], function(jQuery) {
                                wysiwygDescription = new wysiwygSetup("description", {
                                    "width" : "100%",
                                    "height" : "200px",
                                    "plugins" : [{"name":"image"}],
                                    "tinymce4" : {
                                        "toolbar":"formatselect | bold italic underline | alignleft aligncenter alignright | bullist numlist | link table charmap","plugins":"advlist autolink lists link charmap media noneditable table contextmenu paste code help table",
                                    }
                                });
                                wysiwygDescription.setup("exact");
                            });
                        </script>
                    <?php endif; ?>
                </div>
            </div>

            <div class="field">
                <label class="label"><?= $block->escapeHtml(__('Short Description')) ?>:</label>
                <?php if ($product_hint_status && $helper->getProductHintShortDesc()) { ?>
                    <img src="<?= $block->escapeUrl($this->getViewFileUrl('Webkul_Marketplace::images/quest.png')); ?>" class='questimg' title="<?= $block->escapeHtml($helper->getProductHintShortDesc()) ?>"/>
                <?php } ?>
                <div class="control wk-border-box-sizing">
                    <textarea name="product[short_description]" class="input-text" id="short_description" rows="5" cols="75" ><?= /* @noEscape */ $data['product']['short_description']?></textarea>
                    <?php if ($helper->isWysiwygEnabled()): ?>
                        <script>
                            require([
                                "jquery",
                                "mage/translate",
                                "mage/adminhtml/events",
                                "mage/adminhtml/wysiwyg/tiny_mce/setup"
                            ], function(jQuery) {
                                wysiwygShortDescription = new wysiwygSetup("short_description", {
                                    "width" : "100%",
                                    "height" : "200px",
                                    "plugins" : [{"name":"image"}],
                                    "tinymce4" : {
                                        "toolbar":"formatselect | bold italic underline | alignleft aligncenter alignright | bullist numlist | link table charmap","plugins":"advlist autolink lists link charmap media noneditable table contextmenu paste code help table",
                                    }
                                });
                                wysiwygShortDescription.setup("exact");
                            });
                        </script>
                    <?php endif; ?>
                </div>
            </div>
            <?php if ($skuType == 'static'): ?>
                <div class="field required">
                    <label class="label"><?= $block->escapeHtml(__('SKU')) ?>:</label>
                    <?php
                    if ($skuPrefix) {
                        /* @noEscape */ echo "(Prefix - ".$skuPrefix.")";
                    }
                    ?>
                    <?php if ($product_hint_status && $helper->getProductHintSku()): ?>
                        <img src="<?= $block->escapeUrl($this->getViewFileUrl('Webkul_Marketplace::images/quest.png')); ?>" class='questimg' title="<?= $block->escapeHtml($helper->getProductHintSku()) ?>"/>
                    <?php endif; ?>
                    <div class="control">
                        <input name="product[sku]" id="sku" class="required-entry input-text" type="text" value="<?= $block->escapeHtml($data['product']['sku'])?>"/>
                    </div>
                    <div id="skuavail" >
                        <span class="success-msg skuavailable"><?= $block->escapeHtml(__('SKU Available')) ?></span>
                    </div>
                    <div id="skunotavail" >
                        <span class="error-msg skunotavailable"><?= $block->escapeHtml(__('SKU Already Exist')) ?></span>
                    </div>
                </div>
            <?php endif; ?>
            <div class="field required">
                <label class="label"><?= $block->escapeHtml(__('Price')) ?><b><?= /* @noEscape */ " (".$currency_symbol.")"; ?></b>:</label>
                <?php if ($product_hint_status && $helper->getProductHintPrice()): ?>
                    <img src="<?= $block->escapeUrl($this->getViewFileUrl('Webkul_Marketplace::images/quest.png')); ?>" class='questimg' title="<?= $block->escapeHtml($helper->getProductHintPrice()) ?>"/>
                <?php endif; ?>
                <div class="control">
                    <input type="text" class="required-entry validate-zero-or-greater input-text" name="product[price]" id="price" value="<?= /* @noEscape */ $data['product']['price']?>"/>
                </div>
            </div>
            <div class="field">
                <label class="label"><?= $block->escapeHtml(__('Special Price')) ?><b><?= /* @noEscape */ " (".$currency_symbol.")"; ?></b>:</label>
                <?php if ($product_hint_status && $helper->getProductHintSpecialPrice()): ?>
                    <img src="<?= $block->escapeUrl($this->getViewFileUrl('Webkul_Marketplace::images/quest.png')); ?>" class='questimg' title="<?= $block->escapeHtml($helper->getProductHintSpecialPrice()) ?>"/>
                <?php endif; ?>
                <div class="control">
                    <input type="text" class="widthinput input-text validate-zero-or-greater" name="product[special_price]" id="special-price" value="<?= /* @noEscape */ $data['product']['special_price']?>"/>
                </div>
            </div>
            <div class="field">
                <label class="label"><?= $block->escapeHtml(__('Special Price From')) ?>:</label>
                <?php if ($product_hint_status && $helper->getProductHintStartDate()): ?>
                    <img src="<?= $block->escapeUrl($this->getViewFileUrl('Webkul_Marketplace::images/quest.png')); ?>" class='questimg' title="<?= $block->escapeHtml($helper->getProductHintStartDate()) ?>"/>
                <?php endif; ?>
                <div class="control">
                    <input type="text" name="product[special_from_date]" id="special-from-date" class="input-text" value="<?= /* @noEscape */ $data['product']['special_from_date']?>"/>
                </div>
            </div>
            <div class="field">
                <label class="label"><?= $block->escapeHtml(__('Special Price To')) ?>:</label>
                <?php if ($product_hint_status && $helper->getProductHintEndDate()): ?>
                    <img src="<?= $block->escapeUrl($this->getViewFileUrl('Webkul_Marketplace::images/quest.png')); ?>" class='questimg' title="<?= $block->escapeHtml($helper->getProductHintEndDate()) ?>"/>
                <?php endif; ?>
                <div class="control">
                    <input type="text" name="product[special_to_date]" id="special-to-date" class="input-text" value="<?= /* @noEscape */ $data['product']['special_to_date']?>"/>
                </div>
            </div>
            <input id="inventory_manage_stock" type="hidden" name="product[stock_data][manage_stock]" value="1">
            <input type="hidden" value="1" name="product[stock_data][use_config_manage_stock]" id="inventory_use_config_manage_stock">
            <div class="field required">
                <label class="label"><?= $block->escapeHtml(__('Stock')) ?>:</label>
                <?php if ($product_hint_status && $helper->getProductHintQty()): ?>
                    <img src="<?= $block->escapeUrl($this->getViewFileUrl('Webkul_Marketplace::images/quest.png')); ?>" class='questimg' title="<?= $block->escapeHtml($helper->getProductHintQty()) ?>"/>
                <?php endif; ?>
                <div class="control">
                    <input type="text" class="required-entry validate-number input-text" name="product[quantity_and_stock_status][qty]" id="qty" value="<?= /* @noEscape */ $data['product']['quantity_and_stock_status']['qty']?>"/>
                </div>
            </div>
            <div class="field required">
                <label class="label"><?= $block->escapeHtml(__('Stock Availability')) ?>:</label>
                <?php if ($product_hint_status && $helper->getProductHintStock()): ?>
                    <img src="<?= $block->escapeUrl($this->getViewFileUrl('Webkul_Marketplace::images/quest.png')); ?>" class='questimg' title="<?= $block->escapeHtml($helper->getProductHintStock()) ?>"/>
                <?php endif; ?>
                <div class="control">
                    <select id="" class="select" name="product[quantity_and_stock_status][is_in_stock]">
                        <option value="1" <?php if ($data['product']['quantity_and_stock_status']['is_in_stock'] == 1) { echo "selected='selected'";}?>><?= $block->escapeHtml(__("In Stock")); ?></option>
                        <option value="0" <?php if ($data['product']['quantity_and_stock_status']['is_in_stock'] == 0) { echo "selected='selected'";}?>><?= $block->escapeHtml(__("Out of Stock")); ?></option>
                    </select>
                </div>
            </div>
            <div class="field required">
                <label class="label"><?= $block->escapeHtml(__('Visibility')) ?>:</label>
                <div class="control">
                    <select id="visibility" class=" required-entry required-entry select" name="product[visibility]">
                        <option value=""><?= $block->escapeHtml(__('Please Select'))?></option>
                        <?php $product_visibility = $helper->getVisibilityOptionArray(); ?>
                        <?php foreach ($product_visibility as $key => $value): ?>
                            <option value="<?= /* @noEscape */ $key ?>" <?php if ($key==$data['product']['visibility']) { echo "selected='selected'";}?>><?=  /* @noEscape */ $value?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="field required">
                <label class="label"><?= $block->escapeHtml(__('Tax Class')) ?>:</label>
                <?php if ($product_hint_status && $helper->getProductHintTax()): ?>
                    <img src="<?= $block->escapeUrl($this->getViewFileUrl('Webkul_Marketplace::images/quest.png')); ?>" class='questimg' title="<?= $block->escapeHtml($helper->getProductHintTax()) ?>"/>
                <?php endif; ?>
                <div class="control">
                    <select id="tax-class-id" class=" required-entry required-entry select" name="product[tax_class_id]">
                        <option value="0"><?= $block->escapeHtml(__('None'))?></option>
                        <?php $taxes = $helper->getTaxClassModel(); ?>
                        <?php foreach ($taxes as $tax): ?>
                            <option value="<?= $block->escapeHtml($tax->getId()) ?>" <?php if ($tax->getId()==$data['product']['tax_class_id']) { echo "selected='selected'";}?>><?= $block->escapeHtml($tax->getClassName())?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="field required">
                <label class="label"><?= $block->escapeHtml(__('Weight')) ?> (<?= $block->escapeHtml($weightUnit)?>):</label>
                <?php if ($product_hint_status && $helper->getProductHintWeight()): ?>
                    <img src="<?= $block->escapeUrl($this->getViewFileUrl('Webkul_Marketplace::images/quest.png')); ?>" class='questimg' title="<?= $block->escapeHtml($helper->getProductHintWeight()) ?>"/>
                <?php endif; ?>
                <div data-role="weight-switcher">
                    <label data-ui-id="product-tabs-attributes-tab-element-radios-product-product-has-weight-label" for="weight-switcher">
                        <span><?= $block->escapeHtml(__('Does this have a weight?'))?></span>
                    </label>
                    <div class="control">
                        <div class="control">
                            <input type="radio" <?php if ($type!='virtual' || $type!='downloadable' || $data['product']['product_has_weight']==1) { ?> checked="checked" <?php } ?> class="weight-switcher" id="weight-switcher1" value="1" name="product[product_has_weight]">
                            <label for="weight-switcher1">
                                <span><?= $block->escapeHtml(__('Yes'))?></span>
                            </label>
                        </div>
                        <div class="control">
                            <input type="radio" class="weight-switcher" id="weight-switcher0" value="0" name="product[product_has_weight]" <?php if ($type=='virtual' || $type=='downloadable' || $data['product']['product_has_weight']==0) { ?> checked="checked" <?php } ?>>
                            <label for="weight-switcher0">
                                <span><?= $block->escapeHtml(__('No'))?></span>
                            </label>
                        </div>
                    </div>
                </div>
                <div class="control">
                    <input type="text" class="validate-zero-or-greater input-text" name="product[weight]" id="weight" value="<?= /* @noEscape */ $data['product']['weight']?>"/>
                </div>
            </div>
            <div class="field">
                <label class="label"><?= $block->escapeHtml(__('Meta Title')) ?>:</label>
                <div class="control">
                    <input type="text" class="input-text" name="product[meta_title]" id="meta_title"  value="<?= /* @noEscape */ $data['product']['meta_title']?>"/>
                </div>
            </div>
            <div class="field">
                <label class="label"><?= $block->escapeHtml(__('Meta Keywords')) ?>:</label>
                <div class="control">
                    <textarea class="textarea" id="meta_keyword" name="product[meta_keyword]"><?= /* @noEscape */ $data['product']['meta_keyword']?></textarea>
                </div>
            </div>
            <div class="field">
                <label class="label"><?= $block->escapeHtml(__('Meta Description')) ?>:</label>
                <div class="control">
                    <textarea class="textarea" id="meta_description" name="product[meta_description]"><?= /* @noEscape */ $data['product']['meta_description']?></textarea>
                </div>
            </div>
            <?= $block->getChildHtml(); ?>
        </fieldset>
    </div>
</form>
<?php
$formData = [
    'countryPicSelector' => '#country-pic',
    'verifySkuAjaxUrl' => $block->getUrl('marketplace/product/verifysku', ['_secure' => $this->getRequest()->isSecure()]),
    'categoryTreeAjaxUrl' => $block->getUrl('marketplace/product/categorytree/', ['_secure' => $this->getRequest()->isSecure()])
];
$serializedFormData = $this->helper(\Magento\Framework\Json\Helper\Data::class)->jsonEncode($formData);
?>

<script type="text/x-magento-init">
    {
        "*": {
            "sellerAddProduct": <?= /* @noEscape */ $serializedFormData; ?>
        }
    }
</script>
<script type='text/javascript'>
    require(['jquery', 'prototype', 'domReady!'], function($) {
        var qty = $('#qty'),
            productType = $('#product_type_id').val(),
            stockAvailabilityField = $('#quantity_and_stock_status'),
            manageStockField = $('#inventory_manage_stock'),
            useConfigManageStockField = $('#inventory_use_config_manage_stock'),
            fieldsAssociations = {
                'qty': 'inventory_qty',
                'quantity_and_stock_status': 'inventory_stock_availability'
            };

        var qtyDefaultValue = qty.val();
    })
</script>
<script>
    require([
        "jquery",
        "Webkul_Marketplace/catalog/type-events"
    ], function($, TypeSwitcher){
        var $form = $('[data-form=edit-product]');
        $form.data('typeSwitcher', TypeSwitcher.init());
    });
</script>
<script type="text/x-magento-init">
    {
        "*": {
            "Webkul_Marketplace/js/product/weight-handler": {},
            "Webkul_Marketplace/catalog/apply-to-type-switcher": {}
        }
    }
</script>
