<?php

$inputRules = [
    "title" => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    "items" => ["required" => true,]
];

$inputRules2 = [
    "text" => ["required" => false, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
];

if (__RB_validateInput($inputRules, 'shopping_list_add')) {
    $failed = false;

    $oldPost = $_POST;

    $objCreate = ['title' => $_POST['title'], 'date' => gmdate('Y-m-d H:i:s'), 'items' => []];

    foreach ($_POST['items'] as $item) {
        $_POST = $item;

        if (!empty($item['text'])) {
            if (!__RB_validateInput($inputRules2, 'shopping_list_add')) {
                $failed = true;

            } else {
                $objCreate['items'][] = [
                    'text' => $item['text'],
                    'done' => 0
                ];
            }
        }
    }

    if (!$failed) {
        $__RB_success['shopping_list_add'] = true;
        $list = __RB_getShoppingList();
        $maxId = null;

        foreach ($list as $obj) {
            if ($obj['id'] > $maxId) {
                $maxId = $obj['id'];
            }
        }

        $maxId = $maxId === null ? 1 : $maxId + 1;

        $objCreate['id'] = $maxId;

        $list[$maxId] = $objCreate;

        __RB_storeSession('shoppingList', $list);

        header('location:'.$_SERVER['PHP_SELF'] . (!empty($_SERVER['QUERY_STRING']) ? '?' : '') . $_SERVER['QUERY_STRING']);
        exit;
    }
}

