<?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]],
    "done" => ["required" => false, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
];

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

    $oldPost = $_POST;

    $list = __RB_getShoppingList();

    if (empty($_GET['shoppingListEdit']) || empty($list[$_GET['shoppingListEdit']])) {
        __RB_errorHandler('shopping_list_edit', 'invalid', 'Invalid id');

    } else {
        $list[$_GET['shoppingListEdit']]['title'] = $_POST['title'];
        $list[$_GET['shoppingListEdit']]['items'] = [];

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

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

                } else {
                    $list[$_GET['shoppingListEdit']]['items'][] = [
                        'text' => $item['text'],
                        'done' => $item['done'] == 1 ? 1 : 0
                    ];
                }
            }
        }

        if (!$failed) {
            $__RB_success['shopping_list_edit'] = true;

            __RB_storeSession('shoppingList', $list);

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

