<?php

use Lycoreco\Apps\Recipes\Models\RecipeModel;

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

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

    return json_encode($error, JSON_PRETTY_PRINT);
}

/**
 * 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 json_encode($result, JSON_PRETTY_PRINT);
}