<?php

class ProductionController extends BaseController {

	/**
	 * Constructor
	 */
	public function __construct() {
		// Establish Filters
		$this->beforeFilter('auth');
		$this->beforeFilter('hasRole:' . Role::ROLE_PRODUCTION, array('only' => array('index', 'process', 'success')));
		$this->beforeFilter('hasRole:' . Role::ROLE_PACKING, array('only' => array('packing', 'packed')));
	}

	public function index() {
		$user = User::find(Sentry::getUser()->id);

		$productions1	 = Production::whereNull('production_start_at')->orderBy('id', 'ASC')->get();
		$productions2	 = Production::whereNotNull('production_start_at')->whereNull('production_end_at')->orderBy('id', 'ASC')->get();

		return View::make('production.index')
										->with('user', $user)
										->with('productions1', $productions1)
										->with('productions2', $productions2)
										->with('months', $this->months);
	}

	public function productionPrint($id) {
		return View::make('production.print')
										->with('production', Production::find($id));
	}

	public function productionPrintSuccess($id) {
		$input['success'] = 1;
		return View::make('production.print')
										->with('input', $input)
										->with('production', Production::find($id));
	}

	public function packing() {
		$user = User::find(Sentry::getUser()->id);

		$partners = Partner::whereIn('status', array(Partner::STATUS_DELIVERY_AFTER_PRODUCTION_SUCCESS, Partner::STATUS_DELIVERY_BEFORE_PRODUCTION_SUCCESS, Partner::STATUS_DELIVERY_FRANCHISEES_PRODUCTION_SUCCESS))->get();

		return View::make('production.index')
										->with('user', $user)
										->with('packing', true)
										->with('partners', $partners)
										->with('months', $this->months);
	}

	public function sizing() {
		$input = Input::all();

		if (!isset($input['partnerId']) || !isset($input['productionMasterId'])) {
			$response = array(
					'status' => 'fail'
			);
			return Response::json($response);
		}

		$production = Production::whereId($input['partnerId'])->whereNull('production_start_at')->first();
		if ($production == null || !is_numeric($input['partnerId'])) {
			$response = array(
					'status'	 => 'fail',
					'message'	 => 'Заказ не найден'
			);
			return Response::json($response);
		}

		$comment = '';
		foreach (Production::wherePartnerId($production->partner_id)->whereNotNull('production_start_at')->whereNull('production_end_at')->get() as $item) {
			$comment .= "ШТОРКА В ПРОИЗВОДСТВЕ: №{$item->order_id}, {$item->name}\n";
		}
		foreach (Production::wherePartnerId($production->partner_id)->whereNotNull('production_start_at')->whereNotNull('production_end_at')->get() as $item) {
			$comment .= "ШТОРКА УЖЕ ГОТОВА: №{$item->order_id}, {$item->name}\n";
		}
		if ($comment != '') {
			$production->partner->comment = $comment . $production->partner->comment;
		}
		$production->partner->status						 = Partner::STATUS_SIZING;
		$production->partner->salenextdatetime	 = DB::raw('NOW()');
		$production->partner->need_size_message	 = $production->name;
		$production->partner->save();

		$production->partner->productions()->delete();

		$response = array(
				'status' => 'success'
		);

		return Response::json($response);
	}

	public function process() {
		$input = Input::all();

		if (!isset($input['partnerId']) || !isset($input['productionMasterId'])) {
			$response = array(
					'status' => 'fail'
			);
			return Response::json($response);
		}

		$production = Production::whereId($input['partnerId'])->whereNull('production_start_at')->first();
		if ($production == null || !is_numeric($input['partnerId'])) {
			$response = array(
					'status'	 => 'fail',
					'message'	 => 'Заказ не найден'
			);
			return Response::json($response);
		}

		$production->production_start_at	 = DB::raw('NOW()');
		$production->production_master_id	 = $input['productionMasterId'];
		$production->save();

		$message											 = "Началось производство комплекта: №{$production->order_id}, {$production->name}, " . ProductionMaster::find($input['productionMasterId'])->name;
		$partner											 = $production->partner;
		$partner->production_master_id = $input['productionMasterId'];
		if ($partner->status == Partner::STATUS_PRODUCTION_WAIT) { // в производство берут первый комплект заказа
			$partner->status = Partner::STATUS_PRODUCTION_PROCESS;
			$partner->save();
			$partner->saveHistory($message);
		}
		else if ($partner->status == Partner::STATUS_PRODUCTION_PROCESS) { // последующие
			$partner->saveHistory($message);
		}

		$response = array(
				'status' => 'success'
		);

		return Response::json($response);
	}

