<?php

use Orm\Model;

/**
 * SETI Consultyn S.L.
 * www.seticonsultyn.es
 *
 * Copyright(c) 2011-2013
 *
 * @author    SETI Consultyn S.L. <contacto@seticonsultyn.es>
 * @copyright 2011-2013 SETI Consultyn S.L. http://seticonsultyn.com/copyright.txt
 * @license   SETI Consultyn Software License <license.txt>
 * @link      http://seticonsultyn.es
 */
class Model_Recipe extends Model{
	use  \Trait_InutraliaWS;

    protected static $_table_name = 'recipes';

    protected static $_primary_key = array('id');

    protected static $_has_many = array(
        'ingredients' => array(
            'key_from'       => 'id',
            'key_to'         => 'recipe_local_id',
            'model_to'       => 'Model_Ingredient',
            'cascade_delete' => false,
	        'conditions'     => array(
	        	'where'    => array('used' => 'N'),
		        'order_by' => array('used' => 'DESC'),
		        'group_by' => 'ingredient_id'
	        )
        ),
    );

    public static function get_recipes_current_week()
    {
    	//Devolvemos recetas guardadas en la base de datos que correspondan a esta vista.
	    return self::recipes_current_week()->get();
    }

	public static function recipes_current_week()
	{
		//Devolvemos recetas guardadas en la base de datos que correspondan a esta vista.
		return self::query()->where('week_year', date('W'))->where('year', date('Y'))->where('user_id', \Fuel\Core\Session::get('user_id'));
	}

	public function load_ingredients()
    {
    	if($this->loaded=='S' ||  count($this->ingredients)>0 )
	    {
		    return false;
	    }

	    try
	    {
	    	\DB::start_transaction();

			$recipe = $this->ws_recipe_get($this->recipe_id);

			if(!$recipe)
				return array();

			foreach ($recipe->ingredients as $ingredientRecipe)
	        {
	            $ingredient = Model_Ingredient::forge();

	            $ingredient->ingredient_id = $ingredientRecipe->id;

		        $ingredient->desc          = $ingredientRecipe->name;

		        $ingredient->used          = 'N';

		        $ingredient->created_at    = date("Y-m-d H:i:s");

		        $this->ingredients[]       =  $ingredient;
	        }

	        $this->loaded = 'S';

	        $this->save(true);

	    }
	    catch (Exception $e)
	    {
	    	Log::error($e->getMessage());
	    	\DB::rollback_transaction();
	    	return false;
	    }

		\DB::commit_transaction();

    	return $this->ingredients;



    }
}