<?php

use Mtc\Shop\Category;
use Mtc\Shop\Vat;
use Mtc\Shop\Warning;
use Illuminate\Database\Capsule\Manager as DB;
use MtcPharmacy\QualifyingAnswers\Classes\QualifyingAnswersHelper;
use MtcPharmacy\Bundles\Classes\BundleType;
use App\ProductInfo;
use Illuminate\Support\Facades\Event;
use MtcPharmacy\Multisite\Classes\MultisiteManager;
use MtcPharmacy\Multisite\Classes\MultisiteConstants;
use Mtc\Shop\Brand;


$path = '../../../';
require_once $path . 'core/includes/header.inc.php';

$item = new Item();
$errors = [];

$page_meta['title'] = 'Product Details';

if (!empty($_REQUEST['id'])) {
    $requested_item_id = (int)$_REQUEST['id'];
    $requested_item = \Mtc\Shop\Item::find($_REQUEST['id']);
    if ($requested_item) {
        $mm = new MultisiteManager($requested_item);
        $mm->ensureTheCorrectAdminPageLoaded();
    }

    $item->Get_Item($_REQUEST['id']);

    $item_eloquent = $item->eloquent();
} else {
    $item_eloquent = new \Mtc\Shop\Item();
}

$type = null;

$copy_id = null;
if (!empty($_REQUEST['type']) && $_REQUEST['type'] === 'similar') {
    if (!empty($_REQUEST['copy_id'])) {
        $copy_sizes = (new \Mtc\Shop\Item())->find($_REQUEST['copy_id'])->sizes;
    }
    $copy_id = $_REQUEST['id'];
    $_REQUEST['id'] = '';
}

init_request_values([
    'id' => null,
    'free_delivery' => null,
    'preorder' => null,
    'weight' => null,
    'bundle_page_url' => null,
    'form_id' => null,
    'warnings' => null,
    'id_check_required' => null,
]);


/**
 * Process
 */

$request_brand = isset($_REQUEST['brand']) ? $_REQUEST['brand'] : null;
$request_sex = isset($_REQUEST['sex']) ? $_REQUEST['sex'] : null;