	public function success() {
		$input = Input::all();

		if (!isset($input['partnerId'])) {
			$response = array(
					'status' => 'fail'
			);
			return Response::json($response);
		}

//		$production = Production::whereId($input['partnerId'])->whereNotNull('production_start_at')->whereNull('production_end_at')->first();
		$production = Production::whereId($input['partnerId'])->first();
		if ($production == null || !is_numeric($input['partnerId'])) {
			$response = array(
					'status'	 => 'fail',
					'message'	 => 'Заказ не найден'
			);
			return Response::json($response);
		}
		if (!$production->production_start_at) {
			$production->production_start_at = DB::raw('NOW()');
		}
		$production->production_end_at = DB::raw('NOW()');
		$production->save();

		$partner = $production->partner;

		//--> готов очередной комплект
		if ($production->production_master_id) { // производился
			$message = "Закончилось производство комплекта: №{$production->order_id}, {$production->name}, " . ProductionMaster::find($production->production_master_id)->name;
		}
		else { // взят со склада
			$message = "Взят со склада комплект: №{$production->order_id}, {$production->name}";
		}
		$partner->saveHistory($message);
		//<--
		// все комплекты готовы
		if (!$partner->productions()->whereNull('production_end_at')->count()) {
//			if ($partner->status == Partner::STATUS_PRODUCTION_PROCESS) {
//				$partner->status = Partner::STATUS_PRODUCTION_SUCCESS;
				$partner->status = Partner::STATUS_REGISTRATION;
				$partner->save();
				$message				 = "Заказ №{$production->partner_id}, " . Partner::find($production->partner_id)->name . " - полностью готов к отправке";
//			}
				
				$orderContent = '';
					foreach ($partner->getCart() as $item) {
						foreach ($item as $item2) {
							if ($item2['quant'] > 0) {
								$orderContent .= $item2['name'] . ',' . $item2['quant'] . 'компл. <br>';
							}
						}
					}
				
			$partner->user->changeMoney(-$partner->franchisees_cost, "Списание за производство штор, {$orderContent}");
			if ($partner->user->hasRole(Role::ROLE_FRANCHISEES)) {
				// состав заказа
				try {
					$orderContent = '';
					foreach ($partner->getCart() as $item) {
						foreach ($item as $item2) {
							if ($item2['quant'] > 0) {
								$orderContent .= $item2['name'] . ',' . $item2['quant'] . 'компл. <br>';
							}
						}
					}
					$partner->user->createNews('Закончилось производство заказа №' . $production->partner_id, '<br>' . Partner::find($production->partner_id)->name . '.<br><b> Состав заказа:</b><br> ' . $orderContent);
				}
				catch (Exception $e) {

				}
			}
			$partner->saveHistory($message);
		}

		$response						 = array(
				'status' => 'success'
		);
		$productStorageType	 = ProductQuant::where('product_id', $production->product_id)->where('product_type_id', $production->product_type_id)->first();
		if ($productStorageType !== null && $production->production_master_id === 0) { // если было взято со склада
			$productStorageType->decrement('quant');
			$productStorageType->decrement('quant_blocked');
		}
		return Response::json($response);
	}

	public function noStorage() {
		$input = Input::all();

		if (!isset($input['partnerId'])) {
			$response = array(
					'status' => 'fail'
			);
			return Response::json($response);
		}

		$production = Production::whereId($input['partnerId'])->whereNotNull('production_start_at')->whereNull('production_end_at')->first();
		if ($production == null || !is_numeric($input['partnerId'])) {
			$response = array(
					'status'	 => 'fail',
					'message'	 => 'Заказ не найден'
			);
			return Response::json($response);
		}
		$partner													 = $production->partner;
		$production->production_start_at	 = DB::raw('NULL');
		$production->production_master_id	 = DB::raw('NULL');
		$production->save();

		$response	 = array(
				'status' => 'success'
		);
		$message	 = "Нет на складе комплекта: №{$production->order_id}, {$production->name}";
		$partner->saveHistory($message);

		$productStorageType = ProductQuant::where('product_id', $production->product_id)->where('product_type_id', $production->product_type_id)->first();
		if ($productStorageType !== null) {
			$productStorageType->decrement('quant_blocked');
			$productStorageType->decrement('quant');
		}
		return Response::json($response);
	}

	public function packed() {
//		$input = Input::all();
//
//		if (!isset($input['partnerId'])) {
//			$response = array(
//					'status' => 'fail'
//			);
//			return Response::json($response);
//		}
//
//		$partner = Partner::find($input['partnerId']);
//		if ($partner == null || !$partner->statusIsAllow(Partner::ALLOW_PRODUCTION_PACKED) || !is_numeric($input['partnerId'])) {
//			$response = array(
//					'status'	 => 'fail',
//					'message'	 => 'Клиент не найден'
//			);
//			return Response::json($response);
//		}
//
//		if ($partner->status == Partner::STATUS_DELIVERY_AFTER_PRODUCTION_SUCCESS) {
//			$partner->status = Partner::STATUS_DELIVERY_AFTER_REGISTRATION;
//		}
//		elseif ($partner->status == Partner::STATUS_DELIVERY_BEFORE_PRODUCTION_SUCCESS) {
//			$partner->status = Partner::STATUS_DELIVERY_BEFORE_REGISTRATION;
//		}
//		elseif ($partner->status == Partner::STATUS_DELIVERY_FRANCHISEES_PRODUCTION_SUCCESS) {
//			$partner->status = Partner::STATUS_DELIVERY_FRANCHISEES_REGISTRATION;
//		}
//		$partner->salenextdatetime = DB::raw('NOW()');
//		$partner->save();
//		$partner->saveHistory("Заказ упакован");
//
//		$partner->user->changeMoney(-$partner->franchisees_cost, "Списание за производство штор");
//
//		$response = array(
//				'status' => 'success'
//		);

		return Response::json($response);
	}

	public function stat() {
		$user = User::find(Sentry::getUser()->id);

		return View::make('production.stat')
										->with('user', $user)
										->with('masters', ProductionMaster::orderBy('name', 'ASC')->get());
	}

}
