<?php

class StatController extends BaseController {

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

	public function crm() {
		$user	 = User::find(Sentry::getUser()->id);
		$input = Input::all();

		$projects = $user->projects()->whereUsecrm(1)->get();

		return View::make('stat.crm')
										->with('projects', $projects)
										->with('user', $user)
										->with('input', $input)
										->with('months', $this->months);
	}

	public function leadstotal() {

		$this->user	 = Auth::user();
		$input			 = Input::all();

		if (Input::has('startDate')) {
			Session::put('stat_startDate', $input['startDate']);
		}
		else {
			$input['startDate'] = Session::get('stat_startDate');
			if (!$input['startDate']) {
				$input['startDate'] = date("d.m.Y");
			}
		}
		if (Input::has('endDate')) {
			Session::put('stat_endDate', $input['endDate']);
		}
		else {
			$input['endDate'] = Session::get('stat_endDate');
			if (!$input['endDate']) {
				$input['endDate'] = date('d.m.Y');
			}
		}

		$startDate = explode('.', $input['startDate']);
		if (checkdate($startDate[1], $startDate[0], $startDate[2])) {
			$startDate = "{$startDate[2]}-{$startDate[1]}-{$startDate[0]}";
		}
		$endDate = explode('.', $input['endDate']);
		if (checkdate($endDate[1], $endDate[0], $endDate[2])) {
			$endDate = "{$endDate[2]}-{$endDate[1]}-{$endDate[0]}";
		}

		$dateWhere	 = DB::raw("`partners`.lead_id IS NOT NULL AND DATE(`partners`.lead_created_at)>=DATE('{$startDate}') AND DATE(`partners`.lead_created_at)<=DATE('{$endDate}')");
		$dateLeadCreate	       = DB::raw("DATE(`leads`.created_at)>=DATE('{$startDate}') AND DATE(`leads`.created_at)<=DATE('{$endDate}')");
		$datePartnerLeadCreate = DB::raw("DATE(partners.lead_created_at)>=DATE('{$startDate}') AND DATE(partners.lead_created_at)<=DATE('{$endDate}')");
		$dateCreatePartners    = DB::raw("DATE(partners.created_at)>=DATE('{$startDate}') AND DATE(partners.created_at)<=DATE('{$endDate}')");
		$project = Project::find(9);
		if (!$project) {
			return \App::abort(404);
		}

		return $this->setupLayout('stat.leadstotal')
										->with('dateWhere', $dateWhere)
										->with('dateLeadCreate', $dateLeadCreate)
										->with('dateCreatePartners', $dateCreatePartners)
						        ->with('datePartnerLeadCreate', $datePartnerLeadCreate)
										->with('project', $project)
										->with('user', $this->user)
										->with('input', $input)
										->with('months', $this->months);
	}

	public function infosources() {

		$input = Input::all();

		if (Input::has('startDate')) {
			Session::put('stat_startDate', $input['startDate']);
		}
		else {
			$input['startDate'] = Session::get('stat_startDate');
			if (!$input['startDate']) {
				$input['startDate'] = date("d.m.Y");
			}
		}
		if (Input::has('endDate')) {
			Session::put('stat_endDate', $input['endDate']);
		}
		else {
			$input['endDate'] = Session::get('stat_endDate');
			if (!$input['endDate']) {
				$input['endDate'] = date('d.m.Y');
			}
		}

		$startDate = explode('.', $input['startDate']);
		if (checkdate($startDate[1], $startDate[0], $startDate[2])) {
			$startDate = "{$startDate[2]}-{$startDate[1]}-{$startDate[0]}";
		}
		$endDate = explode('.', $input['endDate']);
		if (checkdate($endDate[1], $endDate[0], $endDate[2])) {
			$endDate = "{$endDate[2]}-{$endDate[1]}-{$endDate[0]}";
		}

		$dateCreatePartners = DB::raw("DATE(partners.created_at)>=DATE('{$startDate}') AND DATE(partners.created_at)<=DATE('{$endDate}')");
		$project = Project::find(9);
		if (!$project) {
			return \App::abort(404);
		}

		return $this->setupLayout('stat.infosources')
										->with('dateCreatePartners', $dateCreatePartners)
										->with('project', $project)
										->with('input', $input);
	}

