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

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


class CategoryController extends \BaseController {

	/**
	 * Constructor
	 */
	public function __construct() {
        View::share('active_module', 'categories');
    }


   	public function getIndex()
	{
		Acl::canOrFail('categories', 'view');
		return View::make('categories::index');
	}


	/**
	 * Genera el Json con todas las categorías.
	 * @return string Json con datos para datatables
	 */
	public function getTablaAjax()
	{
		Acl::canOrFail('categories', 'view');
		$datas 		= Category::select('title', 'category_parent', 'created_at', 'updated_at', 'id');
		//$options 	= ;
		return Datatables::of($datas)
				->edit_column('title', 		'{{ $title }} <input type="hidden" class="id" value="{{ $id }}" >')
				->edit_column('category_parent', 	'{{ App\Modules\Backend\Categories\Models\Category::findName($category_parent) }}')
				->make();
	}


	public function getAdd()
	{
		Acl::canOrFail('categories', 'create');
		$category = new Category();
		$categories = Category::lists('title', 'id');
		$categories[0] = trans('categories::label.without_parent');
		return View::make('categories::category')
				->with('title', trans('categories::label.add_category'))
				->with('category', $category)
				->with('categories', $categories)
				->with("formOptions", array("role" 	=> "form", 
					"id" 		=> "frmPrincipal", 
					"class" 	=> "form-horizontal",
					"method" 	=> "POST",
					"files"		=> true,
					"url" 		=> url("admin/categories/add/")));
	}


	public function postAdd()
	{
		Acl::canOrFail('categories', 'create');
		$data = Input::all();
		$rules = array(
            'title'  => 'required',
            '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::hasFile('image') && !Input::file("image")->isValid())
        {
        	Alert::message(trans('dashboard::message.file_overflow', array('file' => Input::file("image")->getClientOriginalName())), 'danger');
        	return Redirect::to('admin/categories/add')
        			->withInput();
        }
        else if($validator->passes())
        {
        	$category 			= new Category($data);
        	$category->image 	= '';
        	if(Input::hasFile('image')) {
	    		$file 	= Input::file("image");
	    		$dir 	= "files/";
	    		$name 	= Innfile::getUniqueFileName($dir, $file->getClientOriginalName());

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

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

	}


	public function getEdit($id)
	{
		Acl::canOrFail('categories', 'update');
		$category = Category::find($id);
		$categories = Category::where('id', '<>', $category->id)->lists('title', 'id');
		$categories[0] = trans('categories::label.without_parent');
		if(!$category)
		{
			Alert::message(trans('dashboard::message.element_not_found'), 'danger');
			return Redirect::to('admin/categories');
		}
		return View::make('categories::category')
				->with('title', trans('categories::label.edit_category'))
				->with('category', $category)
				->with('categories', $categories)
				->with("formOptions", array("role" 	=> "form", 
					"id" 		=> "frmPrincipal", 
					"class" 	=> "form-horizontal",
					"method" 	=> "PUT",
					"files"		=> true,
					"url" 		=> url("admin/categories/edit/".$category->id)));
	}


	public function putEdit($id)
	{
		Acl::canOrFail('categories', 'update');
		$category 		= Category::find($id);
		$category_aux 	= Category::find($id);
		if(!$category)
		{
			Alert::message(trans('dashboard::message.element_not_found'), 'danger');
			return Redirect::to('admin/categories');
		}
		$data = Input::all();
		$rules = array(
            'title'  	=> 'required',
            '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('image') && !Input::file("image")->isValid())
        {
        	Alert::message(trans('dashboard::message.file_overflow', array('file' => Input::file("image")->getClientOriginalName())), 'danger');
        	return Redirect::to('admin/categories/edit/'.$category->id)
        			->withInput();
        }
        else if($validator->passes())
        {
        	$category->fill($data);
        	$category->image = $category_aux->image;
        	if($category->image == '' || Input::has('change-intro-image'))
        	{
        		$category->image 	= '';
	        	if(Input::hasFile('image')) {
		    		$file 	= Input::file("image");
		    		$dir 	= "files/";
		    		$name 	= Innfile::getUniqueFileName($dir, $file->getClientOriginalName());

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

        	
        	

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

	}


	public function deleteEdit($id)
	{
		Acl::canOrFail('categories', 'delete');
		$category = Category::find($id);
		if(!$category)
		{
			Alert::message(trans('dashboard::message.element_not_found'), 'danger');
			return Redirect::to('admin/categories');
		}

		$category->delete();
		Alert::message(trans('categories::message.deleted_category'));
		return Redirect::to('admin/categories');
	}
}