<?php
/**
 * @author      Nithika Senaweera <nithika.senaweera@mtc.co.uk>
 * @date        2025-05-22
 * @description Site Menu Navigation Manager - Edit / Add Menu Item
 * @copyright   MTC Media
 * @version     2.0
 */

// imports
namespace Mtc\Plugins\SiteMenu\Classes;
$path = '../../../../';
require_once $path . 'core/includes/header.inc.php';
require_once $path . 'core/admin/templates/adminheader.html.php';

// check whether request is for edit or add
if (isset($_REQUEST['id'])) {
    // Sanitize request id
    $id = filter_var($_REQUEST['id'], FILTER_SANITIZE_NUMBER_INT);
    // find the menu item by id
    $menu = SiteMenu::find($id);
    // check if menu item exists
    if ($menu) {
        $id        = $menu->id;
        $edit      = true;
        $name      = $menu->name;
        $url       = $menu->url;
        $published = $menu->published;
        $target    = $menu->target;
        $parent    = $menu->parent_id;
        $category  = $menu->category;
    }
} else {
    // if no id is passed, create a new menu item
    $id        = -1;
    $edit      = false;
    $name      = '';
    $url       = '';
    $published = -1;
    $target    = '';
    $parent    = '';
    $category  = '';
}


// check if form is submitted
if (isset($_REQUEST['submit'])) {
    // Sanitize request data
    $name      = filter_var($_REQUEST['name'], FILTER_SANITIZE_STRING);
    $url       = filter_var($_REQUEST['url'], FILTER_SANITIZE_URL);
    $published = filter_var($_REQUEST['published'], FILTER_SANITIZE_NUMBER_INT);
    $target    = filter_var($_REQUEST['target'], FILTER_SANITIZE_STRING);
    $parent    = filter_var($_REQUEST['parent'], FILTER_SANITIZE_NUMBER_INT);
    $id        = filter_var($_REQUEST['id'], FILTER_SANITIZE_NUMBER_INT);
    $category = filter_var($_REQUEST['category'], FILTER_SANITIZE_STRING);
    $message   = '';
    // check if form is submitted for edit or add
    if ($id != -1) {
        // update the menu item
        $menu            = SiteMenu::find($id);
        $menu->name      = $name;
        $menu->url       = $url;
        $menu->published = $published;
        $menu->target    = $target;
        $menu->parent_id = $parent;
        $menu->category  = $category;
        // save the menu item
        if ($menu->save()) {
            // menu item updated successfully
            $message = 'Menu item updated successfully';
        }
    } else {
        // check if menu item already exists
        $existing_menu = SiteMenu::where('name', $name)
                                 ->first();
        if ($existing_menu) {
            // menu item already exists
            $message = 'Menu item already exists';
        } else {
            // create a new menu item
            $menu            = new SiteMenu();
            $menu->name      = $name;
            $menu->url       = $url;
            $menu->published = $published;
            $menu->target    = $target;
            $menu->parent_id = $parent;
            $menu->category  = $category;

            $saveMenu = $menu->save();
            // save the menu item
            if ($saveMenu) {
                // menu item created successfully
                $message = 'Menu item created successfully';
            } else {
                // menu item creation failed
                $message = 'Menu item creation failed';
            }
        }
    }
}


if (isset($_REQUEST['parent'])) {
    // Sanitize parent request
    $parentReq = filter_var($_REQUEST['parent'], FILTER_SANITIZE_NUMBER_INT);
} else {
    $parentReq = '';
}

?>
<ul class="breadcrumbs el">
    <?php
    if ($id != -1) {
        require '../breadcrumbs.php';
    }
    else {
        ?>
        <a href="../index.php?id=<?= htmlspecialchars(clean_page($parentReq))?>" class="btn btn-black">Back</a>
    <?php
    }

    ?>
</ul>
<div class="message">
    <?php
    if (isset($message)) {
        // display the message
        ?>
        <p> <?= htmlspecialchars($message) ?></p>
        <?php
    }
    ?>
