<?php

function cmp($a, $b) {
	return strcmp($a["article"], $b["article"]);
}

class ShipmentsController extends BaseController {

	private $allowCreate = false;
	private $whereProjectId = '';

	/**
	 * Constructor
	 */
	public function __construct() {
		// Establish Filters
		$this->beforeFilter('auth');

		if (Auth::check()) {
			$this->user			 = Auth::user();
			$this->projects	 = $this->user->projects()->whereUsecrm(1)->get();
		}
		parent::__construct();

		if ($this->user && !$this->user->hasAnyRole(array(Role::ROLE_LOGISTICS, Role::ROLE_PROJECT_MANAGER))) {
			$this->beforeFilter('hasRole:' . Role::ROLE_LOGISTICS);
			$this->beforeFilter('hasRole:' . Role::ROLE_PROJECT_MANAGER);
		}

		$shipTime		 = '15:00:00';
		$time				 = date('H:i:s');
		list($hours, $mins, $secs) = explode(':', $shipTime);
		$shipSeconds = ($hours * 3600 ) + ($mins * 60 ) + $secs;
		list($hours, $mins, $secs) = explode(':', $time);
		$seconds		 = ($hours * 3600 ) + ($mins * 60 ) + $secs;

		$this->whereProjectId = "project_id={$this->workProject->id}";
		if (in_array($this->workProject->id, array(20,63))) {
			$this->whereProjectId = "project_id IN (20,63)";
		}

//		if ($seconds > $shipSeconds) {
		$this->allowCreate = true;
//		}
//		$date			 = date('Y-m-d');
//		$shipment	 = Shipment::whereDate($date)->whereTransportType(Partner::TRANSPORT_TYPE_CDEK)->first();
//		if (!$shipment) {
//			Shipment::create(array(
//					'transport_type' => Partner::TRANSPORT_TYPE_CDEK,
//					'date'					 => $date,
//					'status'				 => Shipment::STATUS_NEW
//			));
//			$shipment->user()->associate($this->user);
//			$shipment->project()->associate($this->workProject);
//			$shipment->save();
//		}
//		$shipment = Shipment::whereDate($date)->whereTransportType(Partner::TRANSPORT_TYPE_POST)->first();
//		if (!$shipment) {
//			Shipment::create(array(
//					'transport_type' => Partner::TRANSPORT_TYPE_POST,
//					'date'					 => $date,
//					'status'				 => Shipment::STATUS_NEW
//			));
//			$shipment->user()->associate($this->user);
//			$shipment->project()->associate($this->workProject);
//			$shipment->save();
//		}
	}

	protected function isAllowShipment($type) {
		$allow = false;
		if (in_array($type, array('cdek', 'post'))) {
			switch ($type) {
				case 'cdek':
					if (in_array($this->workProject->id, array(20, 63, 68, 70, 91))) {
						$allow = true;
					}
					break;
				case 'post':
					if (in_array($this->workProject->id, array(20, 63))) {
						$allow = true;
					}
					break;
			}
		}
		return $allow;
	}

