<?php

class ProductsController extends BaseController {

	protected $rules		 = array(
			'mark' => 'numeric|min:1',
			'name' => 'required'
	);
	protected $messages	 = array(
			'required' => 'Неообходимо ввести название',
			'min'			 => 'Укажите марку',
			'numeric'	 => 'Цена вводится цифрами'
	);
	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');
		}

		$this->marks = array('0' => '--Выберите марку--');
		foreach (Mark::orderBy('name', 'ASC')->get() as $item) {
			$this->marks[$item->id] = $item->name;
		}

		$this->yearsStart = array();
		for ($year = date('Y'); $year >= 1950; $year--) {
			$this->yearsStart[$year] = $year;
		}

		$this->yearsEnd					 = array();
		$this->yearsEnd['н.в.']	 = 'н.в.';
		for ($year = date('Y'); $year >= 1950; $year--) {
			$this->yearsEnd[$year] = $year;
		}
	}

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

	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create() {
		return View::make('products.create')
										->with('marks', $this->marks)
										->with('yearsStart', $this->yearsStart)
										->with('yearsEnd', $this->yearsEnd)
										->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('ProductsController@create', array($this->project->id))
											->withInput()
											->withErrors($validation->errors());
		}
		else {
			$noProduction = 0; 
			if (isset($input['no-production'])){
				if ($input['no-production'] == 'on'){ 
				  $noProduction = 1; 
			  }
			}
			$input	 = Input::all();
			$product = new Product(array(
					'mark_id'		    => e($input['mark']),
					'name'			    => e($input['name']),
					'year_start'    => e($input['year_start']),
					'year_end'	    => e($input['year_end']),
					'no_production' => $noProduction
			));
			$product = $this->project->products()->save($product);
			foreach ($input['price'] as $key => $value) {
				$productGroupId = 0;
					if(isset($input['product_group'][$key])){
					  $productGroupId = e($input['product_group'][$key]);
					}
				ProductPrice::create(array(
						'product_id'			 => e($product['id']),
						'product_type_id'	 => e($key),
						'price'						 => e($value),
						'price_back'			 => e($input['price_back'][$key]),
						'price_opt'				 => e($input['price_opt'][$key]),
						'product_group_id' => $productGroupId,
						'plates'					 => e($input['plates'][$key]),
						'hooks'						 => e($input['hooks'][$key]),
						'splates'					 => e($input['splates'][$key])
				));
			}
			return Redirect::action('ProductsController@index', array($this->project->id));
		}
	}

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

		return View::make('products.edit')
										->with('marks', $this->marks)
										->with('yearsStart', $this->yearsStart)
										->with('yearsEnd', $this->yearsEnd)
										->with('product', $product)
										->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('ProductsController@edit', array($projectId, $id))
											->withInput()
											->withErrors($validation->errors());
		}
		else {
			$product = Product::find($id);
			if ($product == null || !is_numeric($id) || $product->project_id != $projectId) {
				return \App::abort(404);
			}
			$noProduction = 0; 
			if (isset($input['no-production'])){
				if ($input['no-production'] == 'on'){ 
				  $noProduction = 1; 
			  }
			}
			$input							    = Input::all();
			$product->mark_id		    = e($input['mark']);
			$product->no_production	= $noProduction;
			$product->name			    = e($input['name']);
			$product->year_start    = e($input['year_start']);
			$product->year_end	    = e($input['year_end']);
			$product->save();

			foreach ($input['price'] as $key => $value) {
				$price = ProductPrice::whereProductId($product->id)->whereProductTypeId($key)->first();
				if ($price) {
					$productGroupId = 0;
					if(isset($input['product_group'][$key])){
					  $productGroupId = e($input['product_group'][$key]);
					}
					$price->price			       = e($value);
					$price->price_back       = e($input['price_back'][$key]);
					$price->price_opt	       = e($input['price_opt'][$key]);
					$price->product_group_id = $productGroupId;
					$price->plates		       = e($input['plates'][$key]);
					$price->hooks			       = e($input['hooks'][$key]);
					$price->splates		       = e($input['splates'][$key]);
					$price->save();
				}
				else {
					$productGroupId = 0;
					if(isset($input['product_group'][$key])){
					  $productGroupId = e($input['product_group'][$key]);
					}

					ProductPrice::create(array(
							'product_id'			 => e($product->id),
							'product_type_id'	 => e($key),
							'price'						 => e($value),
							'price_back'			 => e($input['price_back'][$key]),
							'product_group_id' => $productGroupId,
							'price_opt'				 => e($input['price_opt'][$key]),
							'plates'					 => e($input['plates'][$key]),
							'hooks'						 => e($input['hooks'][$key]),
							'splates'					 => e($input['splates'][$key])
					));
				}
			}
			return Redirect::action('ProductsController@index', array($projectId));
		}
	}
	
	// Обновление кол-ва на складе
	public function updateQuant($projectId, $productId, $productTypeId, $type) {
		$product = Product::find($productId);
			if ($product == null || !is_numeric($productId) || $product->project_id != $projectId) {
				$response = array( 'status' => 'fail');
				return Response::json($response);
			}
	  $productType = ProductType::find($productTypeId);
			if ($product == null || !is_numeric($productTypeId) || $product->project_id != $projectId) {
				$response = array( 'status' => 'fail');
				return Response::json($response); 
		  }	

		$productStorageType = ProductQuant::where('product_id', $productId)->where('product_type_id', $productTypeId)->first();	
			
		if ($productStorageType != null) {
		  if ($type == "up") {
				$oldQuant          = $productStorageType->quant;
				$oldQuantBlocked   = $productStorageType->quant_blocked;
        $productStorageType->increment('quant');
				// $productId = null, $productGroupId = null, $productTypeId = null, $addedQuant = null, $oldQuant = null, $addedQuantBlocked = null, $oldQuantBlocked = null, $message
				$productStorageType->saveProductQuantHistory($productId, 0, $productTypeId, 1, $oldQuant, 0, $oldQuantBlocked, 'Увеличено вручную в списке продуктов (продукт)');
		  }
      elseif ($type == "down") {
				$oldQuant          = $productStorageType->quant;
				$oldQuantBlocked   = $productStorageType->quant_blocked;
		    $productStorageType->decrement('quant');
				$productStorageType->saveProductQuantHistory($productId, 0, $productTypeId, -1, $oldQuant, 0, $oldQuantBlocked, 'Уменьшено вручную в списке продуктов (продукт)');
		  }
		} else {
		  $productQuant = ProductQuant::create(array('quant'=>1));
		  $productQuant->product()->associate($product);
		  $productQuant->productType()->associate($productType);
		  $productQuant->save();

			$productQuant->saveProductQuantHistory($productId, 0, $productType->id, 1, 0, 0, 0, 'Первично увеличено вручную в списке продуктов (продукт)');
		}
		$response = array( 'status' => 'success');
		return Response::json($response); 
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($projectId, $id) {
		Product::destroy($id);
		return Redirect::action('ProductsController@index', array($projectId));
	}

	public function export($projectId) {
		Session::set('products_projectId', $projectId);
		$fileName = "LegatonProducts-" . date('Y-m-d');
		Excel::create($fileName, function($excel) {
			$excel->sheet('Лист1', function($sheet) {
				$projectId = Session::get('products_projectId');
				$project	 = Project::find($projectId);
				if ($project) {
					$sheet->loadView('products.export')->with('project', $project);
				}
			});
		})->store('xlsx');

		return Response::download('../app/storage/exports/' . $fileName . '.xlsx');
	}

}
