<?php

class CdekUploadController extends BaseController {

	/**
	 * Constructor
	 */
	public function __construct() {
		// Establish Filters
		$this->beforeFilter('auth');
		$this->beforeFilter('hasRole:' . Role::ROLE_LOGISTICS);
	}

	public function index() {
		return $this->setupLayout('cdek.upload.index');
	}

	public function uploadFile() {
		$valid_exts	 = array('xls', 'xlsx');
		$max_size		 = 5 * 1024 * 1024;
		$path				 = storage_path() . '/cdek/';
		$file				 = Input::file('file');
		$ext				 = ($file->getClientOriginalExtension()) ? $file->getClientOriginalExtension() : 'xls';
		$size				 = $file->getClientSize();
		$name				 = date("YmdHis") . "." . $ext;

		if (in_array($ext, $valid_exts) && $size < $max_size) {
			if ($file->move($path, $name)) {
				Excel::load($path . $name, function($reader) {
					$result	 = array();
					$reg		 = "#Накладная (.*?) #is";
					foreach ($reader->getActiveSheet()->toArray() as $key => $value) {
						preg_match_all($reg, $value[0], $matches);
						if (isset($matches[1][0]) && $matches[1][0]) {
							if (!isset($result[$matches[1][0]])) {
								$result[$matches[1][0]]['cdek_dispatchNumber'] = $matches[1][0];
								$result[$matches[1][0]]['sum']								 = 0;
							}
							if ($value[1]) {
								$result[$matches[1][0]]['sum'] -= $value[1];
							}
							if ($value[2]) {
								$result[$matches[1][0]]['sum'] += $value[2];
							}
						}
					}
					$operationsProcessCount	 = 0;
					$operationsAddCount			 = 0;
					$operationsSum					 = 0;
					$unknown								 = array();
					foreach ($result as $item) {
						$operationsProcessCount++;
						$partner = Partner::withTrashed()->where('cdek_dispatchNumber', '=', $item['cdek_dispatchNumber'])->first();
						if ($partner) {
							$operationsAddCount++;
							if ($partner->status == Partner::STATUS_WAIT_TRANSPORT_COMPANY_PAY) {
								$partner->status = Partner::STATUS_SUCCESS;
							}
							$partner->paidsum			 = $item['sum'];
							$partner->paidsum_date = DB::raw('NOW()');
							$partner->save();
							$operationsSum += $item['sum'];
						}
						else {
							$unknown[$item['cdek_dispatchNumber']]['cdek_dispatchNumber'] = $item['cdek_dispatchNumber'];
						}
					}
					Session::set('operationsProcessCount', $operationsProcessCount);
					Session::set('operationsAddCount', $operationsAddCount);
					Session::set('operationsSum', $operationsSum);
					Session::set('unknown', $unknown);
				});
				$response = array(
						'status'	 => 'success',
						'message'	 => 'Файл успешно загружен',
						'stat'		 => View::make('cdek.upload.stat')
										->with('operationsProcessCount', Session::get('operationsProcessCount'))
										->with('operationsAddCount', Session::get('operationsAddCount'))
										->with('operationsSum', Session::get('operationsSum'))
										->with('unknown', Session::get('unknown'))
										->render()
				);
				return Response::json($response);
			}
		}

		$response = array(
				'status'	 => 'fail',
				'message'	 => 'Некорректный файл'
		);
		return Response::json($response);
	}

}