	public function leads() {

		$this->user	 = Auth::user();
		$input			 = Input::all();

		if (Input::has('startDate')) {
			Session::put('stat_startDate', $input['startDate']);
		}
		else {
			$input['startDate'] = Session::get('stat_startDate');
			if (!$input['startDate']) {
				$input['startDate'] = date("d.m.Y");
			}
		}
		if (Input::has('endDate')) {
			Session::put('stat_endDate', $input['endDate']);
		}
		else {
			$input['endDate'] = Session::get('stat_endDate');
			if (!$input['endDate']) {
				$input['endDate'] = date('d.m.Y');
			}
		}

		$startDate = explode('.', $input['startDate']);
		if (checkdate($startDate[1], $startDate[0], $startDate[2])) {
			$startDate = "{$startDate[2]}-{$startDate[1]}-{$startDate[0]}";
		}
		$endDate = explode('.', $input['endDate']);
		if (checkdate($endDate[1], $endDate[0], $endDate[2])) {
			$endDate = "{$endDate[2]}-{$endDate[1]}-{$endDate[0]}";
		}

		$dateWhere	 = DB::raw("`partners`.lead_id IS NOT NULL AND DATE(`partners`.lead_created_at)>=DATE('{$startDate}') AND DATE(`partners`.lead_created_at)<=DATE('{$endDate}')");
//		DB::raw("DATE(`partners`.lead_created_at)>=DATE('2014-10-06') AND DATE(`partners`.lead_created_at1)<=DATE('2014-10-06')")
		$dateLeadCreate	       = DB::raw("DATE(`leads`.created_at)>=DATE('{$startDate}') AND DATE(`leads`.created_at)<=DATE('{$endDate}')");
		$datePartnerLeadCreate = DB::raw("DATE(partners.lead_created_at)>=DATE('{$startDate}') AND DATE(partners.lead_created_at)<=DATE('{$endDate}')");
		$dateCreatePartners    = DB::raw("DATE(partners.created_at)>=DATE('{$startDate}') AND DATE(partners.created_at)<=DATE('{$endDate}')");
		$project = Project::find(9);
		if (!$project) {
			return \App::abort(404);
		}

		//$projects = $this->user->projects()->whereUsecrm(1)->whereProjectId($project->id)->get();

		return $this->setupLayout('stat.leads')
										->with('dateWhere', $dateWhere)
										->with('dateLeadCreate', $dateLeadCreate)
										->with('dateCreatePartners', $dateCreatePartners)
						        ->with('datePartnerLeadCreate', $datePartnerLeadCreate)
										->with('project', $project)
										->with('user', $this->user)
										->with('input', $input)
										->with('months', $this->months);
	}

	public function reject() {
		$user	 = User::find(Sentry::getUser()->id);
		$input = Input::all();

		if (Input::has('startDate')) {
			Session::put('stat_startDate', $input['startDate']);
		}
		else {
			$input['startDate'] = Session::get('stat_startDate');
			if (!$input['startDate']) {
				$input['startDate'] = date("d.m.Y", time() - 3600 * 24);
			}
		}
		if (Input::has('endDate')) {
			Session::put('stat_endDate', $input['endDate']);
		}
		else {
			$input['endDate'] = Session::get('stat_endDate');
			if (!$input['endDate']) {
				$input['endDate'] = date('d.m.Y');
			}
		}

		$startDate = explode('.', $input['startDate']);
		if (checkdate($startDate[1], $startDate[0], $startDate[2])) {
			$startDate = "{$startDate[2]}-{$startDate[1]}-{$startDate[0]}";
		}
		$endDate = explode('.', $input['endDate']);
		if (checkdate($endDate[1], $endDate[0], $endDate[2])) {
			$endDate = "{$endDate[2]}-{$endDate[1]}-{$endDate[0]}";
		}

		if (!isset($input['useAgreed'])) {
			$input['useAgreed'] = 0;
		}
		if ($input['useAgreed'] == 1) {
			$dateWhere = DB::raw("DATE(`partners`.updated_at)>=DATE('{$startDate}') AND DATE(`partners`.updated_at)<=DATE('{$endDate}') AND datetime_of_agree IS NOT NULL");
		}
		else {
			$dateWhere = DB::raw("DATE(`partners`.updated_at)>=DATE('{$startDate}') AND DATE(`partners`.updated_at)<=DATE('{$endDate}')");
		}

		if (!Input::has('projectId')) {
			$input['projectId']	 = '';
			$projects						 = $user->projects()->whereUsecrm(1)->get();
		}
		else {
			$projects = $user->projects()->whereUsecrm(1)->whereProjectId($input['projectId'])->get();
		}

		return View::make('stat.reject')
										->with('dateWhere', $dateWhere)
										->with('projects', $projects)
										->with('user', $user)
										->with('input', $input)
										->with('months', $this->months);
	}