	public function index() {
		$input = Input::except('page');

		if (!Input::has('date')) {
			$input['date'] = Session::get('shipments_date');
		}
		if (!$input['date']) {
			$input['date'] = date('Y-m-d');
		}
		Session::set('shipments_date', $input['date']);


		$shipments = Shipment::whereRaw($this->whereProjectId)->whereDate($input['date'])->get();
		foreach ($shipments as $shipment) {
			if ($shipment->status == Shipment::STATUS_NEW) {
				if ($shipment->transport_type == Partner::TRANSPORT_TYPE_CDEK && $this->isAllowShipment('cdek')) {
					$partnersCdek = Partner::with('user')
									->checkStatus(array('statusType' => 'agreed', 'type' => 'registration'))
									->whereRaw($this->whereProjectId)
									->whereTransportType(Partner::TRANSPORT_TYPE_CDEK)
									->whereClarificationAddress(0)
									->whereRaw('partners.id NOT IN (SELECT partner_id FROM shipments_partners WHERE shipment_id IN (SELECT id FROM shipments WHERE status!=?))', array(Shipment::STATUS_SUCCESS))
									->get();
					if ($partnersCdek->count()) {
						foreach ($partnersCdek as $partner) {
							$shipment->partners()->attach($partner);
						}
					}
				}

				if ($shipment->transport_type == Partner::TRANSPORT_TYPE_POST && $this->isAllowShipment('post')) {
					$partnersPost = Partner::with('user')
									->checkStatus(array('statusType' => 'agreed', 'type' => 'registration'))
									->whereRaw($this->whereProjectId)
									->whereTransportType(Partner::TRANSPORT_TYPE_POST)
									->whereClarificationAddress(0)
									->whereRaw('partners.id NOT IN (SELECT partner_id FROM shipments_partners WHERE shipment_id IN (SELECT id FROM shipments WHERE status!=?))', array(Shipment::STATUS_SUCCESS))
									->get();
					if ($partnersPost->count()) {
						foreach ($partnersPost as $partner) {
							$shipment->partners()->attach($partner);
						}
					}

					$productsPost = array();
					foreach ($shipment->partners as $partner) {
						if ($partner->getCart() && !$partner->shipment_no_goods) {
							foreach ($partner->getCart() as $item) {
								if ($item['quant'] > 0) {
									$product = Product::withTrashed()->whereId($item['id'])->first();
									if ($product) {
										if (!isset($productsPost[$product->article])) {
											$productsPost[$product->article]['article']	 = $product->article;
											$productsPost[$product->article]['name']		 = $product->name;
											$productsPost[$product->article]['price']		 = $product->price_purchase;
											$productsPost[$product->article]['weight']	 = $product->weight;
											$productsPost[$product->article]['quant']		 = 0;
										}
										$productsPost[$product->article]['quant'] += $item['quant'];
									}
								}
							}
						}
					}

					usort($productsPost, 'cmp');
					$shipment->products = $productsPost;
				}
			}
		}
		$dates = Shipment::whereRaw($this->whereProjectId)->where('status', '!=', Shipment::STATUS_SUCCESS)->groupBy('date')->orderBy('date', 'ASC')->select('date')->get();

		return $this->setupLayout('shipments.index')
										->with('input', $input)
										->with('dates', $dates)
										->with('shipments', $shipments)
										->with('allowCreate', $this->allowCreate);
	}