if (!empty($_REQUEST['action']) && $_REQUEST['action'] === 'update') {

    if (empty($_REQUEST['name'])) {
        $errors['name'] = 'Please enter a name';
    }

    $item->epos_code = strip_tags($_REQUEST['code']);
    $item->brand = $request_brand;
    $item->name = strip_tags($_REQUEST['name']);
    $item->description = $_REQUEST['description'];
    $item->vat_rate = $_REQUEST['vat_rate'];
    $item->vat_deductable = $_REQUEST['vat_deductable'];
    $item->free_delivery = $_REQUEST['free_delivery'];
    $item->preorder = $_REQUEST['preorder'];
    $item->weight = $_REQUEST['weight'];
    $item->product_type = $_REQUEST['product_type'];
    $item->id_check_required = (bool)$_REQUEST['id_check_required'];
    $item->can_be_sold_separately = $_REQUEST['can_be_sold_separately'] ?? '0';
    $item->basket_quantity_locked = $_REQUEST['basket_quantity_locked'] ?? '0';
    $item->disable_assessment_forms = $_REQUEST['disable_assessment_forms'] ?? '0';
    $item->bundle_page_url = $_REQUEST['bundle_page_url'];
    $item->is_groupbuy_container = $_REQUEST['is_groupbuy_container'] ?? '0';
    $item->groupbuy_bundletype_id = $_REQUEST['groupbuy_bundletype_id'] ?? null;
    $item->form_id = $_REQUEST['form_id'];
    $item->restriction_period_length = filter_input(INPUT_POST, 'restriction_period_length');
    $item->restriction_per_period = filter_input(INPUT_POST, 'restriction_per_period');
    $item->restriction_per_order = filter_input(INPUT_POST, 'restriction_per_order');
    $item->restriction_limit_once = filter_input(INPUT_POST, 'restriction_limit_once') ?: 0;

    $item->seo_title = $_REQUEST['seo_title'];
    $item->seo_keywords = $_REQUEST['seo_keywords'];
    $item->seo_description = $_REQUEST['seo_description'];


    if (isset($_REQUEST['stock'])) {
        $item->stock = $_REQUEST['stock'];
    }

    if (empty($item->sizes) || empty($item->sizes[0]['id'])) {
        $item->price = $_REQUEST['price'];
        $item->sale_price = $_REQUEST['sale_price'];
        if ($item->vat_deductable) {
            $item->price_exvat = $item->price / (1 + $item->vat_rate / 100);
            $item->sale_price_exvat = $item->sale_price / (1 + $item->vat_rate / 100);
        } else {
            $item->price_exvat = $item->price;
            $item->sale_price_exvat = $item->sale_price;
        }

        if ($item->sale_price > 0) {
            $item->sort_price = $item->sale_price;
        } else {
            $item->sort_price = $item->price;
        }
    }

    $item->categories = [];

    for ($i = 0; $i < CATEGORIES_MAX; $i++) {
        if (empty($_REQUEST['category_' . $i])) {
            continue;
        }
        $item->categories[] = $_REQUEST['category_' . $i];
    }

    if (defined('DELIVERY_HEAVY') && DELIVERY_HEAVY == true) {
        if (!empty($_REQUEST['heavy'])) {
            $item->heavy = 1;
        } else {
            $item->heavy = 0;
        }
    }

    $item->hidden = 0;
    if ($_REQUEST['hidden'] != '0') {
        $item->hidden = 1;
    }

    $item->custom_field_set_id = $_REQUEST['custom_field_set_id'];
    if (! $item->custom_field_set_id) {
        $item->custom_field_set_id = CustomFieldsHelper::getDefaultSet();
    }

    if (is_array($_REQUEST['custom'])) {
        $item->custom = array_map(function ($custom_field) {
            return trim($custom_field);
        }, $_REQUEST['custom']);
    }

    if (!empty($_FILES['custom']['name'])) {
        foreach ($_FILES['custom']['name'] as $key => $image_field) {
            if (!empty($image_field)) {
                $item->custom[$key] = $image_field;
            }
        }
    }
    if (!empty($_REQUEST['delete_image'])) {
        foreach ($_REQUEST['delete_image'] as $delete_field => $delete_value) {
            $item->custom[$delete_field] = '';
        }
    }

    $custom_errors = CustomFieldsHelper::validateCustomFields($item->custom_field_set_id, $type, $item->custom);

    $errors = array_merge($errors, $custom_errors);

    if (sizeof($errors) == 0 && $_REQUEST['changesex'] == '') {
        $added = false;

        if (!empty($_REQUEST['id'])) {
            $item->id = clean_page($_REQUEST['id']);
            $item->Update_Item();
            $item->Update_Categories();

            if (!empty($item->brand)) {
                $item->Update_Brand();
            } else {
                \Illuminate\Support\Facades\DB::table('items_brands')->where('item_id', $item->id)->delete();
            }

            $item->Update_Hidden();
            $item->Update_Stock();

            $item->saveCustom();
            $item->saveCustomImages($item->custom_field_set_id, $type, $image_folders['custom_folders']);

            $mm->normaliseSlugs($item->custom['slug']);
            $mm->normaliseCategories($item_eloquent->categories->pluck('id')->toArray());
            $mm->normaliseBrands($item_eloquent->brands->pluck('id')->toArray());

        } else {
            $item->Insert_Item();
            $_REQUEST['id'] = $item->id;
            $item->Update_Categories();
            $item->Insert_Brand();
            $item->Update_Hidden();
            $item->Update_Stock();

            $item->saveCustom();
            $item->saveCustomImages($item->custom_field_set_id, $type, $image_folders['custom_folders']);

            $added = true;
            if (!empty($copy_sizes)) {
                foreach ($copy_sizes as $copy_size) {
                    $copy_item = (new \Mtc\Shop\Item())->find($item->id);
                    $copy_item->sizes()->create($copy_size->toArray());
                }
            }
        }

        \Mtc\Plugins\SeoSchema\Classes\SchemaItem::buildCache($item);
    }

    if (!empty($item->id)) {
        if (defined('ITEMS_KEYWORDS') && ITEMS_KEYWORDS === true) {
            if ($item_eloquent) {
                $item_eloquent = $item->eloquent();
            }
            // attach keywords that were entered
            $keywords = (new \Mtc\Core\Keywords\Keyword())->newCollection();
            foreach (explode(',', $_POST['keywords']) as $keyword) {
                try {
                    $keyword = \Mtc\Core\Keywords\Keyword::fromKeyword($keyword);
                } catch (Exception $e) {
                    $keyword = new \Mtc\Core\Keywords\Keyword(['keyword' => $keyword]);
                    $keyword->save();
                }
                $keywords->add($keyword);
            }
            $item_eloquent->keywords()->sync($keywords);

            $keywords->each(function ($keyword) use ($item_eloquent) {

                if (PorterStemmer::multi_stem($keyword->keyword)) {
                    $search_keyword = implode(' ', PorterStemmer::multi_stem($keyword->keyword));
                    \Illuminate\Support\Facades\DB::table('items_keywords')
                        ->where('item_id', $item_eloquent->id)
                        ->where('keyword_id', $keyword->id)
                        ->update([
                            'keyword' => $keyword->keyword,
                            'search_keyword' => $search_keyword
                        ]);
                }
            });
        }

        if (empty($item_eloquent)) {
            $item_eloquent = $item->eloquent();
        }
        $item_eloquent->warnings()->sync((array)$_REQUEST['warnings']);

        $item_eloquent->ingredients()->detach();
        $ingredients_to_save = explode('#', $_REQUEST['ingredients']);
        foreach ($ingredients_to_save as $ingredient_to_save) {
            if ($ingredient = \Mtc\Shop\Ingredient::query()->where('name', $ingredient_to_save)->first()) {
                $item_eloquent->ingredients()->attach($ingredient->id);
            }
        }
    }

    ProductInfo::saveForItem($item->id);

    \Mtc\Plugins\SiteMenu\Classes\SiteMenu::resetCache();

    if ($added) {
        Event::dispatch('AdminShopItemCreated', $item->eloquent());
    }

    if (!empty($_REQUEST['delivery_methods_all'])) {
        $item_eloquent->deliveryMethods()->detach();
    } else {
        $item_eloquent->deliveryMethods()->sync($_REQUEST['item_delivery_methods'] ?? []);
    }

    header('Location: item.php?id=' . $item->id);
    exit;
}