</div>
<form action="edit.php?submit=<?= clean_page($id) !=-1 ? "edit" : "add" ?>" class="style" method="post">
    <h1><?= clean_page($id) !=-1 ? 'Edit' : 'Add' ?> Menu Item</h1>
    <p><?= clean_page($id) !=-1 ? 'Edit' : 'Add' ?> menu items for the navigation purposes</p>
    <input type="hidden" value="<?= htmlspecialchars($id) ?>" name="id">
    <div class="row">
        <label for="parent">Parent</label>
        <select name="parent" id="parent">
            <option value="" <?= $parent == '' ? 'selected' : '' ?>>--- Select the parent ---</option>
            <option value="0" <?= $parent == 0 ? 'selected' : '' ?>>--- Parent ---</option>
            <?php
            // get all menu items
            $menu_items = SiteMenu::where('category', '!=', 'item')->get();
            // loop through the menu items and create options
            foreach ($menu_items as $item) {
                ?>
                <option value="<?= htmlspecialchars($item->id) ?>"
                    <?= $parent == $item->id || $parentReq == $item->id ? 'selected' : '' ?>>
                    <?= htmlspecialchars($item->name) ?>
                </option>
                <?php
            }
            ?>
        </select>
    </div>
    <div class="row">
        <label for="category">Category</label>
        <select name="category" id="category">
            <option value="" <?= $category == "" ? 'selected' : '' ?>>--- Select the Category ---</option>
            <option value="root" <?= $category == "root" ? 'selected' : '' ?>>Root</option>
            <option value="menu" <?= $category == "menu" ? 'selected' : '' ?>>Menu</option>
            <option value="item" <?= $category == "item" ? 'selected' : '' ?>>Item</option>
        </select>
    </div>
    <div class="row">
        <label for="name">Name</label>
        <input type="text" value="<?= htmlspecialchars($name) ?>" name="name" placeholder="Menu Name" required>
    </div>
    <div class="row siteMenuAdminToggleContainer">
        <label for="url">Url</label>
        <input type="text" value="<?= htmlspecialchars($url) ?>" name="url" id="url" placeholder="Menu URL" required>
    </div>
    <div class="row">
        <label for="published">Published</label>
        <select name="published" id="published">
            <option value="-1" <?= $published == -1 ? 'selected' : '' ?>>--- Select the status ---</option>
            <option value="0" <?= $published == 0 ? 'selected' : '' ?>>Unpublished</option>
            <option value="1" <?= $published == 1 ? 'selected' : '' ?>>Published</option>
        </select>
    </div>
    <div class="row siteMenuAdminToggleContainer">
        <label for="target">Open Link In</label>
        <select name="target" id="target">
            <option value="" <?= $target == '' ? 'selected' : '' ?>>--- Select where to open the link ---</option>
            <option value="_self" <?= $target == '_self' ? 'selected' : '' ?>>Same tab/window (_self)</option>
            <option value="_blank" <?= $target == '_blank' ? 'selected' : '' ?>>New tab/window (_blank)</option>
            <option value="_parent" <?= $target == '_parent' ? 'selected' : '' ?>>Parent frame (_parent)</option>
            <option value="_top" <?= $target == '_top' ? 'selected' : '' ?>>Top-level frame (_top)</option>
        </select>
    </div>
    <div class="row">
        <input type="submit" value="<?= clean_page($id) !=-1 ? 'Update' : 'Add' ?>">
        <a href="../index.php" class="btn btn-black">Cancel</a>
    </div>
</form>
<script>
    document.addEventListener('DOMContentLoaded', () => {
        // get the category
        const category = document.querySelector('select#category');
        // get the toggle container
        const toggleContainer = document.querySelectorAll('.siteMenuAdminToggleContainer');
        // get the url input
        const urlInput = document.querySelector('#url');
        // get the target input
        const targetInput = document.querySelector('#target');
        // value change event listener
        category.addEventListener('change', (e) => {
            // check the value of the category
            if (e.target.value === 'root' || e.target.value === 'menu') {
                // hide the toggle container
                toggleContainer.forEach((container => {
                    container.style.display = 'none';
                }));
                // reset the url input
                urlInput.required = false;
                urlInput.value = '#';
                // reset the target input
                targetInput.value = '_self'; // Reset target to default
            }
            else if (e.target.value === 'item') {
                // show the toggle container
                toggleContainer.forEach((container => {
                    container.style.display = 'block';
                }));
                // set the url input to required
                urlInput.required = true;
                urlInput.value = '';
            }
        });
    })

</script>