	public function create() {
		if (!$this->allowCreate) {
			return Redirect::to('/shipments');
		}

		$partnersPost	 = false;
		$productsCdek	 = array();
		$partnersPost	 = false;
		$productsPost	 = array();

		if ($this->isAllowShipment('cdek')) {
			$partnersCdek	 = Partner::with('user')
							->checkStatus(array('statusType' => 'agreed', 'type' => 'registration'))
							->whereRaw($this->whereProjectId)
							->whereClarificationAddress(0)
							->whereTransportType(Partner::TRANSPORT_TYPE_CDEK)
	//						->whereRaw('(DATE(datetime_of_agree)<DATE(NOW()) OR (DATE(datetime_of_agree)=DATE(NOW()) AND TIME(datetime_of_agree)<TIME(?)))', array('16:00:00'))
							->whereRaw('partners.id NOT IN (SELECT partner_id FROM shipments_partners WHERE shipment_id IN (SELECT id FROM shipments WHERE status!=?))', array(Shipment::STATUS_SUCCESS))
							->get();
			foreach ($partnersCdek as $partner) {
				if ($partner->getCart()) {
					foreach ($partner->getCart() as $item) {
						if ($item['quant'] > 0) {
							$product = Product::withTrashed()->whereId($item['id'])->first();
							if ($product) {
								if (!isset($productsCdek[$product->article])) {
									$productsCdek[$product->article]['article']	 = $product->article;
									$productsCdek[$product->article]['name']		 = $product->name;
									$productsCdek[$product->article]['price']		 = $product->price_purchase;
									$productsCdek[$product->article]['weight']	 = $product->weight;
									$productsCdek[$product->article]['quant']		 = 0;
								}
								$productsCdek[$product->article]['quant'] += $item['quant'];
							}
						}
					}
				}
			}
		}

		if ($this->isAllowShipment('post')) {
			$partnersPost	 = Partner::with('user')
							->checkStatus(array('statusType' => 'agreed', 'type' => 'registration'))
							->whereRaw($this->whereProjectId)
							->whereClarificationAddress(0)
							->whereTransportType(Partner::TRANSPORT_TYPE_POST)
	//						->whereRaw('(DATE(datetime_of_agree)<DATE(NOW()) OR (DATE(datetime_of_agree)=DATE(NOW()) AND TIME(datetime_of_agree)<TIME(?)))', array('16:00:00'))
							->whereRaw('partners.id NOT IN (SELECT partner_id FROM shipments_partners WHERE shipment_id IN (SELECT id FROM shipments WHERE deleted_at IS NULL AND status!=?))', array(Shipment::STATUS_SUCCESS))
							->get();
			foreach ($partnersPost as $partner) {
				if ($partner->getCart()) {
					foreach ($partner->getCart() as $item) {
						if ($item['quant'] > 0) {
							$product = Product::withTrashed()->whereId($item['id'])->first();
							if ($product) {
								if (!isset($productsPost[$product->article])) {
									$productsPost[$product->article]['article']	 = $product->article;
									$productsPost[$product->article]['name']		 = $product->name;
									$productsPost[$product->article]['price']		 = $product->price_purchase;
									$productsPost[$product->article]['weight']	 = $product->weight;
									$productsPost[$product->article]['quant']		 = 0;
								}
								$productsPost[$product->article]['quant'] += $item['quant'];
							}
						}
					}
				}
			}
		}

		usort($productsCdek, 'cmp');
		usort($productsPost, 'cmp');

		$shipmentCdek			 = Shipment::whereTransportType(Partner::TRANSPORT_TYPE_CDEK)->whereRaw($this->whereProjectId)->whereStatus(Shipment::STATUS_NEW)->first();
		$shipmentPost			 = Shipment::whereTransportType(Partner::TRANSPORT_TYPE_POST)->whereRaw($this->whereProjectId)->whereStatus(Shipment::STATUS_NEW)->first();
		$shipmentCdekToday = Shipment::whereTransportType(Partner::TRANSPORT_TYPE_CDEK)->whereRaw($this->whereProjectId)->whereRaw('date=DATE(NOW())')->first();
		$shipmentPostToday = Shipment::whereTransportType(Partner::TRANSPORT_TYPE_POST)->whereRaw($this->whereProjectId)->whereRaw('date=DATE(NOW())')->first();

		return $this->setupLayout('shipments.create')
										->with('shipmentCdek', $shipmentCdek)
										->with('shipmentPost', $shipmentPost)
										->with('shipmentCdekToday', $shipmentCdekToday)
										->with('shipmentPostToday', $shipmentPostToday)
										->with('partnersCdek', $partnersCdek)
										->with('productsCdek', $productsCdek)
										->with('partnersPost', $partnersPost)
										->with('productsPost', $productsPost);
	}

