<?php

namespace Mtc\Plugins\SeoSchema\Classes;

use \Item;
use Mtc\Shop\CustomField;
use MtcPharmacy\Multisite\Classes\MultisiteManager;
use Twig\Environment;

$path = '../../../';
require_once $path.'core/includes/header.inc.php';
$page_meta['title'] = 'Item Seo Schema';
$messages = [];

$errors = [];

$id = filter_input(INPUT_GET, 'id');

$mm = null;
$requested_item = \Mtc\Shop\Item::find($_REQUEST['id']);
if ($requested_item) {
    $mm = new MultisiteManager($requested_item);
    $mm->ensureTheCorrectAdminPageLoaded();
}

$item = new Item($id);

ob_start();
require_once $path.'shop/admin/products/tabnav.php';
$item_tabnav = ob_get_clean();

SchemaItem::installCustomFields();

if (! ($item_custom_fields = (new \Mtc\Shop\Item)->find($id)->custom)) {
    (new \Mtc\Shop\Item)
        ->find($id)
        ->custom()
        ->create([]);
    header('refresh: 0');
    exit();
}

$item_custom_fields = $item_custom_fields->toArray();

foreach ($item_custom_fields as $key => $value) {
    if (strpos($key, 'schema_') === false) {
        unset($item_custom_fields[$key]);
    } else {
        $item_custom_fields[$key] = [
            'name' => CustomField::query()
                ->where('database_field', $key)
                ->first()
                ->name,
            'value' => $value,
        ];
    }
}

if (filter_input(INPUT_POST, 'action') === 'update') {
    $post = $_POST;
    foreach ($post as $key => $value) {
        if (! array_key_exists($key, $item_custom_fields)) {
            unset($post[$key]);
        }
    }
    (new \Mtc\Shop\Item)
        ->find($id)
        ->custom()
        ->update($post);

    // Need to get the item again with updated values, otherwise the old (pre-save) values are passed
    $item = new Item($id);

    SchemaItem::buildCache($item);

    header('refresh: 0');
    exit();
}

if (! empty($_SESSION['message'])) {
    $messages[] = $_SESSION['message'];
}
/** @var Environment $twig */
$twig->display('SeoSchema/admin/index.twig', [
    'page_meta' => $page_meta,
    'self' => $_SERVER['PHP_SELF'],
    'id' => $item->id,
    'item' => $item,
    'errors' => $errors,
    'item_tabnav' => $item_tabnav,
    'request' => $_REQUEST,
    'messages' => $messages,
    'custom_fields' => $item_custom_fields,
    'multisite_toggle_html' => $mm ? $mm->getToggleHtml() : '',
]);
unset($_SESSION['message']);