	// детализированный отчет по отказам по всем менеджерам
	public function rejectDetail() {
		$user	 = User::find(Sentry::getUser()->id);
		$input = Input::all();

		if (Input::has('startDate')) {
			Session::put('stat_startDate', $input['startDate']);
		}
		else {
			$input['startDate'] = Session::get('stat_startDate');
			if (!$input['startDate']) {
				$input['startDate'] = date("d.m.Y", time() - 3600 * 24);
			}
		}
		if (Input::has('endDate')) {
			Session::put('stat_endDate', $input['endDate']);
		}
		else {
			$input['endDate'] = Session::get('stat_endDate');
			if (!$input['endDate']) {
				$input['endDate'] = date('d.m.Y');
			}
		}

		$startDate = explode('.', $input['startDate']);
		if (checkdate($startDate[1], $startDate[0], $startDate[2])) {
			$startDate = "{$startDate[2]}-{$startDate[1]}-{$startDate[0]}";
		}
		$endDate = explode('.', $input['endDate']);
		if (checkdate($endDate[1], $endDate[0], $endDate[2])) {
			$endDate = "{$endDate[2]}-{$endDate[1]}-{$endDate[0]}";
		}

		if (!isset($input['useAgreed'])) {
			$input['useAgreed'] = 0;
		}
		if ($input['useAgreed'] == 1) {
			$dateWhere = DB::raw("DATE(`partners`.updated_at)>=DATE('{$startDate}') AND DATE(`partners`.updated_at)<=DATE('{$endDate}') AND datetime_of_agree IS NOT NULL");
		}
		else {
			$dateWhere = DB::raw("DATE(`partners`.updated_at)>=DATE('{$startDate}') AND DATE(`partners`.updated_at)<=DATE('{$endDate}')");
		}

		if (!Input::has('projectId')) {
			$input['projectId']	 = '';
			$projects						 = Project::whereId(9)->get();
		}
		else {
			$projects						 = Project::whereId(9)->get();
		}

		return View::make('stat.rejectdetail')
										->with('dateWhere', $dateWhere)
										->with('projects', $projects)
										->with('user', $user)
										->with('input', $input)
										->with('months', $this->months);
	}

	public function shipments() {

		$this->user	 = Auth::user();
		$input			 = Input::all();

		if (Input::has('startDate')) {
			Session::put('stat_startDate', $input['startDate']);
		}
		else {
			$input['startDate'] = Session::get('stat_startDate');
			if (!$input['startDate']) {
				$input['startDate'] = date("d.m.Y");
			}
		}
		if (Input::has('endDate')) {
			Session::put('stat_endDate', $input['endDate']);
		}
		else {
			$input['endDate'] = Session::get('stat_endDate');
			if (!$input['endDate']) {
				$input['endDate'] = date('d.m.Y');
			}
		}

		$startDate = explode('.', $input['startDate']);
		if (checkdate($startDate[1], $startDate[0], $startDate[2])) {
			$startDate = "{$startDate[2]}-{$startDate[1]}-{$startDate[0]}";
		}
		$endDate = explode('.', $input['endDate']);
		if (checkdate($endDate[1], $endDate[0], $endDate[2])) {
			$endDate = "{$endDate[2]}-{$endDate[1]}-{$endDate[0]}";
		}

		$dateWhere	 = DB::raw("`partners`.lead_id IS NOT NULL AND DATE(`partners`.lead_created_at)>=DATE('{$startDate}') AND DATE(`partners`.lead_created_at)<=DATE('{$endDate}')");
		$dateLeadCreate	       = DB::raw("DATE(`leads`.created_at)>=DATE('{$startDate}') AND DATE(`leads`.created_at)<=DATE('{$endDate}')");
		$datePartnerLeadCreate = DB::raw("DATE(partners.lead_created_at)>=DATE('{$startDate}') AND DATE(partners.lead_created_at)<=DATE('{$endDate}')");
		$dateCreatePartners    = DB::raw("DATE(partners.created_at)>=DATE('{$startDate}') AND DATE(partners.created_at)<=DATE('{$endDate}')");
		$project = Project::find(9);
		if (!$project) {
			return \App::abort(404);
		}

		return $this->setupLayout('stat.shipments')
										->with('dateWhere', $dateWhere)
										->with('dateLeadCreate', $dateLeadCreate)
										->with('dateCreatePartners', $dateCreatePartners)
						        ->with('datePartnerLeadCreate', $datePartnerLeadCreate)
										->with('project', $project)
										->with('user', $this->user)
										->with('input', $input)
										->with('months', $this->months);
	}

