<?php

namespace Lycoreco\Apps\Recipes\Controllers;

use Lycoreco\Apps\Recipes\Models\{
   CategoryModel,
   IngredientModel,
   RecipeModel
};
use Lycoreco\Includes\BaseController;

define('CATALOG_MAX_RECIPES', 20);

class CatalogController extends BaseController
{
   protected $template_name = APPS_PATH . '/Recipes/Templates/catalog.php';

   public function get_context_data()
   {
      $context = parent::get_context_data();

      $context["page"] = isset($_GET['page']) ? (int)$_GET['page'] : 1;

      $context['categories'] = CategoryModel::filter(sort_by: ['obj.name'], count: 200);
      $context['ingredients'] = IngredientModel::filter(sort_by: ['obj.name'], count: 200);

      // GET request to filter catalog
      $fields = array();

      $category_id = isset($_GET['category']) ? $_GET['category'] : null;
      if ($category_id) {
         $fields[] = array(
            'name'      => 'obj.category_id',
            'type'      => '=',
            'value'     => $category_id
         );
      }
      $ingredient_ids = isset($_GET['ingredient']) ? $_GET['ingredient'] : null;
      if ($ingredient_ids) {
         $fields[] = array(
            'name'      => 'tb2.ingredient_id',
            'type'      => 'IN',
            'value'     => $ingredient_ids,
            'is_having' => true
         );
      }

      $context['recipes'] = RecipeModel::filter(
         $fields,
         ['-obj.created_at'],
         CATALOG_MAX_RECIPES
      );

      return $context;
   }
}
