<?php
namespace Mtc\Plugins\SeoSchema\Classes;

use \Item;
use Mtc\Core\Response;

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

$item_id = filter_input(INPUT_POST, 'item_id');
$id = filter_input(INPUT_POST, 'id') ?? null;

if (filter_input(INPUT_POST, 'action') === 'load') {
    $data = SchemaItem::query()
        ->where('item_id', $item_id)
        ->where('parent_id', $id)
        ->get()
        ->map(function ($item) {
            $item->isExpanded = false;
            return $item;
        });
    Response::outputJson('ok', [
        'children' => $data
    ]);
    exit;
}

if (filter_input(INPUT_POST, 'action') === 'add_item' && filter_input(INPUT_POST, 'field')) {
    if ($id == 0) {
        $id = null;
    }
    SchemaItem::query()->create([
        'item_id' => $item_id,
        'item_type' => \Mtc\Shop\Item::class,
        'parent_id' => $id,
        'field' => filter_input(INPUT_POST, 'field'),
        'type' => filter_input(INPUT_POST, 'type')
    ]);
    $messages[] = 'Item Added';
}

if (filter_input(INPUT_POST, 'action') === 'update_value' && filter_input(INPUT_POST, 'id')) {
    $item = SchemaItem::query()
        ->where('item_id', $item_id)
        ->where('id', $id)
        ->first();
    $item->value = filter_input(INPUT_POST, 'value') ?? '';
    $item->save();

    // We need to update the $id to be the parent of this item
    // So we can return collection of the correct level
    $id = $item->parent_id;
    $messages[] = 'Value updated';
}

if (filter_input(INPUT_POST, 'action') === 'remove' && filter_input(INPUT_POST, 'id')) {
    $item = SchemaItem::query()
        ->where('item_id', $item_id)
        ->where('id', $id)
        ->first();

    // We need to update the $id to be the parent of this item
    // So we can return collection of the correct level
    $id = $item->parent_id;
    $item->delete();
    $messages[] = 'Item Deleted';
}

$data = SchemaItem::query()
    ->where('item_id', $item_id)
    ->where('parent_id', $id)
    ->get()
    ->map(function ($item) {
        $item->isExpanded = false;
        return $item;
    });
Response::outputJson('ok', [
    'children' => $data
], $messages);
exit;