	public function products() {
		$user	 = User::find(Sentry::getUser()->id);
		$input = Input::all();

		if (Input::has('startDate')) {
			Session::put('stat_startDate', $input['startDate']);
		}
		else {
			$input['startDate'] = Session::get('stat_startDate');
			if (!$input['startDate']) {
				$input['startDate'] = date("d.m.Y", time() - 3600 * 24);
			}
		}
		if (Input::has('endDate')) {
			Session::put('stat_endDate', $input['endDate']);
		}
		else {
			$input['endDate'] = Session::get('stat_endDate');
			if (!$input['endDate']) {
				$input['endDate'] = date('d.m.Y');
			}
		}

		$startDate = explode('.', $input['startDate']);
		if (checkdate($startDate[1], $startDate[0], $startDate[2])) {
			$startDate = "{$startDate[2]}-{$startDate[1]}-{$startDate[0]}";
		}
		$endDate = explode('.', $input['endDate']);
		if (checkdate($endDate[1], $endDate[0], $endDate[2])) {
			$endDate = "{$endDate[2]}-{$endDate[1]}-{$endDate[0]}";
		}
		$dateWhere = DB::raw("DATE(`partners`.datetime_of_agree)>=DATE('{$startDate}') AND DATE(`partners`.datetime_of_agree)<=DATE('{$endDate}')");

		if (!Input::has('projectId')) {
			$input['projectId'] = Session::get('stat_products_projectId');
		}
		if (!$input['projectId']) {
			$input['projectId'] = $user->projects()->whereUsecrm(1)->first()->id;
		}
		$project	 = $user->projects()->whereUsecrm(1)->whereId($input['projectId'])->first();
		$partners	 = $project->partners()->where('status', '!=', Partner::STATUS_REJECT)->whereRaw($dateWhere)->get();

		$productsArray = array();
		$products			 = $project->products()->with('mark')->withTrashed()->get();
		$productTypes	 = ProductType::all();
		if ($products) {
			foreach ($products as $product) {
				foreach ($productTypes as $type) {
					$productsArray[$product->id][$type->id]['product'] = $product->toArray();
					$productsArray[$product->id][$type->id]['type']		 = $type->toArray();
					$productsArray[$product->id][$type->id]['quant']	 = 0;
					$productsArray[$product->id][$type->id]['price']	 = 0;
					$productsArray[$product->id][$type->id]['name']		 = '';
				}
			}
		}
		if ($partners) {
			foreach ($partners as $partner) {
				foreach ($partner->getCart() as $cart) {
					foreach ($cart as $item) {
//					if (isset($productsArray[$cart['id']])) {
						$productsArray[$item['product_id']][$item['product_type_id']]['name'] = $item['name'];
						$productsArray[$item['product_id']][$item['product_type_id']]['quant'] += $item['quant'];
						$productsArray[$item['product_id']][$item['product_type_id']]['price'] += $item['price'] * $item['quant'];
//					}
					}
				}
			}
		}
		Session::put('stat_products_projectId', $input['projectId']);

		$productsResultArray = array();
		foreach ($productsArray as $product) {
			foreach ($product as $productType) {
				if ($productType['quant']) {
					$productsResultArray [] = $productType;
				}
			}
		}
		usort($productsResultArray, function($a, $b){
				return ($b['quant'] - $a['quant']);
		});

		return View::make('stat.products')
										->with('dateWhere', $dateWhere)
										->with('project', $project)
										->with('products', $productsResultArray)
										->with('user', $user)
										->with('input', $input)
										->with('months', $this->months);
	}

