<?php

namespace Lycoreco\Apps\Recipes\Controllers;

use Lycoreco\Apps\Recipes\Models\FavoriteModel;
use Lycoreco\Apps\Recipes\Models\RecipeModel;
use Lycoreco\Includes\BaseController;

define('FAVORITES_MAX_RECIPES', 500); 

class FavoritesController extends BaseController
{
    protected $template_name = APPS_PATH . '/Recipes/Templates/favorites.php';
    protected $allow_role = 'user';

    public function get_context_data()
    {
        $context = parent::get_context_data();
        
        $favorite_recipes = FavoriteModel::filter(array(
            [
                'name'      => 'obj.user_id',
                'type'      => '=',
                'value'     => CURRENT_USER->get_id()
            ]
        ));
        $fav_ids = array_map(function($recipe) {
            return $recipe->field_recipe_id;
        }, $favorite_recipes);

        if(!empty($fav_ids)) {
            $context['recipes'] = RecipeModel::filter(
                array(
                    [
                        'name'      => 'obj.id',
                        'type'      => 'IN',
                        'value'     => $fav_ids
                    ]
                ),
                ['-obj.created_at'],
                FAVORITES_MAX_RECIPES
            );
        }
        else {
            $context['recipes'] = [];
        }

        return $context;
    }
}