<?php
/**
 * Site Menu Edit page
 *
 * @category Plugins
 * @package  Mtc_Site_Menu
 * @author   mtc. Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 */

namespace Mtc\Plugins\SiteMenu\Classes;

use CMSNav;
use Mtc\Shop\Category;

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

$page['title'] = 'Edit Menu Item';

if (!empty($_REQUEST['id'])) {
    $add_edit = 'Edit';
    $menu = SiteMenu::find($_REQUEST['id']);
    $menu_id = (int)$_REQUEST['id'];
    $append_url = '?id=' . $menu_id;
} else {
    $add_edit = 'Add';
    $menu = new SiteMenu();
    $menu_id = '';
    $append_url = '';
    if (!empty($_REQUEST['parent_id'])) {
        $menu->parent_id = (int)$_REQUEST['parent_id'];
    }
}

$errors = [];

// ------------------------ POSTBACK --------------------------

if (!empty($_REQUEST['action'])
    && $_REQUEST['action'] == 'update') {
    if (empty($_REQUEST['name'])) {
        $errors['name'] = 'Menu item name is required';
    }

    if (empty($errors)) {
        $menu->fill($_POST);
        $menu->name = $menu->name;
        $menu->css_class = filter_var($menu->css_class, FILTER_SANITIZE_STRING);
        $menu->url = filter_var($menu->url, FILTER_SANITIZE_STRING);
        $menu->target = filter_var($menu->target, FILTER_SANITIZE_STRING);
        $menu->category_id = filter_var($menu->category_id, FILTER_SANITIZE_STRING);
        $menu->single_category = filter_var($menu->single_category, FILTER_SANITIZE_STRING);
        $menu->single_cms_page = filter_var($menu->single_cms_page, FILTER_SANITIZE_STRING);
        $parsed_url = parse_url($menu->url);

        // If not a full URL, then ensure that we have the / at the start of the string.
        if (!array_key_exists('host', $parsed_url)) {
            $menu->url = '/' . ltrim($menu->url, '/');
        }

        $menu->save();

        if ($add_edit == "Add") {
            // add item at the end of order list by default
            $menu->order = $menu->id;
            $menu->save();

            $params = [
                'id' => $menu->id,
                'confirm' => 'added',
            ];
            header('Location: /plugins/SiteMenu/admin/edit.php?' . http_build_query($params));
            exit;
        }
    }
}
// --------------------- END OF POSTBACK ----------------------

require_once $path . 'core/admin/templates/adminheader.html.php';
?>
    <link rel="stylesheet" href="/plugins/SiteMenu/admin/css/style.css"/>
    <ul class="breadcrumbs el">
        <?php
        require 'breadcrumbs.php';
        ?>
    </ul>

    <h1><?= clean_page($add_edit) ?> menu item</h1>

    <?php
require 'tabnav.php';

if (sizeof($errors) > 0) {
    showerrors($errors);
}

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

if (!empty($_REQUEST['confirm']) && $_REQUEST['confirm'] == 'added') {
    echo showmsg("Menu added", "success", $path);
}

