<?php namespace App\Modules\Backend\Articles\Controllers;

use Auth, Input, Redirect, View, DB, Datatables, Validator, Innfile, Hash, Alert, Acl, Dashboard;
use \App\Modules\Backend\Articles\Models\Article;
use \App\Modules\Backend\Categories\Models\Category;
use \App\Modules\Backend\Users\Models\User;


class ArticleController extends \BaseController {

	/**
	 * Constructor
	 */
	public function __construct() {
        View::share('active_module', 'articles');
        View::share('galleryTypes', ['video' => trans('articles::galleries.video'), 'image' => trans('articles::galleries.image')]);
    }

	/**
	 * Ejecutado cuando acceden a /admin/users
	 * @return string Muestra la pantalla con todos los usuarios registrados en el sistema.
	 */
	public function getIndex($id)
	{
		Acl::canOrFail('articles', 'view');
		$category = Category::findOrFail($id);
		return View::make('articles::index', compact('category'));
	}


	/**
	 * Genera el Json con todos los articulos.
	 * @return string Json con datos para datatables
	 */
	public function getTablaAjax($id)
	{
		Acl::canOrFail('articles', 'view');
		$category = Category::findOrFail($id);
		$datas 		= Article::select('title', 'created_by', 'created_at', 'updated_at', 'id', 'state')
						->where('category_id', $category->id);
		//$options 	= ;
		return Datatables::of($datas)
				->edit_column('title', 		'{{ $title }} <input type="hidden" class="id" value="{{ $id }}" >')
				->edit_column('created_by', '{{ \App\Modules\Backend\Users\Models\User::find($created_by)->name }} ')
				//->edit_column('id',   '@if($active==1)<span class="label label-success">'.trans('users::label.active').'</span> @else <span class="label label-danger">'.trans('users::label.inactive').'</span>@endif')
				->make();
	}


	/**
	 * Muestra el formulario para crear un nuevo artículo
	 * @return string Vista
	 */
	public function getAdd($id)
	{
		Acl::canOrFail('articles', 'create');
		$category = Category::findOrFail($id);
		$user 						= Auth::user();
		$article 					= new Article();		
		$article->created 			= date('Y-m-d');
		$article->category_id		= $category->id;
		$article->created_by 		= $user->id;
		$article->name_created_by 	= $user->name;
		return View::make('articles::article')
				->with('title', trans('articles::label.add_article'))
				->with('article', $article)
				->with('category', $category)
				->with('gallery_items', array())
				->with('categories', Category::lists('title', 'id'))
				->with('states', Article::getStates())
				->with('languages', Dashboard::getLanguagesList())
				->with("formOptions", array("role" 	=> "form", 
					"id" 		=> "frmPrincipal", 
					"class" 	=> "form-horizontal",
					"method" 	=> "POST",
					"files"		=> true,
					"url" 		=> url("admin/articles/add/")));
	}


