<?php

use Lycoreco\Apps\Recipes\Models\{
    RecipeModel,
    RecipeUserMenu
};

function get_ajax_error($message, $error_code = 500)
{
    http_response_code($error_code);

    $error = array();
    $error['error'] = $message;

    return $error;
}

/**
 * Ajax actions
 */
function ajax_search()
{
    $search_query = $_POST['query'] ?? null;
    if (!isset($search_query)) {
        return get_ajax_error("Missing 'query' parameter.", 400);
    }
    if (!CURRENT_USER) {
        return get_ajax_error('You are not authorized', 401);
    }
    $result = array();

    $recipes = RecipeModel::filter(
        array(),
        array(),
        5,
        'AND',
        0,
        $search_query
    );
    
    $result['count'] = count($recipes);
    $result['result'] = $recipes;

    return $result;
}

function ajax_usermenu() 
{
    $recipe_id = $_POST['recipe_id'] ?? null;
    $dayofweek = $_POST['dayofweek'] ?? null;

    if (!CURRENT_USER) {
        return get_ajax_error('You are not authorized', 401);
    }
    if (!isset($recipe_id)) {
        return get_ajax_error("Missing 'recipe_id' parameter.", 400);
    }
    if (!isset($dayofweek)) {
        return get_ajax_error("Missing 'dayofweek' parameter.", 400);
    }
    $result = array();

    $user_menu = RecipeUserMenu::get(array(
        [
            'name'      => 'obj.recipe_id',
            'type'      => '=',
            'value'     => $recipe_id
        ],
        [
            'name'      => 'obj.user_id',
            'type'      => '=',
            'value'     => CURRENT_USER->get_id()
        ]
    ));
    // If user choose optiopn 'remove'
    if($dayofweek == 'remove') {
        if($user_menu) {
            $user_menu->delete();
            $result['success'] = 'This recipe was removed from your list';
            return $result;
        }
        else {
            return get_ajax_error("This recipe in your menu is not exists", 400);
        }
    }

    // If not exists, add new recipe in user menu
    if(!$user_menu) {
        $user_menu = new RecipeUserMenu();
        $user_menu->field_recipe_id = $recipe_id;
        $user_menu->field_user_id = CURRENT_USER->get_id();
    }

    $user_menu->field_dayofweek = $dayofweek;
    $user_menu->save();

    $result['success'] = 'You have successfully added the recipe to your menu.';
    return $result;
}
