<?php

class UserController extends \BaseController {

	/**
	 * Display a listing of the resource.
	 * GET /user
	 *
	 * @return Response
	 */
	public function index()
	{
		if(!UserRole::has('list_user')) return Redirect::route("dashboard");
		$users = DB::table('users')
	    ->leftJoin('positions', function($join)
	    {
	        $join->on('users.position_id', '=', 'positions.id');
	    })
    ->select('users.*', 'positions.id AS position_id', 'positions.name AS pname')->where("users.id", "<>", 1)->get();
		$master = $this->getMaster();
		return View::make("users.index")
								->withMaster($master)
								->with("users",$users);
	}

	/**
	 * Show the form for creating a new resource.
	 * GET /user/create
	 *
	 * @return Response
	 */
	public function create()
	{
		if(!UserRole::has('create_user')) return Redirect::route("dashboard");
		$stocks = Stock::lists('name','id');
		$stocks[0] = "None";
		$roles = [
			3 	=>	"Admin",
			4   => "Staff"
		];
		if(Branch::getNumber() == 'one') {
			$branches = Branch::take(1)->lists("name","id");
		}else {
			$branches = Branch::all()->lists("name","id");
		}
		$branches[0] = "None";
		$positions = Position::all()->lists("name","id");
		$positions[0] = "None";
		return View::make("users.create")
								->with("branches",$branches)
								->with("roles",$roles)
								->with("stocks",$stocks)
								->with("positions",$positions);
	}

	/**
	 * Store a newly created resource in storage.
	 * POST /user
	 *
	 * @return Response
	 */
	public function store()
	{
		$arr = Input::except('_token');
		/**
		 * Set all select box to null user select none
		 */
		$arr['branch_id'] = (Input::get('branch_id') ? Input::get('branch_id') : null);
		$arr['stock_id'] = (Input::get('stock_id') ? Input::get('stock_id') : null);
		$arr['role_id'] = (Input::get('role_id') ? Input::get('role_id') : null);
		$arr['position_id'] = (Input::get('position_id') ? Input::get('position_id') : null);
		/**
		 * Check Upload File
		 */
    if (Input::hasFile('photo')) {
			$arr['photo'] = \Helper::uploadFile(Input::file('photo'), User::getUploadPath());
    } else {
    	if(!empty(Input::get("image_name"))) {
				$destinationPath = public_path() . DIRECTORY_SEPARATOR.  User::getUploadPath();
    		$imageName = uniqid().".jpg";
				saveImage(Input::get("image_name"),$destinationPath,$imageName);
				$arr['photo'] = User::getUploadPath() .$imageName;
    	} else {
      	$arr['photo'] = User::getUploadPath() .'none.png';
			}
    }
    $arr['password'] = Hash::make(Input::get("password"));
    $inputs = $arr;
    // run the validation rules on the inputs from the form
    $validator = Validator::make(Input::all(), User::$rules);
    $messages = $validator->messages();
    if ($validator->fails()) {
      return Redirect::back()
				->withInput()
				->withErrors($validator)
				->with('message','messages.fail-to-create')
				->with('messageType','danger');
    } else {
      $user = User::create($inputs);
      if ($user) return Redirect::back()
					->withInput()
					->with('message','messages.success-to-create')
					->with('messageType','success');
    }
	}