if (defined('ITEMS_KEYWORDS') && ITEMS_KEYWORDS) {
    // get item's keywords
    $keywords = $item_eloquent->keywords;
    // all available keywords for autocompletion
    $all_keywords = \Mtc\Core\Keywords\Keyword::all();

    if (!empty($keywords)) {
        $keywords_strings = implode(',', $keywords->toStrings());
    }

}

$warnings = Warning::query()->orderBy('warning_type')->get();

require_once $path . 'core/admin/templates/adminheader.html.php';

?>

<script src="../js/shop_script.js"></script>


<?php Event::dispatch('AdminBeforeBreadcrumbs', [ $item->eloquent() ?? null ]); ?>

<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>
    <li><a href="/shop/admin/products/manage.products.php">Manage Products</a> /</li>
    <li class="end"><?= clean_page($page_meta['title']) ?></li>
</ul>

<h1><?= $item->name ?: '(New Product)' ?></h1>
<br />

<?php

require 'tabnav.php';

if (sizeof($errors) > 0 && empty($_REQUEST['changesex'])) {
    showerrors($errors);
}

if ((sizeof($errors) == 0 && isset($_REQUEST['action'])) || isset($_REQUEST['confirm']) && $_REQUEST['confirm'] == 'added') {
    echo showmsg("Item updated", "success", $path);
}

