<?php

namespace Lycoreco\Apps\Recipes\Controllers;

use Exception;
use Lycoreco\Apps\Recipes\Models\IngredientInRecipeModel;
use Lycoreco\Apps\Recipes\Models\RecipeModel;
use Lycoreco\Apps\Recipes\Models\ReviewsModel;
use Lycoreco\Apps\Users\Models\UserModel;
use Lycoreco\Includes\BaseController;
use Lycoreco\Includes\Model\ValidationError;
use Lycoreco\Includes\Routing\HttpExceptions;

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

   protected function post()
   {
      if(!CURRENT_USER) {
         $this->context['reviews_error'] = 'You are not authorized';
         return;
      }
      $rating = $_POST['rating-select'] ?? null;
      $title = $_POST['review-title'] ?? null;
      $content = $_POST['review-body-input'] ?? null;

      $recipe = $this->get_model();

      $review = new ReviewsModel();
      $review->field_title = $title;
      $review->field_content = $content;
      $review->field_rating = $rating;
      $review->field_status = 'pending';
      $review->field_user_id = CURRENT_USER->get_id();
      $review->field_recipe_id = $recipe->get_id();

      try {
         $review->save();
         $this->context['display_review_form'] = false;
      }
      catch(ValidationError $ex) {
         $this->context['reviews_error'] = $ex->getMessage();
      }
      catch(Exception $ex) {
         $this->context['reviews_error'] = 'Unexpected error';
      }
   }

   protected function get_model()
   {
      if (isset($this->__model))
         return $this->__model;

      $this->__model = RecipeModel::get(
         array(
            [
               'name'      => 'obj.id',
               'type'      => '=',
               'value'     => $this->url_context['url_1']
            ]
         )
      );
      if (empty($this->__model))
         throw new HttpExceptions\NotFound404('Recipe not found');

      return $this->__model;
   }

   public function get_context_data() 
   {
      $context = parent::get_context_data();
      $recipe = $this->get_model();


      $context['recipe'] = $recipe;
      $context['display_review_form'] = true;

      $context['author'] = UserModel::get(array(
         [
            'name' => 'obj.id',
            'type' => '=',
            'value' => $recipe->field_author_id
         ]
      ));

      $context['ingredients'] = IngredientInRecipeModel::filter(array(
         [
            'name' => 'obj.recipe_id',
            'type' => '=',
            'value' => $recipe->get_id()
         ]
         ));

      $context['reviews'] = ReviewsModel::filter(array(
         [
            'name'      => 'obj.recipe_id',
            'type'      => '=',
            'value'     => $recipe->get_id()
         ],
         [
            'name'      => 'obj.status',
            'type'      => '=',
            'value'     => 'publish'
         ],
      ));
      $context['reviews_average'] = '0.0';
      if(!empty($context['reviews'])) {
         $sum = array_sum(array_column($context['reviews'], 'field_rating'));
         $count = count($context['reviews']);
         $context['reviews_average'] = number_format($sum / $count, 1);
      }

      if(CURRENT_USER) {
         $review_exists = ReviewsModel::count(array(
            [
               'name'      => 'obj.recipe_id',
               'type'      => '=',
               'value'     => $recipe->get_id()
            ],
            [
               'name'      => 'obj.user_id',
               'type'      => '=',
               'value'     => CURRENT_USER->get_id()
            ]
         ));
         if($review_exists > 0)
            $context['display_review_form'] = false;
      }

      return $context;
   }
}
