<?php

use Mtc\Shop\Incompatibility;

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

$display_form = true;

$errors = [];

/** @var Incompatibility $incompatibility */
$incompatibility = (new Incompatibility())->findOrNew($_REQUEST['id']);

$addedit = $_REQUEST['id'] ? 'Update' : 'Add';

$page_meta['title'] = $addedit . ' Incompatible Categories';

//pe($_REQUEST);

if ($_REQUEST['action'] === 'save') {
    if (empty($_REQUEST['categories'])) {
        $errors[] = 'Please specify categories!';
    }
    if (empty($_REQUEST['message'])) {
        $errors[] = 'Please specify message!';
    }
    if (empty($errors)) {
        $incompatibility->message = $_REQUEST['message'];
        $incompatibility->save();
        $incompatibility->categories()->sync((array)$_REQUEST['categories']);
        header('location: incompatible.categories.php');
        exit;
    }
}

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

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

<h1><?= $page_meta['title']; ?></h1>
<?php

include __DIR__ . '/tabnav.php';
if (count($errors)>0) {
    showerrors($errors);
}
    ?>

    <form action="" method="post" class="style">
        <fieldset class="show">
            <h1><a class="show el"><?= $page_meta['title']; ?> <i class="fa fa-caret-right"></i></a></h1>
            <div class="row">
                <label for="categories">Categories</label>
                <select name="categories[]" id="categories" multiple size="30">
                <?php echo \Mtc\Shop\Category::renderList([
                    'selected' => $incompatibility->categories()->pluck('category_id')->toArray(),
                    'template' => 'option',
                    'show_subs' => true
                ]); ?>
                </select>
            </div>
            <div class="row">
                <label for="message">Message</label>
                <textarea name="message" id="message" class="simpletinymce"><?= $incompatibility->message; ?></textarea>
            </div>
       </fieldset>
       <fieldset>
        <div class="save-button">
            <input type="hidden" name="action" value="save"/>
            <input type="submit" value="Save"/>
        </div>
       </fieldset>
    </form>

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