<?php

namespace Lycoreco\Apps\Recipes\Controllers;

use Exception;
use Lycoreco\Apps\Recipes\Models\RecipeModel;
use Lycoreco\Includes\BaseController;
use Lycoreco\Apps\Recipes\Models\CategoryModel;
use Lycoreco\Apps\Recipes\Models\IngredientInRecipeModel;
use Lycoreco\Includes\Model\ValidationError;

class SingleSubmitController extends BaseController
{
    protected $template_name = APPS_PATH . '/Recipes/Templates/single-submit.php';
    protected $allow_role = 'user';

    protected function post()
    {
        $title = $_POST['title'] ?? '';
        $description = $_POST['description'] ?? '';
        $image = $_FILES['image'] ?? null;
        $estimated_time = $_POST['est-time'] ?? 0;
        $estimated_price = $_POST['est-price'] ?? 0;
        $category_id = $_POST['category'] ?? null;

        $ingredient_ids = $_POST['ing-id'] ?? [];
        $ingredient_counts = $_POST['ing-count'] ?? [];
        
        $recipe = new RecipeModel();
        $recipe->field_title = $title;
        $recipe->field_instruction = $description;

        if($image) {
            $file_url = upload_file($image, RecipeModel::get_table_name() . '/', 'image');
            $recipe->field_image_url = $file_url;
        }
        $recipe->field_estimated_time = $estimated_time;
        $recipe->field_estimated_price = $estimated_price;
        $recipe->field_category_id = $category_id;
        $recipe->field_author_id = CURRENT_USER->get_id();
        $recipe->field_status = 'pending';

        try {
            $recipe->save();
        }
        catch (ValidationError $ex) {
            $this->context['error_message'] = $ex->getMessage();
        }
        catch (Exception $ex) {
            $this->context['error_message'] = "Unexpected error";
        }

        for ($i = 0; $i < count($ingredient_ids); $i++) { 
            $ing_id = $ingredient_ids[$i];
            $ing_count = (int) $ingredient_counts[$i];

            if($ing_count <= 0)
                continue;

            $relation = new IngredientInRecipeModel();
            $relation->field_ingredient_id = $ing_id;
            $relation->field_amount = $ing_count;
            $relation->field_recipe_id = $recipe->get_id();

            $relation->save();
        }

        redirect_to($recipe->get_absolute_url());
    }

    public function get_context_data()
    {
        $context = parent::get_context_data();
        
        $context['category_options'] = CategoryModel::get_cat_values();


        return $context;
    }
}