<?php

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

use Mtc\Core\Admin\Menu;

//initialize variables
if (!isset($_REQUEST['action'])) {
    $_REQUEST['action'] = null;
}

$errors = null;

$pagename = 'Admin Menu';
$table = 'admin_menu';

if (empty($_GET['id'])) {
    $addedit = 'Add';
} else {
    $addedit = 'Edit';
}

$page_meta['title'] = 'Manage Admin Menu';

$display_form = true;

if ($_REQUEST['action'] == 'update') {
    $groups = [];
    parse_str($_REQUEST['values'], $pageorder);
    foreach ($pageorder['page'] as $id => $sub_id) {
        if ($sub_id == 'root') {
            $sub_id = 0;
        }
        $groups[$sub_id][] = $id;
    }

    foreach ($groups as $sub_id => $pages) {
        foreach ($pages as $order => $id) {
            $menu = Menu::where('id', $id)->first();
            $menu->sub_id = $sub_id;
            $menu->order = $order;
            $menu->save();
        }
    }
}

if ($_REQUEST['action'] == 'delete') {
    Menu::destroy($_REQUEST['delete_id']);
}

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

?>

<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>
    <li class="end"><?= clean_page($page_meta['title']) ?></li>
</ul>

<h1>Manage <?= $pagename ?></h1>

<?php

require_once 'tabnav.menu.php';

if (!empty($updated)) {
    if (count($errors) == 0 && isset($_REQUEST['action'])) {
        echo showmsg($pagename . " updated", "success", $path);
    }
}

if (!empty($errors)) {
    showerrors($errors);
}

if ($display_form === true) {
    ?>
    <form action="" method="POST" enctype="multipart/form-data" class="style manageAdminMenu">
        <?php
        Menu::getSubPages();
        ?>

        <input type="hidden" name="action" value="update" />
        <input type="hidden" name="values" value="" id="menuInfo" />

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

    </form>

    <?php
}

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