	/**
	 * Display the specified resource.
	 * GET /user/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		//
	}

	/**
	 * Show the form for editing the specified resource.
	 * GET /user/{id}/edit
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		if(!UserRole::has('edit_user')) return Redirect::route("dashboard");
		//$permissions = PermissionRole::getPermission($user->role_id)->get();
		$stocks = Stock::lists('name','id');
		$stocks[0] = "None";
		$roles = [
			1		=>	"Master",
			3 	=>	"Admin",
			4   => "Staff"
		];
		if(Branch::getNumber() == 'one') {
			$branches = Branch::take(1)->lists("name","id");
		}else {
			$branches = Branch::all()->lists("name","id");
		}
		$branches[0] = "None";
		$positions = Position::all()->lists("name","id");
		$positions[0] = "None";
		$user = User::find($id);
		if(empty($user)) return Redirect::back();
		return View::make("users.edit")
								->with("user",$user)
								->with("roles",$roles)
								->with("branches",$branches)
								->with("stocks",$stocks)
								->with("positions",$positions);
	}

	/**
	 * Update Users
	 * PUT /user/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		$user = User::find($id);
		$arr = Input::except('_token');
		if(Input::get('branch_id') == 0) $arr['branch_id'] = null;
		if(Input::get('stock_id') == 0) $arr['stock_id'] = null;
		if(Input::get('role_id') == 0) $arr['role_id'] = null;
		if(Input::get('position_id') == 0) $arr['position_id'] = null;
    /*
      Check file input if file is given
     */
    if (Input::hasFile('photo'))
    {
      $arr['photo'] = \Helper::uploadFile(Input::file('photo'), User::getUploadPath());
    }
    /*
      Check Webcam Image if User used
     */
    else
    {
      if(!empty(Input::get("image_name"))) {
				$destinationPath = public_path() . DIRECTORY_SEPARATOR. User::getUploadPath();
				$imageName = uniqid().".jpg";
				saveImage(Input::get("image_name"),$destinationPath,$imageName);
				$arr['photo'] = User::getUploadPath() .$imageName;
      } else {
				$arr['photo'] = $user->photo;
			}
    }
    $arr['password'] = Hash::make(Input::get("password"));
    $inputs = $arr;
		$rules = [
			'username' 		=> 'required|unique:users,username,'. $user->id,
      'email' => 'email|unique:users,email,'. $user->id,
      'tel' => 'unique:users,tel,'. $user->id
		];
    $validator = Validator::make(Input::all(), $rules);
    $messages = $validator->messages();

    /*
      Return with Old Input and Error Message If validator is fails
     */

    if ($validator->fails())
    {
      return Redirect::back()
				->withInput()
				->withErrors($validator)
				->with('message','messages.fail-to-update')
				->with('messageType','danger');
    }
    else {
      if ($user->update($inputs)) {
				return Redirect::back()
					->withInput()
					->with('message','messages.success-to-update')
					->with('messageType','success');
			} else {
				return Redirect::back()
					->withInput()
					->with('message','messages.fail-to-update')
					->with('messageType','danger');
			}
    }
	}

	/**
	 * Remove the specified resource from storage.
	 * DELETE /user/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
        return Redirect::back()
        ->with('message','messages.not_allow_to_delete')
        ->with('messageType','warning');
		$user = User::find($id);
		if(empty($user)) return Redirect::back()
											->with('message','messages.fail-to-delete')
											->with('messageType','danger');
		if($user->delete()) {
			return Redirect::back()
			->with('message','messages.success-to-delete')
			->with('messageType','success');
		} else {
			return Redirect::back()
						->with('message','messages.fail-to-delete')
						->with('messageType','danger');
		}
	}
	/**
	 * Create New Master if delete all users
	 * @param  string $username Username
	 * @param  string $password Password
	 * @return mix           		Redirect to Home
	 */
	public function getCreateMaster($username, $password)
	{
		$master = Role::where('role_name', "Master")->first();
	  if (empty($master)) {
	    $role = new Role;
	    $role->role_name = "Master";
	    $role->description  = "Developer";
	    if ($role->save()) {
				$result = Helper::createMaster($username, $password, $role->id);
				if ($result) return Redirect::to('/');
			}
		}
		$result = Helper::createMaster($username, $password, $master->id);
		if ($result) return Redirect::to('/');
	}
	private function getMaster()
	{
		$master = DB::table('users')
							->join('roles', 'roles.id','=', 'users.role_id')
							->select('roles.role_name')
							->where('roles.role_name', "Master")
							->where('users.id', Auth::user()->id)
							->first();
		return $master;
	}
}