	/**
	 * Guarda un nuevo artículo
	 * @return string Vista
	 */
	public function postAdd()
	{
		Acl::canOrFail('articles', 'create');
		$data = Input::all();
		$rules = array(
            'title'  		=> 'required',
            'created'   	=> 'required',
            'created_by'  	=> 'required|exists:users,id',
            'intro_image'  	=> 'mimes:jpeg,gif,png',
            'large_image'  	=> 'mimes:jpeg,gif,png'
        );

        $category_id = Input::get('category_id');

        $validator = Validator::make($data, $rules);

        // Checamos si se envío un archivo y si este marco un error por el tamaño.
        if(Input::hasFile('intro_image') && !Input::file("intro_image")->isValid())
        {
        	Alert::message(trans('dashboard::message.file_overflow', array('file' => Input::file("intro_image")->getClientOriginalName())), 'danger');
        	return Redirect::to('admin/articles/add/'.$category_id)
        			->withInput();
        }
        else if(Input::hasFile('large_image') && !Input::file("large_image")->isValid())
        {
        	Alert::message(trans('dashboard::message.file_overflow', array('file' => Input::file("large_image")->getClientOriginalName())), 'danger');
        	return Redirect::to('admin/articles/add/'.$category_id)
        			->withInput();
        }
        else if($validator->passes())
        {
        	$article 				= new Article($data);
        	$article->intro_image 	= '';
        	if(Input::hasFile('intro_image')) {
	    		$file 	= Input::file("intro_image");
	    		$dir 	= "files/";
	    		$name 	= Innfile::getUniqueFileName($dir, $file->getClientOriginalName());

	    		if($file->move($dir, $name)) {
	    			$article->intro_image = $dir.$name;
	    		}
	    		else {
	    			Alert::message(trans('dashboard::message.error'), 'danger');
	    			return Redirect::to('admin/articles/add/'.$category_id)
	        			->withInput();
	    		}
        	}

        	$article->large_image 	= '';
        	if(Input::hasFile('large_image')) {
	    		$file 	= Input::file("large_image");
	    		$dir 	= "files/";
	    		$name 	= Innfile::getUniqueFileName($dir, $file->getClientOriginalName());

	    		if($file->move($dir, $name)) {
	    			$article->large_image = $dir.$name;
	    		}
	    		else {
	    			Alert::message(trans('dashboard::message.error'), 'danger');
	    			return Redirect::to('admin/articles/add/'.$category_id)
	        			->withInput();
	    		}
        	}

        	// Gallery
        	if(Input::has('galleryItemTitle'))
        	{
        		$galleryItems = array();
        		$titles 	= Input::get('galleryItemTitle');
        		$types 		= Input::get('galleryItemType');
        		$resources 	= Input::get('galleryItemResource');

        		foreach ($titles as $key => $value) {
        			$galleryItems[] = [
        								'title' 	=> $value,
        								'type' 		=> $types[$key],
        								'resource' 	=> $resources[$key]
        							];
        		}

        		$article->gallery_items = json_encode($galleryItems);
        	}
        	else
        	{
        		$article->gallery_items = '{}';
        	}

        	if($article->save())
        	{
        		Alert::message(trans('articles::message.added_article'), 'success');
        		return Redirect::to('admin/articles/edit/'.$article->id);
        	}
        	else {
        		Alert::message(trans('dashboard::message.error'), 'danger');
        		return Redirect::to('admin/articles/add/'.$category_id)
        			->withInput();
        	}
        }
        else
        {
        	Alert::message($validator, 'danger');
        	return Redirect::to('admin/articles/add/'.$category_id)
        			->withInput();
        }

	}



	/**
	 * Muestra el formulario para editar un artículo
	 * @return string Vista
	 */
	public function getEdit($id)
	{
		Acl::canOrFail('articles', 'update');
		$article = Article::find($id);
		if(!$article)
		{
			Alert::message(trans('dashboard::message.element_not_found'), 'danger');
			return Redirect::to('admin/articles');
		}
		$user 						= User::find($article->created_by);
		$article->name_created_by 	= $user->name;

		$gallery_items = array();
		if(!empty($article->gallery_items))
		{
			$gallery_items = json_decode($article->gallery_items);
			foreach ($gallery_items as &$item) {
				if($item->type == 'image')
				{
					$item->url 		= $item->resource;
					$item->image 	= $item->resource;
				}
				else
				{
					$item->image	= 'http://img.youtube.com/vi/'.$item->resource.'/0.jpg';
					$item->url 		= 'https://www.youtube.com/watch?v='.$item->resource;
				}
			}
		}
		//return $article->publish_up->timestamp;

		return View::make('articles::article')
				->with('title', trans('articles::label.edit_article'))
				->with('article', $article)
				->with('category', $article->category)
				->with('gallery_items', $gallery_items)
				->with('categories', Category::lists('title', 'id'))
				->with('states', Article::getStates())
				->with('languages', Dashboard::getLanguagesList())
				->with("formOptions", array("role" 	=> "form", 
					"id" 		=> "frmPrincipal", 
					"class" 	=> "form-horizontal",
					"method" 	=> "PUT",
					"files"		=> true,
					"url" 		=> url("admin/articles/edit/".$article->id)));
	}