	public function production() {
		$user	 = User::find(Sentry::getUser()->id);
		$input = Input::all();

		if (Input::has('startDate')) {
			Session::put('stat_startDate', $input['startDate']);
		}
		else {
			$input['startDate'] = Session::get('stat_startDate');
			if (!$input['startDate']) {
				$input['startDate'] = date("d.m.Y", time() - 3600 * 24);
			}
		}
		if (Input::has('endDate')) {
			Session::put('stat_endDate', $input['endDate']);
		}
		else {
			$input['endDate'] = Session::get('stat_endDate');
			if (!$input['endDate']) {
				$input['endDate'] = date('d.m.Y');
			}
		}

		$startDate = explode('.', $input['startDate']);
		if (checkdate($startDate[1], $startDate[0], $startDate[2])) {
			$startDate = "{$startDate[2]}-{$startDate[1]}-{$startDate[0]}";
		}
		$endDate = explode('.', $input['endDate']);
		if (checkdate($endDate[1], $endDate[0], $endDate[2])) {
			$endDate = "{$endDate[2]}-{$endDate[1]}-{$endDate[0]}";
		}
		$dateWhere = DB::raw("DATE(`productions`.production_end_at)>=DATE('{$startDate}') AND DATE(`productions`.production_end_at)<=DATE('{$endDate}') AND TIME_TO_SEC(TIMEDIFF(`productions`.production_end_at,`productions`.production_start_at))>0.2*(60*60)");

		if (!Input::has('projectId')) {
			$input['projectId']	 = '';
			$projects						 = $user->projects()->whereUsecrm(1)->get();
		}
		else {
			$projects = $user->projects()->whereUsecrm(1)->whereProjectId($input['projectId'])->get();
		}

		return View::make('stat.production')
										->with('dateWhere', $dateWhere)
										->with('projects', $projects)
										->with('user', $user)
										->with('input', $input)
										->with('months', $this->months);
	}

	public function franchisees(){
		$user	 = User::find(Sentry::getUser()->id);
		$input = Input::all();

		if (Input::has('startDate')) {
			Session::put('stat_startDate', $input['startDate']);
		}
		else {
			$input['startDate'] = Session::get('stat_startDate');
			if (!$input['startDate']) {
				$input['startDate'] = date("d.m.Y", time() - 3600 * 24);
			}
		}
		if (Input::has('endDate')) {
			Session::put('stat_endDate', $input['endDate']);
		}
		else {
			$input['endDate'] = Session::get('stat_endDate');
			if (!$input['endDate']) {
				$input['endDate'] = date('d.m.Y');
			}
		}

		$startDate = explode('.', $input['startDate']);
		if (checkdate($startDate[1], $startDate[0], $startDate[2])) {
			$startDate = "{$startDate[2]}-{$startDate[1]}-{$startDate[0]}";
		}
		$endDate = explode('.', $input['endDate']);
		if (checkdate($endDate[1], $endDate[0], $endDate[2])) {
			$endDate = "{$endDate[2]}-{$endDate[1]}-{$endDate[0]}";
		}

		$dateWhereSize = DB::raw("DATE(`partners`.created_at)>=DATE('{$startDate}') AND DATE(`partners`.created_at)<=DATE('{$endDate}') AND `partners`.status = ".Partner::STATUS_SIZING);
		$dateWhereAgree = DB::raw("DATE(partners.datetime_of_agree)>=DATE('{$startDate}') AND DATE(partners.datetime_of_agree)<=DATE('{$endDate}')");
    $dateWhereAll = DB::raw( "((DATE(`partners`.created_at)>=DATE('{$startDate}') AND DATE(`partners`.created_at)<=DATE('{$endDate}') AND `partners`.status = ".Partner::STATUS_SIZING.")
		OR (DATE(partners.datetime_of_agree)>=DATE('{$startDate}') AND DATE(partners.datetime_of_agree)<=DATE('{$endDate}')))" );

		if (!Input::has('projectId')) {
			$input['projectId']	 = '';
			$projects						 = $user->projects()->whereUsecrm(1)->get();
		}
		else {
			$projects = $user->projects()->whereUsecrm(1)->whereProjectId($input['projectId'])->get();
		}

		return View::make('stat.franchisees')
						        ->with('dateWhereAll', $dateWhereAll)
										->with('dateWhereSize', $dateWhereSize)
										->with('dateWhereAgree', $dateWhereAgree)
										->with('projects', $projects)
										->with('user', $user)
										->with('input', $input)
										->with('months', $this->months);
	}

