<?php
/**
 * Site Menu Listing page
 *
 * @category Plugins
 * @package  Mtc_Site_Menu
 * @author   mtc. Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 */
namespace Mtc\Plugins\SiteMenu\Classes;

$path = '../../../';
require_once $path . 'core/includes/header.inc.php';
require_once dirname(__DIR__) . '/includes/install.php';

$page['title'] = 'Manage Site Menu';


if (filter_input(INPUT_POST, 'action') === 'restore') {
    SiteMenu::query()
        ->whereIn('id', $_POST['restore_ids'])
        ->withTrashed()
        ->get()
        ->each(function (SiteMenu $menu_entry) {
            $menu_entry->restore();
        });
    $_SESSION['message'] = 'Menu entries restored';
    header('Location: ' . $_SERVER['REQUEST_URI']);
    exit;
}

require_once $path . 'core/admin/templates/adminheader.html.php';
?>
<ul class="breadcrumbs el">
    <?php
    require 'breadcrumbs.php';
    ?>
</ul>
<h1>Manage Site Menu Trashed entries</h1>

<?php
require 'tabnav.php';

$menu_items = SiteMenu::query()
    ->orderBy('deleted_at', 'desc')
    ->onlyTrashed()
    ->with('parentMenu')
    ->get();

if (!empty($_SESSION['message'])) {
    echo showmsg($_SESSION['message'], 'success', $path);
    unset ($_SESSION['message']);
}

if (count($menu_items) > 0) {
    ?>
    <form action="<?= $_SERVER['REQUEST_URI'] ?>" method="post">
        <table id="manage-site-menus" class="manage-items">
            <tr>
                <th class="center">Menu ID</th>
                <th>Name</th>
                <th>Parent</th>
                <th class="center">Restore</th>
            </tr>
            <tbody class="tabular">
                <?php
                foreach ($menu_items as $menu) {
                    ?>
                    <tr>
                        <td class="center">
                            <?= clean_page($menu->id); ?>
                        </td>
                        <td>
                                <?= clean_page($menu->name); ?>
                        </td>
                        <td>
                            <?= $menu->parent_id ? clean_page($menu->parentMenu()->withTrashed()->first()->name) : 'Root' ?>
                        </td>
                        <td class="center">
                            <input type="checkbox"
                                   name="restore_ids[]"
                                   value="<?= (int)$menu->id ?>"
                        </td>
                    </tr>
                    <?php
                }
                ?>
            </tbody>
        </table>
        <div class="row">
            <button type="submit"
                    name="action"
                    value="restore"
                    class="btn">
                Restore Entries
            </button>
        </div>
    </form>
<?php
} else {
    ?>
    <p>There are currently no menu items in this section</p>
    <?php
}

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