<?php

use Mtc\Shop\PropertyType;

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

init_request_values([
    'id' => null,
]);

$errors = [];

if ($_REQUEST['id'] > 0) {
    $addedit = 'Update';
} else {
    $addedit = 'Add';
}

$page_meta['title'] = $addedit . ' Property';

$display_form = true;

/*
  Add A New Property
 */
if ($_REQUEST['action'] == 'updateproperty') {
    if ($_REQUEST['property_name'] == '') {
        $errors['property_name'] = 'You must enter a property name';
    }

    if (count($errors) == 0) {

        if ($_REQUEST['id'] > 0) {
            PropertyType::query()
                ->where('id', $_REQUEST['id'])
                ->update([
                    'name' => $_REQUEST['property_name']
                ]);
            header('Location: manage.properties.php?message=update');
        } else {
            PropertyType::query()
                ->create([
                    'name' => $_REQUEST['property_name'],
                ]);
            header('Location: manage.properties.php?message=added');
        }

        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.properties.php">Manage Item Properties</a> /</li>

    <li class="end"><?= $addedit ?> Property</li>
</ul>

<h1><?= $addedit ?> Property</h1>

<?php
include 'tabnav.php';
?>

<?php
if (isset($updated)) {
    ?>
    <?php
    if (count($errors) == 0 && isset($_REQUEST['action'])) {
        echo showmsg("Property updated", "success", $path);
    }
    ?>
    <?php
}

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

if ($display_form) {
    $propertyType = PropertyType::query()
        ->find($_REQUEST['id']);
    ?>

    <form action="edit.properties.php" method="POST" enctype="multipart/form-data" class="style">
        <fieldset class="show">
            <h1>
                <a class="show el">
                    Property Information <i class="fa fa-caret-right"></i>
                </a>
            </h1>

            <div class="row">
                <label for="property_name">
                    Name
                </label>
                <input type="text"
                       name="property_name"
                       id="property_name"
                       value="<?= ($propertyType->name ?? null) ?>"
                       class="INPUT1"
                >
            </div>
        </fieldset>

        <input type="hidden" name="action" value="updateproperty"/>
        <input type="hidden" name="id" value="<?= $_REQUEST['id']; ?>"/>

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

    </form>

    <?php
}

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