<?php

class SettingsController extends BaseController {

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

		parent::__construct();
	}

	public function index() {
		if(!$this->user->isAdmin()) {
			return \App::abort(404);
		}

		$input = Input::all();

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

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

		if (in_array($ext, $valid_exts) && $size < $max_size) {
//			Excel::load("D://cdekcacheondelivery.xls", function($reader) {
//				foreach ($reader->getActiveSheet()->toArray() as $key => $value) {
//					if ($key > 14) {
//						$cityName = $value[0] ? $value[0] : $value[1];
//						if ($cityName) {
//							$cdekCacheondelivery = CdekCacheondelivery::whereName($cityName)->first();
//							if (!$cdekCacheondelivery) {
//								CdekCacheondelivery::create(array('name' => $cityName));
//							}
//						}
//					}
//				}
//			});
			if ($file->move($path, $name)) {
				Excel::load($path.'/'.$name, function($reader) {
					foreach ($reader->getActiveSheet()->toArray() as $key => $value) {
						if ($key > 14) {
							if ($value[0]) {
								$cityName = explode(',', $value[0]);
								$cityName = $cityName[0];
							}
							elseif($value[1]) {
								$cityName = $value[1];
							}
							if ($cityName) {
								$cdekCacheondelivery = CdekCacheondelivery::whereName($cityName)->first();
								if (!$cdekCacheondelivery) {
									CdekCacheondelivery::create(array('name' => $cityName));
								}
							}
						}
					}
				});
				$response = array(
						'status'	 => 'success',
						'message'	 => 'Файл успешно загружен'
				);
				return Response::json($response);
			}
		}

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

}