	public function store() {
		if (!$this->allowCreate) {
			$response = array(
					'status' => 'fail'
			);
			return Response::json($response);
		}

		$shipmentCdek	 = Shipment::whereTransportType(Partner::TRANSPORT_TYPE_CDEK)->whereRaw($this->whereProjectId)->whereStatus(Shipment::STATUS_NEW)->first();
		$shipmentPost	 = Shipment::whereTransportType(Partner::TRANSPORT_TYPE_POST)->whereRaw($this->whereProjectId)->whereStatus(Shipment::STATUS_NEW)->first();

		if (!$shipmentCdek && $this->isAllowShipment('cdek')) {
			$partnersCdek = Partner::with('user')
							->checkStatus(array('statusType' => 'agreed', 'type' => 'registration'))
							->whereRaw($this->whereProjectId)
							->whereClarificationAddress(0)
							->whereTransportType(Partner::TRANSPORT_TYPE_CDEK)
//							->whereRaw('(DATE(datetime_of_agree)<DATE(NOW()) OR (DATE(datetime_of_agree)=DATE(NOW()) AND TIME(datetime_of_agree)<TIME(?)))', array('16:00:00'))
							->whereRaw('partners.id NOT IN (SELECT partner_id FROM shipments_partners WHERE shipment_id IN (SELECT id FROM shipments WHERE status!=?))', array(Shipment::STATUS_SUCCESS))
							->get();
			if ($partnersCdek->count()) {
				$shipment = Shipment::whereTransportType(Partner::TRANSPORT_TYPE_CDEK)->whereRaw($this->whereProjectId)->whereRaw('date=DATE(NOW())')->first();
				if (!$shipment) {
					$shipment = Shipment::create(array(
											'transport_type' => Partner::TRANSPORT_TYPE_CDEK,
											'date'					 => DB::raw('NOW()'),
											'status'				 => Shipment::STATUS_NEW
					));
					$shipment->user()->associate($this->user);
					$shipment->project()->associate($this->workProject);
					$shipment->save();
				}
				$shipment->partners()->sync($partnersCdek);
			}
		}

		if (!$shipmentPost && $this->isAllowShipment('post')) {
			$partnersPost = Partner::with('user')
							->checkStatus(array('statusType' => 'agreed', 'type' => 'registration'))
							->whereRaw($this->whereProjectId)
							->whereClarificationAddress(0)
							->whereTransportType(Partner::TRANSPORT_TYPE_POST)
							->whereRaw('(DATE(datetime_of_agree)<DATE(NOW()) OR (DATE(datetime_of_agree)=DATE(NOW()) AND TIME(datetime_of_agree)<TIME(?)))', array('16:00:00'))
							->whereRaw('partners.id NOT IN (SELECT partner_id FROM shipments_partners WHERE shipment_id IN (SELECT id FROM shipments WHERE status!=?))', array(Shipment::STATUS_SUCCESS))
							->get();
			if ($partnersPost->count()) {
				$shipment = Shipment::whereTransportType(Partner::TRANSPORT_TYPE_POST)->whereRaw($this->whereProjectId)->whereRaw('date=DATE(NOW())')->first();
				if (!$shipment) {
					$shipment = Shipment::create(array(
											'transport_type' => Partner::TRANSPORT_TYPE_POST,
											'date'					 => DB::raw('NOW()'),
											'status'				 => Shipment::STATUS_NEW
					));
					$shipment->user()->associate($this->user);
					$shipment->project()->associate($this->workProject);
					$shipment->save();
				}
				$shipment->partners()->sync($partnersPost);
			}
		}

		$response = array(
				'status' => 'success'
		);
		return Response::json($response);
	}

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

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

		$partner = Partner::find($input['partnerId']);
		if ($partner == null || !is_numeric($input['partnerId'])) {
			$response = array(
					'status'	 => 'fail',
					'message'	 => 'Клиент не найден'
			);
			return Response::json($response);
		}
		$partner->shipment_no_goods = 1;
		$partner->save();

