<?php

class BudgetCostsRequestsUploadController extends BaseController {

	/**
	 * Constructor
	 */
	public function __construct() {
		// Establish Filters
		$this->beforeFilter('auth');
		//$this->beforeFilter('csrf', array('only' => array('createOperation')));
		$this->beforeFilter('hasAnyRole:', array(Role::ROLE_BUDGET_OUTCOMING_REQUEST, Role::ROLE_BUDGET_CFO, Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_ACC_SECRETARY));

		if (Auth::check()) {
			$this->user			 = Auth::user();
			$this->projects	 = $this->user->budgetProjects;
		}
		$this->projectPrefix = 'budget';
		parent::__construct();
	}

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

		if ( !isset($input['fileId']) || !isset($input['requestId']) ) {
			$response = array(
					'status' => 'fail',
					'message'	 => 'Неверный id файла или заявки'
			);
			return Response::json($response);
		}
		$file = BudgetCostsRequestsFiles::withTrashed()->find($input['fileId']);
		if ( $file == null || !is_numeric($input['fileId']) || !is_numeric($input['requestId']) ) {
			$response = array(
					'status'	 => 'fail',
					'message'	 => 'Файл не найден'
			);
			return Response::json($response);
		}
		if ( $file->budget_cost_request_id != $input['requestId'] ) {
			$response = array(
					'status'	 => 'fail',
					'message'	 => 'Не совпадает id заявки'
			);
			return Response::json($response);
		}

		if( $file->trashed() ){
			$file->restore();
		}
		else{
			$file->delete();
		}

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

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

    $date = time();
		$valid_exts	 = array('xls', 'xlsx', 'doc', 'docx', 'pdf', 'txt', 'jpg', 'jpeg', 'bmp', 'gif', 'tiff');
		$max_size		 = 15 * 1024 * 1024;
		$path				 = public_path() . '/costsrequests/uploadfile/'.Auth::user()->id;
		$file				 = Input::file('file');
		$ext				 = ($file->getClientOriginalExtension()) ? $file->getClientOriginalExtension() : 'txt';
		$size				 = $file->getClientSize();
		$name				 = Auth::user()->id.'_'.$date.'.'.$ext;
		$showName		 = $file->getClientOriginalName();

		if (in_array(strtolower($ext), $valid_exts) AND $size < $max_size) {
		$fileObj = BudgetCostsRequestsFiles::create(array(
												"name"		 => e($name),
												"show_name" => $showName
							                           ));

			if ($file->move($path , iconv("UTF-8", "Windows-1251", $name))) {
				$response = array(
						'status'	 => 'success',
						'file'		 => $fileObj,
//					'filePath' => URL::to('../budget/costsrequests/downloadfile/'.$fileObj->id.'/'.Auth::user()->id.'/'.$name)
						'filePath' => URL::to('../budget/costsrequests/downloadfile/'.$fileObj->id)

				);
				return Response::json($response);
			}
		}
		if ($size > $max_size){
			$response = array(
				'status'  => 'fail',
				'message' => 'Размер файла превышает максимально допустимый объем - 15 Mb.'
		  );
		  return Response::json($response);
		}

		$response = array(
				'status' => 'fail',
				'message' => 'Файлы данного формата не поддерживаются'
		);
		return Response::json($response);
	}

	public function downloadFile($id) {
		$fileObj = BudgetCostsRequestsFiles::find($id);
		if ($fileObj == null || !is_numeric($id)) {
			return \App::abort(404);
		}
		$fileNameArr = explode ('_', $fileObj->name);
		$userId = $fileNameArr[0];
		
		$name = $fileObj->name;
		return Response::download(public_path().'/costsrequests/uploadfile/'.$userId.'/'.$name);
		//return Response::download(link_to_asset('/costsrequests/uploadfile/'.$userId.'/'.$name));
	}
}