<?php

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

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 = array();
    $recipe_models = RecipeModel::filter(
        count: 5,
        search: $search_query
    );
    foreach ($recipe_models as $recipe_model) {
        $recipe = $recipe_model->getAssocArr();
        $recipe['image_url'] = $recipe_model->get_image_url();
        $recipe['url'] = $recipe_model->get_absolute_url();
        $recipes[] = $recipe;
    }
    
    $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;
}
function ajax_create_ingredient()
{
    $ingredient_name = $_POST['name'] ?? null;
    $ingredient_unit = $_POST['unit'] ?? null;

    if (!CURRENT_USER) {
        return get_ajax_error('You are not authorized', 401);
    }
    if (!isset($ingredient_name)) {
        return get_ajax_error("Missing 'name' parameter.", 400);
    }
    if (!isset($ingredient_unit)) {
        return get_ajax_error("Missing 'unit' parameter.", 400);
    }

    $ingredient = new IngredientModel();
    $ingredient->field_name = $ingredient_name;
    $ingredient->field_unit_name = $ingredient_unit;
    $ingredient->save();

    $result = array();
    $result['success'] = 'You have successfully added new ingredient';
    return $result;
}
function ajax_search_ingredient()
{
    $search_query = $_POST['query'] ?? null;
    if (!isset($search_query)) {
        return get_ajax_error("Missing 'query' parameter.", 400);
    }
    $result = array();

    $ingredients = IngredientModel::filter(
        count: 5,
        search: $search_query
    );
    $result['count'] = count($ingredients);
    $result['result'] = array_map(function($ing) {
        return $ing->getAssocArr();
    }, $ingredients);

    return $result;
}

function ajax_favorites()
{
    $recipe_id = $_POST['recipe_id'] ?? null;
    $type = $_POST['type'] ?? 'add'; // add, remove

    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($type != 'add' && $type != 'remove')
    {
        return get_ajax_error("'type' parameter can be only 'add' or 'remove'", 400);
    }
    $result = array();

    $favorite = FavoriteModel::get(array(
        [
            'name'      => 'obj.recipe_id',
            'type'      => '=',
            'value'     => $recipe_id
        ],
        [
            'name'      => 'obj.user_id',
            'type'      => '=',
            'value'     => CURRENT_USER->get_id()
        ]
    ));

    if($type == 'remove') {
        if($favorite) {
            $favorite->delete();
            $result['success'] = 'This recipe was removed from your favorite list';
            return $result;
        }
        else {
            return get_ajax_error("This recipe from your favorites list does not exist.", 400);
        }
    }

    if(!$favorite)
        $favorite = new FavoriteModel();

    $favorite->field_user_id = CURRENT_USER->get_id();
    $favorite->field_recipe_id = $recipe_id;
    $favorite->save();

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