?>
    <form action="" method="post" name="item" enctype="multipart/form-data" class="style">


        <fieldset>
            <div class="row">
                <input type="submit" value="Save product" />

                <?php if (defined('ITEM_PREVIEW') && ITEM_PREVIEW && !empty($_REQUEST['id'])) { ?>

                    <a href="<?= $item->url ?>" class="btn actionButton secondaryActionButton" target="_blank">
                        <?= !empty($item->hidden) ? 'Preview ' : 'View ' ?> this product
                    </a>

                <?php } elseif (!empty($_REQUEST['id'])) { ?>

                    <a href="<?= $item->url ?>" class="btn actionButton secondaryActionButton" target="_blank">View this product</a>

                <?php } ?>

            </div>
        </fieldset>


        <?php

        if (defined('CATEGORIES_MAX') && CATEGORIES_MAX > 0) {
            ?>
            <fieldset<?php
            if (empty($_REQUEST['id'])) {
                ?> class="show"<?php
            }
                ?>>
                <h1>
                    <a class="show el">Categories <i class="fa fa-caret-right"></i></a>
                </h1>
                <?php
                $categories_with_normalised_keys = array_values($item->categories);
                ?>

                <?php for ($i = 0; $i < CATEGORIES_MAX; $i++) { ?>
                    <?php $temp_category = $categories_with_normalised_keys[$i] ?? [] ?>
                    <?php
                        $category_label = 'Category ' . ($i + 1);
                        if ($i === 0) {
                            $category_label = 'Main Category';
                        }
                    ?>
                    <div class="row">
                        <label for="category_<?= $i ?>"><?= $category_label ?></label>
                        <select name="category_<?= $i; ?>" id="category_<?= $i ?>">
                            <option value="">No Category</option>
                            <?php
                            echo Category::renderList([
                                'selected' => $temp_category['cat_id'] ?? null,
                                'template' => 'option',
                                'show_subs' => true
                            ]);
                            ?>
                        </select>
                    </div>
                <?php } ?>

            </fieldset>
            <?php
        }

        if (defined('BRANDS_ENABLED') && BRANDS_ENABLED == true) {
            ?>
            <fieldset<?php
                if (empty($_REQUEST['id'])) {
                    ?> class="show"<?php
                }
            ?>>
                <h1>
                    <a class="show el">Brand Information<i class="fa fa-caret-right"></i></a>
                </h1>

                <div class="row">
                    <label for="brand">Brand</label>
                    <select name="brand" id="brand">
                        <option value="">No Brand</option>
                        <?php

                        $brands_query = Brand::selectBasics()->where('brands.deleted', 0);
                        MultisiteManager::decorateQueryBaseOnly($brands_query, MultisiteConstants::ENTITY_TYPE_SHOP_BRAND);

                        $brands = $brands_query->get();
                        if ($brands->count() > 0) {
                            foreach ($brands as $brand) {
                                $is_selected = ($request_brand == $brand->id || $item->brand == $brand->id);
                            ?>
                                <option value="<?= $brand->id ?>" <?= $is_selected ? 'selected' : '' ?>>
                                    <?= $brand->name ?>
                                </option>';
                            <?php
                            }
                        }
                        ?>
                    </select>
                </div>
            </fieldset>
            <?php
        }
        ?>

        <fieldset class="show">
            <h1>
                <a class="show el">
                    Product Details <i class="fa fa-caret-right"></i>
                </a>
            </h1>
            <div class="row">
                <label for="name">Name</label>
                <input type="text" id="name" name="name" value="<?= clean_page($item->name) ?>"/>
            </div>
            <div class="row">
                <label for="slug">Item Slug</label>
                <input type="text" value="<?= clean_page($item->custom['slug'] ?? '') ?>" name="custom[slug]" id="slug"/>
            </div>

            <?php
            
            if (defined('ITEMS_KEYWORDS') && ITEMS_KEYWORDS) {
                ?>
                  
                    <?php /*
                <!-- Keywords -->
                <div class="row">
                    <label for="keywords">Keywords</label>
                    <input type="hidden" id="keywords" name="keywords"
                           class="js_keywords_tagit"
                           value="<?= clean_page($keywords_strings) ?>" />
                </div>
 */?>

                <input type="hidden" id="keywords" name="keywords" value="<?= clean_page($keywords_strings) ?>" />

                <script src="/core/admin/js/libs/tagit/js/tag-it.min.js"></script>
                <link rel="stylesheet" href="/core/admin/js/libs/tagit/css/jquery.tagit.css">

                <script>
                    var all_keywords = <?= json_encode($all_keywords->toStrings()) ?>;
                </script>
                <!-- /Keywords -->
                <?php
            }
            
            ?>
            <?php
            if (defined('ITEMS_CODE') && ITEMS_CODE == true) {
                ?>
                <div class="row">
                    <label for="epos_code">EPOS Code</label>
                    <input type="text" value="<?= clean_page($item->epos_code) ?>" name="code" id="epos_code"/>
                </div>
                <?php
            }
            ?>

            <div class="row">
                <label for="product_type">Product Type</label>
                <select name="product_type" id="product_type">
                    <option value="">General</option>
                    <?php
                    foreach (\Mtc\Shop\Item::$product_types as $type => $name) {
                        $selected = $type === $item->product_type ? 'selected' : '';
                        echo "<option value='{$type}' {$selected}>{$name}</option>";
                    }
                    ?>
                </select>
            </div>

            <div class="row">
                <label for="id_check_required">Id check required (LexisNexis)</label>
                <input type="checkbox" value="1" name="id_check_required" id="id_check_required" <?= $item->id_check_required ? 'checked' : '' ?> />
            </div>

            <div class="row">
                <label for="price">
                    Price <?= (defined('VAT_ENABLED') && VAT_ENABLED == true) ? '(&pound; inc. VAT)' : ''; ?>
                </label>
                <input type="text"
                       name="price"
                       id="price"
                       value="<?= $item->price ?>"
                       class="short"
                       <?= $item_eloquent->sizes->count() ? 'readonly' : ''; ?>
                />
            </div>

            <div class="row">
                <label for="vat_rate">
                    Item Price (ex vat)
                </label>
                <input type="text"
                       name="item_vat"
                       id="item_vat"
                       value="&pound;<?= sprintf("%01.2f", $item->price_exvat) ?>"
                       class="short"
                       disabled
                />
            </div>

            <div class="row">
                <label for="sale_price">
                    Sale Price <?= VAT_ENABLED ? '(&pound; inc. VAT)' : ''; ?>
                </label>
                <input type="text"
                       name="sale_price"
                       value="<?= $item->sale_price ?: 0 ?>"
                       class="short"
                        <?= $item_eloquent->sizes->count() ? 'readonly' : ''; ?>
                />
            </div>
            <?php

            if (defined('VAT_ENABLED') && VAT_ENABLED == true) {
            ?>
            <div class="row">
                <label for="vat_rate">
                    VAT Rate
                </label>
                <?php
                $vats = Vat::all();

                if ($vats->count() > 0) {

                    if (!isset($item->vat_rate)) {
                        $item->vat_rate = VAT_RATE;
                    }
                    ?>
                    <select name="vat_rate" id="vat_rate">
                        <?php
                        foreach ($vats as $vat) {
                        ?>
                            <option value="<?= clean_page($vat->name)?>" <?= $item->vat_rate == $vat->name ? 'selected="selected"' : '';?>><?= clean_page($vat->name)?>%</option>
                        <?php
                        }
                        ?>
                    </select>
                <?php
                }
                ?>
            </div>

            <div class="row checkboxes">
                <label class="master">VAT Deductable</label>
                <input type="radio" name="vat_deductable" id="vat_deductable_yes" value="1" <?php
                if($item->vat_deductable==1 || empty($_REQUEST['id'])) {
                    echo "checked";
                }
                ?>/> <label for="vat_deductable_yes">Yes</label>
                <input type="radio" name="vat_deductable" id="vat_deductable_no" value="0" <?php
                if($item->vat_deductable == '0') {
                    echo "checked";
                }
                    ?>/> <label for="vat_deductable_no">No</label>
            </div>

            <div class="row">
                <label for="basket_quantity_locked">Basket quantity locked?</label>
                <input type="checkbox" value="1" <?= (! $item->eloquent() || $item->eloquent()->basket_quantity_locked) ? 'checked' : '' ?> name="basket_quantity_locked" id="basket_quantity_locked"/>
            </div>

            <?php
            }
            ?>
            <div class="row">
                <label for="stock">Stock</label>
                <input type="text" name="stock" id="stock" value="<?= clean_page($item->stock); ?>" />
            </div>
            <?php

            if (defined('DELIVERY_HEAVY') && DELIVERY_HEAVY == true) {

                ?>
                <div class="row">
                    <label for="heavy">Heavy Item</label>
                    <input type="checkbox" name="heavy" <?php if ($item->heavy==1) { echo "checked"; } ?>>
                </div>
                <?php
            }

            ?>
            <div class="row checkboxes">
                <label class="master">Published</label>
                <input type="radio" name="hidden" id="hidden_yes" value="0" <?php
                    if ($item->hidden == 0) {
                        echo "checked";
                    }
                    ?>/> <label for="hidden_yes">Yes</label>

                <input type="radio" name="hidden" id="hidden_no" value="1" <?php
                if($item->hidden == 1) {
                    echo "checked";
                }
                ?>/> <label for="hidden_no">No</label>
            </div>

            <div class="row">
                <label for="form_id">Assessment Form</label>
                <?php $af = $item->findAssessmentForm() ?>
                <?php $main_cat = $item->getMainCategory() ?>
                <input type="text" value="<?= $af ? $af->name : '-' ?>" readonly />
                <div class="defaultValue">
                <small>Use product's <a href="<?= $main_cat ? "/shop/admin/categories/edit.category.php?id={$main_cat->id}" : '/shop/admin/categories/manage.categories.php' ?>">main category</a> to assign assessment form.</small>
                </div>
            </div>

            <div class="row">
                <label for="disable_assessment_forms">Disable assessment forms?</label>
                <input type="checkbox" value="1" <?= (! $item->eloquent() || $item->eloquent()->disable_assessment_forms) ? 'checked' : '' ?> name="disable_assessment_forms" id="disable_assessment_forms"/>
            </div>

             <?php /*
            <div class="row">
                <label for="ingredients">Ingredients</label>
                <input type="hidden" id="ingredients" name="ingredients"
                       class="js_ingredients_tagit"
                       value="<?= !empty($_REQUEST['ingredients']) ? $_REQUEST['ingredients'] : (empty($item_eloquent->ingredients) ? '' : clean_page(implode('#', $item_eloquent->ingredients()->pluck('name')->toArray()))); ?>" />
            </div>
 */?>

            <input 
                    type="hidden" 
                    id="ingredients" 
                    name="ingredients" 
                    value="<?= !empty($_REQUEST['ingredients']) ? $_REQUEST['ingredients'] : (empty($item_eloquent->ingredients) ? '' : clean_page(implode('#', $item_eloquent->ingredients()->pluck('name')->toArray()))); ?>" 
            />

            <script>
                var all_ingredients = <?= json_encode(\Mtc\Shop\Ingredient::query()->pluck('name')->toArray()); ?>;
            </script>

            <div class="row">
                <label for="description">Description (Overview)</label>
                <textarea name="description" class="tinymce" id="description"><?= clean_page($item->description) ?></textarea>
            </div>
        </fieldset>

        <?php
        $twig->display('shop/admin/products/delivery_methods.twig', [
            'item' => $item_eloquent,
            'itemDeliveryMethods' => $item_eloquent->deliveryMethods()
                ->pluck('delivery_method_id')
                ->toArray(),
            'deliveryMethods' => DeliveryMethod::all(),
        ]);
        ?>


        <?php if ($item->eloquent()): ?>

            <fieldset class="show js_movable">
                <h1>
                    <a class="show el">
                        Product Info sections<i class="fa fa-caret-right"></i>
                    </a>
                </h1>

                <?= ProductInfo::renderInfoRecordsForm($item->id); ?>
            </fieldset>

        <?php endif ?>


        <?php if (false): ?>
            <fieldset class="show">
                <h1>
                    <a class="show el">
                        Grouping <i class="fa fa-caret-right"></i>
                    </a>
                </h1>
                <div class="row">
                    <label for="can_be_sold_separately">Can be sold separately?</label>
                    <input type="checkbox" value="1" <?= (! $item->eloquent() || $item->eloquent()->can_be_sold_separately) ? 'checked' : '' ?> name="can_be_sold_separately" id="can_be_sold_separately"/>
                </div>

                <?php if ($item->eloquent() && ! $item->eloquent()->can_be_sold_separately): ?>
                    <div class="row">
                        <label for="bundle_page_url">Bundle/Pack Creator URL</label>
                        <select name="bundle_page_url" id="bundle_page_url">
                            <option value="">--- select ---</option>
                            <?php
                            foreach (BundleType::getContainingShopItem($item->eloquent()) as $bt) {
                                $selected = ($bt->url == $item->bundle_page_url ? 'selected' : '');
                                echo "<option value='{$bt->url}' {$selected}>{$bt->url}</option>";
                            }
                            ?>
                        </select>
                    </div>
                <?php endif ?>

                <?php if ($item->eloquent()): ?>
                    <div class="row">
                        <label for="is_groupbuy_container">Group Buy container?</label>
                        <input type="checkbox" value="1" <?= $item->eloquent()->is_groupbuy_container ? 'checked' : '' ?> name="is_groupbuy_container" id="is_groupbuy_container"/>
                    </div>
                <?php endif ?>

                <?php if (true): ?>
                    <div class="row">
                        <label for="groupbuy_bundletype_id">Grouped items</label>
                        <select name="groupbuy_bundletype_id" id="groupbuy_bundletype_id">
                            <option value="">--- select ---</option>
                            <?php
                            foreach (BundleType::groupBuyTypes()->get() as $bt) {
                                $selected = ($bt->id == $item->groupbuy_bundletype_id ? 'selected' : '');
                                echo "<option value='{$bt->id}' {$selected}>{$bt->name}</option>";
                            }
                            ?>
                        </select>
                    </div>
                <?php endif ?>

            </fieldset>
        <?php endif ?>

        <?php
        if (defined('EDITABLE_META_DATA') && EDITABLE_META_DATA == true) {
        ?>
            <fieldset<?php
                if (empty($_REQUEST['id'])) {
                ?> class="show"<?php
                }
                ?>>
                <h1><a class="show el">SEO <i class="fa fa-caret-right"></i></a></h1>

                <div class="row">
                    <label for="seo_title">Page Title</label>
                    <input type="text" name="seo_title" id="seo_title" value="<?= clean_page($item->seo_title) ?>"/>
                </div>
                <div class="row">
                    <label for="seo_keywords">Meta Keywords</label>
                    <input type="text" name="seo_keywords" id="seo_keywords" value="<?= clean_page($item->seo_keywords) ?>"/>
                </div>
            
                <div class="row">
                    <label for="seo_description">Meta Description</label>
                    <input type="text" name="seo_description" id="seo_description" value="<?= clean_page($item->seo_description) ?>"/>
                </div>
            </fieldset>
        <?php
        } ?>

        <fieldset class="hide">
            <h1><a class="show el">Product Warnings <i class="fa fa-caret-down"></i></a></h1>
            <table class="manage-items">
                <tr>
                    <th>Warning type</th>
                    <th>Display</th>
                    <th>Message</th>
                </tr>
                <tbody class="tabular">
            <?php
            foreach ($warnings as $warning) {
                $checked = '';
                if (!empty($item_eloquent)) {
                    $checked = $item_eloquent->warnings->contains($warning->id) ? 'checked' : '';
                }
                ?>
                <tr>
                    <td><?= Warning::$warning_types[$warning->warning_type]; ?></td>
                    <td><input type="checkbox" value="<?= $warning->id; ?>" name="warnings[]" id="warning-<?= $warning->id; ?>" <?= $checked; ?> /> </td>
                    <td><label for="warning-<?= $warning->id; ?>" class="pointer"><?= clean_page($warning->content); ?></label></td>
                </tr>
                <?php
            }
            ?>
                </tbody>
            </table>
        </fieldset>


        <?php
        $twig->display('shop/admin/products/restrictions.twig', [
            'item' => $item_eloquent
        ]);

        ?>


        <?= QualifyingAnswersHelper::renderItemForm($item_eloquent) ?>


        <fieldset class="show">
            <h1><a class="show el">Custom fields<i class="fa fa-caret-right"></i></a></h1>

            <div id="customfields_html">
                <?php
                    $custom_field_set_id = $item->custom_field_set_id ?: CustomFieldsHelper::getDefaultSet();
                    CustomFieldsHelper::displaySet(
                        $custom_field_set_id,
                        'items',
                        $item->custom,
                        $image_folders['custom_folders']
                    );
                ?>

                <input type="hidden" name="custom_field_set_id" value="<?= clean_page($custom_field_set_id); ?>" />

            </div> <!-- #customfields_html -->

        </fieldset>

        <fieldset>
            <div class="">
                <?php
                if (!empty($_REQUEST['sku']) && sizeof($_REQUEST['sku']) > 0) {
                    foreach ($_REQUEST['sku'] as $sku) {
                        ?>
                        <input type="hidden" name="sku[]" value="<?= $sku; ?>"/>
                        <?php
                    }
                }
                ?>

                <input type="hidden" name="action" value="update"/>
                <input type="hidden" name="changesex" value=""/>
                <input type="hidden" name="id" value="<?= clean_page($_REQUEST['id']) ?>"/>
                <input type="hidden" name="copy_id" value="<?= clean_page($copy_id ?? null) ?>"/>
                <div class="row">
                    <input type="submit" value="Save product" />

                    <?php if (defined('ITEM_PREVIEW') && ITEM_PREVIEW && !empty($_REQUEST['id'])) { ?>

                        <a href="<?= $item->url ?>" class="btn actionButton secondaryActionButton" target="_blank">
                            <?= !empty($item->hidden) ? 'Preview ' : 'View ' ?> this product
                        </a>

                    <?php } elseif (!empty($_REQUEST['id'])) { ?>

                        <a href="<?= $item->url ?>" class="btn actionButton secondaryActionButton" target="_blank">View this product</a>

                    <?php } ?>

                </div>
            </div>
        </fieldset>

    </form>

<?php
require_once $path . 'core/admin/templates/adminfooter.html.php';
