<?php

class ProductsGroupController extends BaseController {

	protected $rules		 = array(
			'name' => 'required'
	);
	protected $messages	 = array(
			'required' => 'Неообходимо ввести название',
	);
	private $project		 = null;

	/**
	 * Constructor
	 */
	public function __construct() {
		$id			 = Request::segment(2);
		$project = Project::find($id);
		if ($project == null || !is_numeric($id)) {
			return \App::abort(404);
		}
		else {
			$this->project = $project;
		}
		// Establish Filters
		if (Sentry::check()) {
			$user = User::find(Sentry::getUser()->id);
			if (!$user->hasAccess('admin')) {
				if (!$user->hasAnyRole(array(Role::ROLE_PROJECTS_EDITOR, Role::ROLE_PRODUCTS_EDITOR))) {
					$this->beforeFilter('hasRole:' . Role::ROLE_PROJECTS_EDITOR);
					$this->beforeFilter('hasRole:' . Role::ROLE_PRODUCTS_EDITOR);
				}
			}
		}
		else {
			$this->beforeFilter('auth');
		}
	}

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index() {
		return View::make('products_group.index')->with('project', $this->project);
	}

	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create() {
		return View::make('products_group.create')->with('project', $this->project);
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store() {
		$input			 = Input::all();
		$validation	 = Validator::make($input, $this->rules, $this->messages);

		if ($validation->fails()) {
			return Redirect::action('ProductsGroupController@create', array($this->project->id))
											->withInput()
											->withErrors($validation->errors());
		}
		else {
			$input	 = Input::all();
			$productGroup	 = new ProductGroup(array(
					'name' => e($input['name'])
			));
			$productGroup	 = $this->project->productGroups()->save($productGroup);
			return Redirect::action('ProductsGroupController@index', array($this->project->id));
		}
	}

	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($projectId, $id) {
		$productGroup = ProductGroup::find($id);
		if ($productGroup == null || !is_numeric($id) || $productGroup->project_id != $projectId) {
			return \App::abort(404);
		}

		$currProducts = ProductPrice::select(DB::raw('product_prices.id,
																								  pt.name AS productType,
																								  p.name AS model,
																								  m.name AS mark'))
																->leftJoin('product_groups as pg', 'product_prices.product_group_id', '=', 'pg.id')
																->leftJoin('product_types as pt', 'product_prices.product_type_id', '=', 'pt.id')
																->leftJoin('products as p', 'product_prices.product_id', '=', 'p.id')
																->leftJoin('marks as m', 'p.mark_id', '=', 'm.id')
																->whereProductGroupId($productGroup->id)
																->where('product_prices.price', '>', 0)
																->orderBy('m.name')
																->get();

		$anotherProducts = ProductPrice::select(DB::raw('product_prices.id,
																										 pt.name AS productType,
																										 pt.id AS productTypeId,
																										 p.name AS model,
																										 m.name AS mark,
																										 pg.name AS productGroupName'))
																	->leftJoin('product_groups as pg', 'product_prices.product_group_id', '=', 'pg.id')
																	->leftJoin('product_types as pt', 'product_prices.product_type_id', '=', 'pt.id')
																	->leftJoin('products as p', 'product_prices.product_id', '=', 'p.id')
																	->leftJoin('marks as m', 'p.mark_id', '=', 'm.id')
																	->whereRaw('(product_group_id <> '.$productGroup->id.' OR product_group_id is null)')
																	->where('product_prices.price', '>', 0)
																	->orderBy('pg.id')
																	->orderBy('m.name')
																	->orderBy('p.name')
																	->get();
		
		$productTypes = ProductType::all();
		
		return View::make('products_group.edit')
										->with('productGroup', $productGroup)
										->with('currProducts', $currProducts)
										->with('anotherProducts', $anotherProducts)
										->with('productTypes', $productTypes)
										->with('project', $this->project);
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($projectId, $id) {
		$input			 = Input::all();
		$validation	 = Validator::make($input, $this->rules, $this->messages);

		if ($validation->fails()) {
			return Redirect::action('ProductsGroupController@edit', array($projectId, $id))
											->withInput()
											->withErrors($validation->errors());
		}
		else {
			$productGroup = ProductGroup::find($id);
			if ($productGroup == null || !is_numeric($id) || $productGroup->project_id != $projectId) {
				return \App::abort(404);
			}
			$productGroup->name	 = e($input['name']);
			$productGroup->save();

			// старые
		  if( isset ($input['curr-product']) ){
				foreach ($input['curr-product'] as $key => $value){
					$currProducts[] = $key;
				} 
				$productPrices = ProductPrice::whereProductGroupId($productGroup->id)
																		 ->whereNotIn('id', $currProducts)
																		 ->get();
				foreach ($productPrices as $productPrice){
					$productPrice->product_group_id = NULL;
					$productPrice->save();
				}
			}else{ // если нет списка с текущими продуктами, то сняты все галочки, удалить все
				$productPrices = ProductPrice::whereProductGroupId($productGroup->id)->get();
				foreach ($productPrices as $productPrice){
					$productPrice->product_group_id = NULL;
					$productPrice->save();
				}
			}

			//новые
			if( isset ($input['another-product']) ){
				foreach ($input['another-product'] as $key => $value){
					$anotherProducts[] = $key;
				} 
				$productPrices = ProductPrice::whereIn('id', $anotherProducts)
																		 ->get();
				foreach ($productPrices as $productPrice){
					$productPrice->product_group_id = $productGroup->id;
					$productPrice->save();
				}
			}
			return Redirect::action('ProductsGroupController@index', array($projectId));
		}
	}

	// Обновление кол-ва шторок по группе на складе
	public function updateQuant($projectId, $productGroupId, $type) {
		$productGroup = ProductGroup::find($productGroupId);
		
		if ($productGroup == null || !is_numeric($productGroupId) || $productGroup->project_id != $projectId) {
			$response = array( 'status' => 'fail');
			return Response::json($response);
		}

		if ($type == "up") {
			$oldQuant = $productGroup->quant;
			$oldQuantBlocked   = $productGroup->quant_blocked;
			$productGroup->increment('quant');
			// $productId = null, $productGroupId = null, $productTypeId = null, $addedQuant = null, $oldQuant = null, $addedQuantBlocked = null, $oldQuantBlocked = null, $message
			$productGroup->saveProductGroupQuantHistory(0, $productGroup->id, 0, 1, $oldQuant, 0, $oldQuantBlocked, 'Увеличено вручную в списке продуктов (группа)');
		}
		elseif ($type == "down") {
			$oldQuant = $productGroup->quant;
			$oldQuantBlocked   = $productGroup->quant_blocked;
			$productGroup->decrement('quant');
			$productGroup->saveProductGroupQuantHistory(0, $productGroup->id, 0, -1, $oldQuant, 0, $oldQuantBlocked, 'Уменьшено вручную в списке продуктов (группа)');
		}
			
		$response = array( 'status' => 'success');
		return Response::json($response);
	}
	
	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($projectId, $id) {
		$productPrices = ProductPrice::whereProductGroupId($id)->get();
		
		foreach ($productPrices as $productPrice){
			$productPrice->product_group_id = NULL;
			$productPrice->save();
		}
		ProductGroup::destroy($id);
		
		return Redirect::action('ProductsGroupController@index', array($projectId));
	}

}