	public function dailymoney() {
		$user	 = User::find(Sentry::getUser()->id);
		$input = Input::all();

		if (Input::has('startDate')) {
			Session::put('stat_startDate', $input['startDate']);
		}
		else {
			$input['startDate'] = Session::get('stat_startDate');
			if (!$input['startDate']) {
				$input['startDate'] = date("d.m.Y");
			}
		}
		if (Input::has('endDate')) {
			Session::put('stat_endDate', $input['endDate']);
		}
		else {
			$input['endDate'] = Session::get('stat_endDate');
			if (!$input['endDate']) {
				$input['endDate'] = date('d.m.Y');
			}
		}

		$startDate = explode('.', $input['startDate']);
		if (checkdate($startDate[1], $startDate[0], $startDate[2])) {
			$startDate = "{$startDate[2]}-{$startDate[1]}-{$startDate[0]}";
		}
		$endDate = explode('.', $input['endDate']);
		if (checkdate($endDate[1], $endDate[0], $endDate[2])) {
			$endDate = "{$endDate[2]}-{$endDate[1]}-{$endDate[0]}";
		}

		$project = $user->projects()->whereUsecrm(1)->whereProjectId(9)->first();

		$begin = new DateTime($startDate);
		$end	 = new DateTime($endDate);
		$end	 = $end->modify('+1 day');

		$interval	 = DateInterval::createFromDateString('1 day');
		$period		 = new DatePeriod($begin, $interval, $end);

		return $this->setupLayout('stat.dailymoney')
										->with('startDate', $startDate)
										->with('endDate', $endDate)
										->with('period', $period)
										->with('project', $project)
										->with('user', $user)
										->with('input', $input)
										->with('months', $this->months);
	}

	public function daily() {
		$user	 = User::find(Sentry::getUser()->id);
		$input = Input::all();

		if (Input::has('startDate')) {
			Session::put('stat_startDate', $input['startDate']);
		}
		else {
			$input['startDate'] = Session::get('stat_daily_startDate');
			if (!$input['startDate']) {
				$input['startDate'] = date("d.m.Y", time() - 3600 * 24);
			}
		}

		$startDate = explode('.', $input['startDate']);
		if (checkdate($startDate[1], $startDate[0], $startDate[2])) {
			$startDate = "{$startDate[2]}-{$startDate[1]}-{$startDate[0]}";
		}

		$project = $user->projects()->whereUsecrm(1)->whereProjectId(9)->first();

		return View::make('stat.daily')
						        ->with('startDate', $startDate)
										->with('project', $project)
										->with('user', $user)
										->with('input', $input)
										->with('months', $this->months);
	}

	public function dailypay() {
		$user	 = User::find(Sentry::getUser()->id);
		$input = Input::all();

		if (Input::has('startDate')) {
			Session::put('stat_startDate', $input['startDate']);
		}
		else {
			$input['startDate'] = Session::get('stat_daily_pay_startDate');
			if (!$input['startDate']) {
				$input['startDate'] = date("d.m.Y");
			}
		}

		$startDate = explode('.', $input['startDate']);
		if (checkdate($startDate[1], $startDate[0], $startDate[2])) {
			$startDate = "{$startDate[2]}-{$startDate[1]}-{$startDate[0]}";
		}

		$project = $user->projects()->whereUsecrm(1)->whereProjectId(9)->first();

		return View::make('stat.dailypay')
						        ->with('startDate', $startDate)
										->with('project', $project)
										->with('user', $user)
										->with('input', $input)
										->with('months', $this->months);
	}

}
