<?php

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

$failed = false;

$oldPost = $_POST;

$list = __RB_getShoppingList();

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

} else {
    $list[$_GET['shoppingList']]['items'] = [];

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

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

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

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

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