	/**
	 * Guarda los cambios de un artículo.
	 * @return string Vista
	 */
	public function putEdit($id)
	{
		Acl::canOrFail('articles', 'update');
		$article = Article::find($id);
		$article_aux = Article::find($id);
		if(!$article)
		{
			Alert::message(trans('dashboard::message.element_not_found'), 'danger');
			return Redirect::to('admin/articles');
		}
		$data = Input::only('title', 'intro_text', 'full_text', 'state', 'created_by', 'created_by_alias', 'category_id', 'created', 'publish_up', 'publish_down', 'metakey', 'metadesc', 'language', 'intro_image', 'large_image');
		$rules = array(
            'title'  		=> 'required',
            'created'   	=> 'required',
            'created_by'  	=> 'required|exists:users,id',
            'intro_image'  	=> 'mimes:jpeg,gif,png',
            'large_image'  	=> 'mimes:jpeg,gif,png'
        );

        $validator = Validator::make($data, $rules);

        // Checamos si se envío un archivo y si este marco un error por el tamaño.
        if(Input::has('change-intro-image') && Input::hasFile('intro_image') && !Input::file("intro_image")->isValid())
        {
        	Alert::message(trans('dashboard::message.file_overflow', array('file' => Input::file("intro_image")->getClientOriginalName())), 'danger');
        	return Redirect::to('admin/articles/edit/'.$article->id)
        			->withInput();
        }
        else if(Input::has('change-large-image') && Input::hasFile('large_image') && !Input::file("large_image")->isValid())
        {
        	Alert::message(trans('dashboard::message.file_overflow', array('file' => Input::file("large_image")->getClientOriginalName())), 'danger');
        	return Redirect::to('admin/articles/edit/'.$article->id)
        			->withInput();
        }
        else if($validator->passes())
        {
        	$article->fill($data);
        	$article->intro_image = $article_aux->intro_image;
        	$article->large_image = $article_aux->large_image;
        	if($article->intro_image == '' || Input::has('change-intro-image'))
        	{
        		$article->intro_image 	= '';
	        	if(Input::hasFile('intro_image')) {
		    		$file 	= Input::file("intro_image");
		    		$dir 	= "files/";
		    		$name 	= Innfile::getUniqueFileName($dir, $file->getClientOriginalName());

		    		if($file->move($dir, $name)) {
		    			$article->intro_image = $dir.$name;
		    		}
		    		else {
		    			Alert::message(trans('dashboard::message.error'), 'danger');
		    			return Redirect::to('admin/articles/edit/'.$article->id)
		        			->withInput();
		    		}
	        	}
        	}

        	if($article->large_image == '' || Input::has('change-large-image'))
        	{
        		$article->large_image 	= '';
	        	if(Input::hasFile('large_image')) {
		    		$file 	= Input::file("large_image");
		    		$dir 	= "files/";
		    		$name 	= Innfile::getUniqueFileName($dir, $file->getClientOriginalName());

		    		if($file->move($dir, $name)) {
		    			$article->large_image = $dir.$name;
		    		}
		    		else {
		    			Alert::message(trans('dashboard::message.error'), 'danger');
		    			return Redirect::to('admin/articles/edit/'.$article->id)
		        			->withInput();
		    		}
	        	}
        	}


        	if(Input::has('galleryItemTitle'))
        	{
        		$galleryItems = array();
        		$titles 	= Input::get('galleryItemTitle');
        		$types 		= Input::get('galleryItemType');
        		$resources 	= Input::get('galleryItemResource');

        		foreach ($titles as $key => $value) {
        			$galleryItems[] = [
        								'title' 	=> $value,
        								'type' 		=> $types[$key],
        								'resource' 	=> $resources[$key]
        							];
        		}

        		$article->gallery_items = json_encode($galleryItems);
        	}
        	else
        	{
        		$article->gallery_items = '{}';
        	}
        	


        	if($article->save())
        	{
        		Alert::message(trans('articles::message.edited_article'), 'success');
        		return Redirect::to('admin/articles/edit/'.$article->id);
        	}
        	else {
        		Alert::message(trans('dashboard::message.error'), 'danger');
        		return Redirect::to('admin/articles/edit/'.$article->id)
        			->withInput();
        	}
        }
        else
        {
        	Alert::message($validator, 'danger');
        	return Redirect::to('admin/articles/edit/'.$article->id)
        			->withInput();
        }

	}


	/**
	 * Elimina a un artículo.
	 * @return  View vista
	 */
	public function deleteEdit($id)
	{
		Acl::canOrFail('articles', 'delete');
		$article = Article::find($id);
		$category = $article->category;
		if(!$article)
		{
			Alert::message(trans('dashboard::message.element_not_found'), 'danger');
			return Redirect::to('admin/articles');
		}

		$article->delete();
		Alert::message(trans('articles::message.deleted_article'));
		return Redirect::to('admin/articles/'.$category->id);
	}

}