?>
    <form action="<?= $_SERVER['PHP_SELF'] . $append_url ?>" method="post" class="style">
        <fieldset class="show">
            <h1>
                <a class="show el">Menu Item Information <i class="icon-caret-right"></i></a>
            </h1>

            <div class="row">
                <label for="name">Name</label>
                <input type="text"
                       name="name"
                       id="name"
                       value="<?= $menu->name ?>"
                >
            </div>

            <div class="row checkboxes">
                <label class="master">Published</label>
                <input type="radio"
                       name="published"
                       id="publishedYes"
                       value="1"
                    <?= $menu->published ? 'checked' : '' ?>
                />
                <label for="publishedYes">Yes</label>

                <input type="radio"
                       name="published"
                       id="publishedNo"
                       value="0"
                    <?= $menu->published ? '' : 'checked' ?>
                />
                <label for="publishedNo">No</label>
            </div>

            <div class="row">
                <label for="parent_id">Parent Menu Item</label>
                <select name="parent_id" id="parent_id">
                    <?php
                    foreach (SiteMenu::getAllSiteMenuOptions($menu->parent_id) as $menu_item) { ?>
                        <option value="<?= $menu_item['id']; ?>"<?= $menu_item['selected'] ? ' selected="selected"' : ''; ?>>
                            <?= str_repeat('- ', $menu_item['sublevel']); ?><?= $menu_item['name']; ?>
                        </option>
                        <?php
                    } ?>
                </select>
                <div class="hint el">
                    <i class="icon fa fa-info-circle"></i>
                    <div class="text">
                        Under which menu item this should be listed
                    </div>
                </div>
            </div>

            <div class="row">
                <label for="url">Link</label>
                <input type="text"
                       name="url"
                       id="url"
                       value="<?= clean_page($menu->url) ?>"
                >
            </div>

            <div class="row">
                <label for="parent_id">Target</label>
                <select name="target" id="target">
                    <?php
                    foreach (['_self', '_blank'] as $target) { ?>
                        <option value="<?= $target ?>"<?= $menu->target == $target ? ' selected="selected"' : ''; ?>>
                            <?= $target ?>
                        </option>
                        <?php
                    } ?>
                </select>
                <div class="hint el">
                    <i class="icon fa fa-info-circle"></i>
                    <div class="text">
                        Target '_self' means opening in same window. '_blank' would open in a new window. Use the latter
                        for external links.
                    </div>
                </div>
            </div>

            <?php
            if ($adminuser->user['id'] == MTCADMIN_USERID) {
                ?>
                <div class="row">
                    <label for="cssClass">CSS Class</label>
                    <input type="text"
                           name="css_class"
                           id="cssClass"
                           value="<?= clean_page($menu->css_class) ?>"
                    >
                </div>
                <?php
            }

            ?>
            <style>
                <?php if(empty($_GET['debug'])): ?>
                .keepHidden{
                    display: none !important;
                }
                <?php endif; ?>
            </style>
            <?php

            if (BRANDS_ENABLED === true) {
                ?>
                <div class="row checkboxes <?php if(empty($_GET['debug'])): ?>keepHidden<?php endif ?>">
                    <label for="brand_list">List Brands</label>
                    <input type="radio"
                           name="brand_list"
                           id="brandListYes"
                           value="1"
                        <?= $menu->brand_list ? 'checked' : ''; ?>
                    />
                    <label for="brandListYes">Yes</label>

                    <input type="radio"
                           name="brand_list"
                           id="brandListNo"
                           value="0"
                        <?= $menu->brand_list ? '' : 'checked'; ?>
                    />
                    <label for="brandListNo">No</label>

                    <div class="hint el">
                        <i class="icon fa fa-info-circle"></i>
                        <div class="text">
                            If checked, menu will list all site brands
                        </div>
                    </div>
                </div>
                <?php
            }


            if (CATEGORIES_MAX > 0) {
                ?>
                <div class="row <?php if(empty($_GET['debug'])): ?>keepHidden<?php endif ?>">
                    <label for="category_id">Display info from Category</label>
                    <select name="category_id" id="category_id">
                        <option value="0">None</option>
                        <?= get_the_categories($menu->category_id, true, []) ?>
                        ?>
                    </select>
                </div>
                <div class="row <?php if(empty($_GET['debug'])): ?>keepHidden<?php endif ?>">
                    <label for="single_category">List single category</label>
                    <select name="single_category" id="single_category">
                        <option value="0">None</option>
                        <?=
                        $categories = Category::getParentCategories();
                        foreach ($categories as $category) {
                            ?>
                            <option value="<?php echo $category->id; ?>"<?php if ($menu->single_category == $category->id) { ?> selected<?php } ?>><?php echo $category->name; ?></option>
                            <?php
                        }
                        ?>
                    </select>
                    <div class="hint el">
                        <i class="icon fa fa-info-circle"></i>
                        <div class="text">
                            If chosen, only one category will be shown
                        </div>
                    </div>
                </div>
                <div class="row">
                    <label for="category_list">List Sub-Categories of</label>
                    <select name="category_list" id="category_list">
                        <option value="0">None</option>
                        <option value="-1"
                            <?= $menu->category_list == -1 ? 'selected="selected"' : '' ?>>
                            All
                        </option>
                        <?= get_the_categories($menu->category_list, true, []); ?>
                    </select>
                    <div class="hint el">
                        <i class="icon fa fa-info-circle"></i>
                        <div class="text">
                            If chosen, menu will list sub-categories of the chosen category as menu items
                        </div>
                    </div>
                </div>
                <?php
            }

            if (CMS_ENABLED === true) {
                ?>
                <div class="row <?php if(empty($_GET['debug'])): ?>keepHidden<?php endif ?>">
                    <label for="site_tree">This is a CMS Tree</label>
                    <select name="site_tree" id="site_tree">
                        <option value="-1">None</option>
                        <?php
                        $tree = CMSNav::tree(0);
                        foreach ($tree as $id => $leaf) {
                            ?>
                            <option value="<?= $id ?>" <?= $menu->site_tree == $id ? 'selected="selected"' : '' ?>>
                                <?= clean_page($leaf['title']) ?>
                            </option>
                            <?php
                            if (!empty($leaf['sub'])) {
                                foreach ($leaf['sub'] as $l2_id => $l2_leaf) {
                                    ?>
                                    <option value="<?= $l2_id ?>"
                                        <?= $menu->site_tree == $l2_id ? 'selected="selected"' : '' ?>>
                                        - <?= clean_page($l2_leaf['title']) ?>
                                    </option>
                                    <?php
                                    if (!empty($l2_leaf['sub'])) {
                                        foreach ($l2_leaf['sub'] as $l3_id => $l3_leaf) {
                                            ?>
                                            <option value="<?= $l3_id ?>"
                                                <?= $menu->site_tree == $l3_id ? 'selected="selected"' : '' ?>>
                                                -- <?= clean_page($l3_leaf['title']) ?>
                                            </option>
                                            <?php
                                        }
                                    }
                                }
                            }
                        }
                        ?>
                    </select>
                    <div class="hint el">
                        <i class="icon fa fa-info-circle"></i>
                        <div class="text">
                            If chosen, menu will create sub-menu if the linked page has sub-entries.
                            CMS page link will be used instead of Link field above.
                        </div>
                    </div>
                </div>
                <div class="row <?php if(empty($_GET['debug'])): ?>keepHidden<?php endif ?>">
                    <label for="single_cms_page">Single page</label>
                    <input type="hidden" value="0" name="single_cms_page"/>
                    <input type="checkbox" value="1" name="single_cms_page"
                           id="single_cms_page"<?php if ($menu->single_cms_page == 1) { ?> checked="checked"<?php } ?> />
                    <div class="hint el">
                        <i class="icon fa fa-info-circle"></i>
                        <div class="text">
                            If chosen, only the selected cms page will be shown instead of the page and it's sub pages.
                        </div>
                    </div>
                </div>
                <?php
            }
            ?>
        </fieldset>

        <div class="row">
            <input type="hidden" name="action" value="update"/>
            <input type="hidden" name="id" value="<?= clean_page($menu_id) ?>"/>
            <input type="submit" value="Save"/>
        </div>
    </form>
    <?php
require_once $path . 'core/admin/templates/adminfooter.html.php';