		$response = array(
				'status'	 => 'success',
				'partner'	 => $partner->toArray(),
				'btns'		 => View::make('shipments.btns')->with('partner', $partner)->render()
		);
		return Response::json($response);
	}

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

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

		$partner = Partner::find($input['partnerId']);
		if ($partner == null || !is_numeric($input['partnerId'])) {
			$response = array(
					'status'	 => 'fail',
					'message'	 => 'Клиент не найден'
			);
			return Response::json($response);
		}
		$partner->shipment_no_goods = 0;
		$partner->save();

		$response = array(
				'status'	 => 'success',
				'partner'	 => $partner->toArray(),
				'btns'		 => View::make('shipments.btns')->with('partner', $partner)->render()
		);
		return Response::json($response);
	}

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

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

		$partner = Partner::find($input['partnerId']);
		if ($partner == null || !is_numeric($input['partnerId'])) {
			$response = array(
					'status'	 => 'fail',
					'message'	 => 'Клиент не найден'
			);
			return Response::json($response);
		}

		$shipment = $partner->shipment()->first();
		if (!$shipment->cdekDeliveryRequest) {
			$cdekDeliveryRequest = CdekDeliveryRequest::create(array(
									'date'		 => date('Y-m-d'),
									'user_id'	 => Auth::user()->id,
			));
			$shipment->cdekDeliveryRequest()->associate($cdekDeliveryRequest);
			$shipment->save();
		}

		$cdek	 = new CdekIntegrator(($shipment->project_id==70));
		$res	 = $cdek->addDeliveries(Partner::with('user')->whereId($partner->id)->get(), $shipment->cdekDeliveryRequest);
		foreach ($res['Order'] as $item) {
			if (isset($item['@attributes']['ErrorCode']) && $item['@attributes']['ErrorCode'] == 'ERR_CASH_ON_DELIV_PAYREC_MISTAKE') {
				$message = "{$item['@attributes']['Msg']}.";
				$partner->saveHistory($message);
				$partner->save();

				$response = array(
						'status'	 => 'fail',
						'partner'	 => $partner->toArray(),
						'message'	 => $message,
						'btns'		 => View::make('shipments.btns')->with('partner', $partner)->render()
				);
				return Response::json($response);
			}
			elseif (isset($item['@attributes']['DispatchNumber'])) {
				$partner = Partner::find($item['@attributes']['Number']);
				$partner->update(array('cdek_dispatchNumber' => $item['@attributes']['DispatchNumber'], 'cdek_deliveryRequestNumber' => $shipment->cdekDeliveryRequest->id));
				if ($partner->status == Partner::STATUS_DELIVERY_AFTER_REGISTRATION) {
					$partner->status = Partner::STATUS_DELIVERY_AFTER_WAIT_DELIVERING;
				}
				elseif ($partner->status == Partner::STATUS_DELIVERY_BEFORE_REGISTRATION) {
					$partner->status = Partner::STATUS_DELIVERY_BEFORE_WAIT_DELIVERING;
				}
				$message = "Заявка отправлена в СДЭК. Номер отправления СДЭК - {$partner->cdek_dispatchNumber}.";
				$partner->saveHistory($message);
				$partner->save();
			}
		}

		$response = array(
				'status'	 => 'success',
				'partner'	 => $partner->toArray(),
				'btns'		 => View::make('shipments.btns')->with('partner', $partner)->render()
		);
		return Response::json($response);
	}

	public function shoplogisticsActFence() {
		$input			 = Input::all();
		$shipmentId	 = $input['id'];
		$shipment		 = Shipment::whereTransportType(Partner::TRANSPORT_TYPE_POST)->whereid($shipmentId)->whereStatus(Shipment::STATUS_NEW)->first();
		if (!$shipment) {
			$response = array('status' => 'fail');
			return Response::json($response);
		}

		$productsPost = array();
		foreach ($shipment->partners as $partner) {
			if ($partner->getCart()) {
				foreach ($partner->getCart() as $item) {
					if ($item['quant'] > 0) {
						$product = Product::withTrashed()->whereId($item['id'])->first();
						if ($product) {
							if (!isset($productsPost[$product->article])) {
								$productsPost[$product->article]['article']	 = $product->article;
								$productsPost[$product->article]['name']		 = $product->name;
								$productsPost[$product->article]['price']		 = $product->price_purchase;
								$productsPost[$product->article]['weight']	 = $product->weight;
								$productsPost[$product->article]['quant']		 = 0;
							}
							$productsPost[$product->article]['quant'] += $item['quant'];
						}
					}
				}
			}
		}
		foreach ($input['products'] as $key => $value) {
			if ($value < $productsPost[$key]['quant']) {
				$quant = $productsPost[$key]['quant'] - $value;
				foreach (Partner::whereRaw('partners.id IN (SELECT partner_id FROM shipments_partners WHERE shipment_id=?)', array($shipment->id))
								->where('cart', 'LIKE', '%"article":"' . $key . '"%')
								->orderBy('datetime_of_agree', 'ASC')
								->get() as $partner) {
					foreach ($partner->getCart() as $item) {
						if ($item['article'] == $key && !$partner->shipment_no_goods) {
							if ($quant > 0 && $item['quant'] > 0) {
								$partner->shipment_no_goods = 1;
								$partner->save();
								$quant -= $item['quant'];
							}
						}
					}
				}
			}
		}

		$partners = $shipment->partners()->whereShipmentNoGoods(0)->get();
		$shipment->partners()->sync($partners);
		Partner::whereTransportType(Partner::TRANSPORT_TYPE_POST)->update(array('shipment_no_goods' => 0));

		$shipment	 = Shipment::whereTransportType(Partner::TRANSPORT_TYPE_POST)->whereid($shipmentId)->whereStatus(Shipment::STATUS_NEW)->first();
		$sl				 = new ShopLogistics();
		$res			 = $sl->addProductsAct($shipment);
		if (isset($res['error']) && !$res['error']) {
			$shipment->status = Shipment::STATUS_WAIT_ZABOR;
			$shipment->save();
		}

		$response = array('status' => 'success');
		return Response::json($response);
	}

	public function shoplogisticsAddZabor() {
		$shipmentId	 = Input::get('id');
		$shipment		 = Shipment::whereTransportType(Partner::TRANSPORT_TYPE_POST)->whereid($shipmentId)->whereStatus(Shipment::STATUS_WAIT_ZABOR)->first();
		if (!$shipment) {
			$response = array('status' => 'fail');
			return Response::json($response);
		}
		$date = date('Y-m-d');
		if (Input::has('date')) {
			$date	 = explode(".", Input::get('date'));
			$date	 = "{$date[2]}-{$date[1]}-{$date[0]}";
		}

		$sl	 = new ShopLogistics();
		$res = $sl->addZabor($shipment, $date);
		if (isset($res['error']) && !$res['error']) {
			if ($res['zabors']['zabor']['error_code'] == 43) {
				$response = array('status' => 'fail', 'message' => 'Выбранная дата уже закрыта');
				return Response::json($response);
			}
			elseif ($res['zabors']['zabor']['error_code'] == 44) {
				$response = array('status' => 'fail', 'message' => 'Забор на выбранную дату уже есть в базе');
				return Response::json($response);
			}
			$shipment->status = Shipment::STATUS_WAIT_TRANSFER;
			$shipment->save();
		}

		$response = array('status' => 'success');
		return Response::json($response);
	}

	public function shoplogisticsTransfered() {
		$shipmentId	 = Input::get('id');
		$shipment		 = Shipment::whereTransportType(Partner::TRANSPORT_TYPE_POST)->whereid($shipmentId)->whereStatus(Shipment::STATUS_WAIT_TRANSFER)->first();
		if (!$shipment) {
			$response = array('status' => 'fail');
			return Response::json($response);
		}

		$shipment->status = Shipment::STATUS_WAIT_SEND;
		$shipment->save();

		$response = array('status' => 'success');
		return Response::json($response);
	}

	public function shoplogisticsSend() {
		$shipmentId	 = Input::get('id');
		$shipment		 = Shipment::whereTransportType(Partner::TRANSPORT_TYPE_POST)->whereid($shipmentId)->whereStatus(Shipment::STATUS_WAIT_SEND)->first();
		if (!$shipment) {
			$response = array('status' => 'fail');
			return Response::json($response);
		}

		foreach ($shipment->partners as $partner) {
			if ($partner && $partner->statusIsAllow(Partner::ALLOW_SEND_TO_SHOPLOGISTICS)) {
				$result					 = $partner->addToShopLogistics();
				$partner->recall = 0;
				$partner->save();

				if ($result['status'] == 'success') {
					$partner->saveHistory($result['message']);
					$partner->save();
				}
			}
		}
		$shipment->status = Shipment::STATUS_SUCCESS;
		$shipment->save();

		$response = array('status' => 'success');
		return Response::json($response);
	}

	//формирование акта забора ShopLogistics
	public function downloadShoplogisticsActFence($shipmentId) {
		$shipment = Shipment::whereTransportType(Partner::TRANSPORT_TYPE_POST)->whereid($shipmentId)->first();
		if (!$shipment) {
			return Redirect::to('shipments');
		}

		Session::set('shipments_shipmentId', $shipmentId);
		$fileName = "ShopLogisticsActFence-{$shipment->date}";
		Excel::create($fileName, function($excel) {
			$excel->sheet('Лист1', function($sheet) {
				$shipmentId	 = Session::get('shipments_shipmentId');
				$shipment		 = Shipment::whereTransportType(Partner::TRANSPORT_TYPE_POST)->whereid($shipmentId)->first();
				if ($shipment) {
					$products = array();

					foreach ($shipment->partners as $partner) {
						if ($partner->getCart()) {
							foreach ($partner->getCart() as $item) {
								if ($item['quant'] > 0) {
									$product = Product::withTrashed()->whereId($item['id'])->first();
									if ($product) {
										if (!isset($products[$product->article])) {
											$products[$product->article]['article']	 = $product->article;
											$products[$product->article]['name']		 = $product->name;
											$products[$product->article]['price']		 = $product->price_purchase;
											$products[$product->article]['quant']		 = 0;
										}
										$products[$product->article]['quant'] += $item['quant'];
									}
								}
							}
						}
					}
					$sheet->loadView('crm.shoplogistics.act_fence')->with('products', $products);
				}
			});
		})->store('xlsx');

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

	public function cdekSend() {
		$shipmentId	 = Input::get('id');
		$shipment		 = Shipment::whereTransportType(Partner::TRANSPORT_TYPE_CDEK)->whereid($shipmentId)->whereStatus(Shipment::STATUS_WAIT_ZABOR)->first();
		if (!$shipment) {
			$response = array('status' => 'fail');
			return Response::json($response);
		}

//		if ($shipment->partners->count()) {
//			$cdekDeliveryRequest = CdekDeliveryRequest::create(array(
//									'date'		 => date('Y-m-d'),
//									'user_id'	 => Auth::user()->id,
//			));
//			$cdek								 = new CdekIntegrator();
//			$res								 = $cdek->addDeliveries($shipment->partners, $cdekDeliveryRequest);
//			foreach ($res['Order'] as $item) {
//				if (isset($item['@attributes']['DispatchNumber'])) {
//					$partner = Partner::find($item['@attributes']['Number']);
//					$partner->update(array('cdek_dispatchNumber' => $item['@attributes']['DispatchNumber'], 'cdek_deliveryRequestNumber' => $cdekDeliveryRequest->id));
//					if ($partner->status == Partner::STATUS_DELIVERY_AFTER_REGISTRATION) {
//						$partner->status = Partner::STATUS_DELIVERY_AFTER_WAIT_DELIVERING;
//					}
//					elseif ($partner->status == Partner::STATUS_DELIVERY_BEFORE_REGISTRATION) {
//						$partner->status = Partner::STATUS_DELIVERY_BEFORE_WAIT_DELIVERING;
//					}
//					$message = "Заявка отправлена в СДЭК. Номер отправления СДЭК - {$partner->cdek_dispatchNumber}.";
//					$partner->saveHistory($message);
//					$partner->save();
//				}
//			}
//		}
		$shipment->status = Shipment::STATUS_SUCCESS;
		$shipment->save();

		$response = array('status' => 'success');
		return Response::json($response);
	}

	//формирование печатной формы СДЭК
	public function downloadCdekOrderPrint($partnerId) {
		$partner = Partner::whereId($partnerId)->first();
		if (!$partner || !$partner->statusIsAllow(Partner::ALLOW_CHECK_CDEK)) {
			return Redirect::to('shipments');
		}

		$cdek	 = new CdekIntegrator(($partner->project_id==70));
		$res	 = $cdek->ordersPrint(Partner::whereId($partner->id)->get());

		return Response::make($res, 200, array('content-type' => 'application/pdf'));
	}

	public function cdekActFence() {
		$shipmentId	 = Input::get('id');
		$shipment		 = Shipment::whereTransportType(Partner::TRANSPORT_TYPE_CDEK)->whereid($shipmentId)->whereStatus(Shipment::STATUS_NEW)->first();
		if (!$shipment) {
			$response = array('status' => 'fail');
			return Response::json($response);
		}

		$shipment->partners()->update(array('shipment_no_goods' => 0));
		$partners = $shipment->partners()->checkStatus(array('statusType' => 'agreed', 'type' => 'waitdelivery'))->get();
		$shipment->partners()->sync($partners);

		$shipment->status = Shipment::STATUS_WAIT_ZABOR;
		$shipment->save();

		$response = array('status' => 'success');
		return Response::json($response);
	}

	//формирование акта забора СДЭК
	public function downloadCdekActFence($shipmentId) {
		$shipment = Shipment::whereTransportType(Partner::TRANSPORT_TYPE_CDEK)->whereId($shipmentId)->first();
		if (!$shipment) {
			return Redirect::to('shipments');
		}

		Session::set('shipments_shipmentId', $shipmentId);
		$fileName = "CdekActFence-{$shipment->date}";
		Excel::create($fileName, function($excel) {
			$excel->sheet('Лист1', function($sheet) {
				$shipmentId	 = Session::get('shipments_shipmentId');
				$shipment		 = Shipment::whereTransportType(Partner::TRANSPORT_TYPE_CDEK)->whereid($shipmentId)->first();
				if ($shipment) {
					$products = array();

					foreach ($shipment->partners as $partner) {
						if ($partner->getCart()) {
							foreach ($partner->getCart() as $item) {
								if ($item['quant'] > 0) {
									$product = Product::withTrashed()->whereId($item['id'])->first();
									if ($product) {
										if (!isset($products[$product->article])) {
											$products[$product->article]['article']	 = $product->article;
											$products[$product->article]['name']		 = $product->name;
											$products[$product->article]['price']		 = $product->price_purchase;
											$products[$product->article]['quant']		 = 0;
										}
										$products[$product->article]['quant'] += $item['quant'];
									}
								}
							}
						}
					}
					$sheet->loadView('crm.shoplogistics.act_fence')->with('products', $products);
				}
			});

			$excel->sheet('Лист2', function($sheet) {
				$shipmentId	 = Session::get('shipments_shipmentId');
				$shipment		 = Shipment::whereTransportType(Partner::TRANSPORT_TYPE_CDEK)->whereid($shipmentId)->first();
				if ($shipment) {
					$sum		 = 0;
					$weight	 = 0;
					foreach ($shipment->partners as $partner) {
						$partner->weight = 0;
						if ($partner->getCart()) {
							foreach ($partner->getCart() as $item) {
								if ($item['quant'] > 0) {
									$product = Product::withTrashed()->whereId($item['id'])->first();
									if ($product) {
										$partner->weight += $product->weight * $item['quant'];
										$partner->sum += $item['price'] * $item['quant'];
										$weight += $product->weight * $item['quant'];
										$sum += $item['price'] * $item['quant'];
									}
								}
							}
						}
					}
					$sheet->loadView('crm.cdek.act_fence')->with('shipment', $shipment)->with('months', $this->months)->with('sum', $sum)->with('weight', $weight);
				}
			});
		})->store('xlsx');

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

	//формирование выгрузки для почтовой программы
	public function downloadPostExport($shipmentId) {
		$shipment = Shipment::whereTransportType(Partner::TRANSPORT_TYPE_POST)->whereid($shipmentId)->first();
		if (!$shipment) {
			return Redirect::to('shipments');
		}

		Session::set('shipments_shipmentId', $shipmentId);
		$fileName = "PostExport-{$shipment->date}";
		Excel::create($fileName, function($excel) {
			$excel->sheet('Лист1', function($sheet) {
				$shipmentId	 = Session::get('shipments_shipmentId');
				$shipment		 = Shipment::whereTransportType(Partner::TRANSPORT_TYPE_POST)->whereid($shipmentId)->first();
				if ($shipment) {
					$sum		 = 0;
					$weight	 = 0;
					foreach ($shipment->partners as $partner) {
						$partner->weight = 0;
						if ($partner->getCart()) {
							foreach ($partner->getCart() as $item) {
								if ($item['quant'] > 0) {
									$product = Product::withTrashed()->whereId($item['id'])->first();
									if ($product) {
										$partner->weight += $product->weight * $item['quant'];
										$partner->sum += $item['price'] * $item['quant'];
										$weight += $product->weight * $item['quant'];
										$sum += $item['price'] * $item['quant'];
									}
								}
							}
						}
					}
					$sheet->setColumnFormat(array(
							'H' => '0.000',
					));
					$sheet->loadView('crm.post.export')->with('shipment', $shipment);
				}
			});
//					print_r($excel);die();
		})->store('csv');

		$file = storage_path() . '/exports/' . $fileName . '.csv';
		File::put($file, iconv('UTF-8', "windows-1251", str_replace("','", "';'", str_replace("\"", "'", File::get($file)))));

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

}
