<?php

ini_set('precision', 14);

/*
  |--------------------------------------------------------------------------
  | Register The Laravel Class Loader
  |--------------------------------------------------------------------------
  |
  | In addition to using Composer, you may use the Laravel class loader to
  | load your controllers and models. This is useful for keeping all of
  | your classes in the "global" namespace without Composer updating.
  |
 */

ClassLoader::addDirectories(array(
		app_path() . '/commands',
		app_path() . '/controllers',
		app_path() . '/models',
		app_path() . '/database/seeds',
));

/*
  |--------------------------------------------------------------------------
  | Application Error Logger
  |--------------------------------------------------------------------------
  |
  | Here we will configure the error logger setup for the application which
  | is built on top of the wonderful Monolog library. By default we will
  | build a basic log file setup which creates a single file for logs.
  |
 */

Log::useFiles(storage_path() . '/logs/laravel.log');

/*
  |--------------------------------------------------------------------------
  | Application Error Handler
  |--------------------------------------------------------------------------
  |
  | Here you may handle any errors that occur in your application, including
  | logging them or displaying custom views for specific errors. You may
  | even register several error handlers to handle different types of
  | exceptions. If nothing is returned, the default error view is
  | shown, which includes a detailed stack trace during debug.
  |
 */

App::error(function(Exception $exception, $code) {
	Log::error($exception);
});

/*
  |--------------------------------------------------------------------------
  | Maintenance Mode Handler
  |--------------------------------------------------------------------------
  |
  | The "down" Artisan command gives you the ability to put an application
  | into maintenance mode. Here, you will define what is displayed back
  | to the user if maintenance mode is in effect for the application.
  |
 */

App::down(function() {
	return Response::make("Be right back!", 503);
});

/*
  |--------------------------------------------------------------------------
  | Require The Filters File
  |--------------------------------------------------------------------------
  |
  | Next we will load the filters file for the application. This gives us
  | a nice separate location to store our route and application filter
  | definitions instead of putting them all in the main routes file.
  |
 */

require app_path() . '/filters.php';

Event::listen('user.fine', function($user, $fineId, $date = null) {
	if ($user && $fineId) {
		if (!$date) {
			$date = date('Y-m-d');
		}
		$lastTimesheetday = Timesheetday::whereUserId($user->id)->whereDate($date)->first();

		$timesheetdayFine = TimesheetdayFine::create(array(
								'date'		 => $date,
								'fine_id'	 => $fineId
		));
		$timesheetdayFine->user()->associate($user);

		switch ($fineId) {
			case Fine::FINE_LATE:
				$timesheetdayFine->value = $user->late_fee;
				$lastTimesheetday->fines_amount += $user->late_fee;
				$lastTimesheetday->save();
				break;
			default:
				$timesheetdayFine->value = 0;
				break;
		}

		$timesheetdayFine->save();
	}
});

Event::listen('cron.collectJobs', function() {
	Cron::add('changePassword', '0 8 * * *', function() {
		foreach (User::whereUseSmsPassword(1)->get() as $user) {
			$characters	 = '0123456789';
			$randstring	 = '';
			for ($i = 0; $i < 5; $i++) {
				$randstring .= $characters[rand(0, strlen($characters) - 1)];
			}

			$user->password							 = e(Hash::make($randstring));
			$user->sms_password					 = e($randstring);
			$user->sms_password_changed	 = 1;
			$user->save();

			$smsc = new SMSCService();
			$smsc->sendSMS($user->phone, "Пароль {$randstring}");
		}
		return 'Ok';
	});

	Cron::add('checkShopLogistics', '*/29 8-18 * * *', function() {
		foreach (Partner::with('user')
						->checkStatus(array('statusType' => 'agreed'))
						->whereNotIn('status', array(Partner::STATUS_DELIVERY_AFTER_SUCCESS, Partner::STATUS_DELIVERY_BEFORE_WAIT_PAY, Partner::STATUS_DELIVERY_BEFORE_SUCCESS))
						->whereNotNull('shoplogistics_code')
						->whereTransportType(Partner::TRANSPORT_TYPE_POST)
						->whereClarificationAddress(0)
						->get() as $partner) {
			if ($partner && $partner->statusIsAllow(Partner::ALLOW_CHECK_SHOPLOGISTICS)) {
				$res						 = $partner->checkShopLogistics();
				$partner->recall = 0;
				$partner->save();
				if ($res['status'] == 'success' && isset($res['statusChanged']) && $res['statusChanged']) {
					$partner->saveHistory($res['message'], 1, 1);
				}
			}
		}

		return 'Ok';
	});

	Cron::add('checkCdek', '*/25 8-18 * * *', function() {
		foreach (Partner::with('user')
						->checkStatus(array('statusType' => 'agreed'))
						->whereNotIn('status', array(Partner::STATUS_DELIVERY_AFTER_SUCCESS, Partner::STATUS_DELIVERY_BEFORE_WAIT_PAY, Partner::STATUS_DELIVERY_BEFORE_SUCCESS, Partner::STATUS_DELIVERY_BEFORE_DELIVERING_FAIL))
						->whereNotNull('cdek_dispatchNumber')
						->whereTransportType(Partner::TRANSPORT_TYPE_CDEK)
						->whereClarificationAddress(0)
						->get() as $partner) {
			if ($partner && $partner->statusIsAllow(Partner::ALLOW_CHECK_CDEK)) {
				$res						 = $partner->checkCdek();
				$partner->recall = 0;
				$partner->save();
				if ($res['status'] == 'success' && isset($res['statusChanged']) && $res['statusChanged']) {
					$partner->saveHistory($res['message'], 1, 1);
				}
			}
		}

		return 'Ok';
	});
	
Cron::add('sendBudgetBalanceEvening', '00 18 * * 1-5', function() {
		$role = Role::find(Role::ROLE_BUDGET_GIVE_BALANCE_NOTICE);
		$usersForBalanceSend = $role->users()->get();

		$budgetProjectsBalance = BudgetOperation::getBudgetProjectsBalance(date('Y-m-d'));
		$budgetProjectsMoney   = BudgetOperation::getBudgetProjectsMoney();
    
		foreach($usersForBalanceSend as $user){
			$userProjects = $user->budgetProjects()->get();
			$content = '<h3><b>Суммы операций по проектам за сегодняшний день ('.date('d.m.Y').')</b></h3>';
			foreach ($userProjects as $userProject){
        $projectid = $userProject->id;
				$in = isset($budgetProjectsBalance[$projectid][BudgetOperation::TYPE_INCOMING])? $budgetProjectsBalance[$projectid][BudgetOperation::TYPE_INCOMING] : '0';
				$out = isset($budgetProjectsBalance[$projectid][BudgetOperation::TYPE_OUTCOMING])? $budgetProjectsBalance[$projectid][BudgetOperation::TYPE_OUTCOMING] : '0';
				$money = 0;
        if(isset($budgetProjectsMoney[$projectid])){
          $money = $budgetProjectsMoney[$projectid]['in'] - $budgetProjectsMoney[$projectid]['out'];
        }
        $content .=	
					'<b>'.$userProject->name.'</b>
						<div>
						  Приход: '.number_format($in, 0, ',', ' ').' руб.<br>
						  Расход: '.number_format($out, 0, ',', ' ').' руб. <br>
						  Всего денег на текущий момент: '.number_format($money, 0, ',', ' ').' руб.
						</div><br>';
			}
			
			$user->sendOperationsSum($content, date('d.m.Y'));
		}

		return 'Ok';
	});
	
	Cron::add('sendBudgetBalanceMorning', '00 10 * * 1-5', function() {
		$role = Role::find(Role::ROLE_BUDGET_GIVE_BALANCE_NOTICE);
		$usersForBalanceSend = $role->users()->get();
		$isMonday = (date('w') == 1)? 1 : 0;

		$budgetProjectsBalance = BudgetOperation::getBudgetProjectsBalance( date('Y-m-d', time() - 3600 * 24 - 3600 * 24*2*$isMonday) );
    $budgetProjectsMoney   = BudgetOperation::getBudgetProjectsMoney();

		foreach($usersForBalanceSend as $user){
			$userProjects = $user->budgetProjects()->get();
			$content = '<h3><b>Суммы операций по проектам за '. ($isMonday? 'пятницу' : 'вчерашний день').' ('.date('d.m.Y', time() - 3600 * 24 - 3600 * 24*2*$isMonday).')</b></h3>';
			foreach ($userProjects as $userProject){
        $projectid = $userProject->id;
				$in = isset($budgetProjectsBalance[$projectid][BudgetOperation::TYPE_INCOMING])? $budgetProjectsBalance[$projectid][BudgetOperation::TYPE_INCOMING] : '0';
				$out = isset($budgetProjectsBalance[$projectid][BudgetOperation::TYPE_OUTCOMING])? $budgetProjectsBalance[$projectid][BudgetOperation::TYPE_OUTCOMING] : '0';
        $money = 0;
        if(isset($budgetProjectsMoney[$projectid])){
          $money = $budgetProjectsMoney[$projectid]['in'] - $budgetProjectsMoney[$projectid]['out'];
        }
				$content .=	
					'<b>'.$userProject->name.'</b>
						<div>
						  Приход: '.number_format($in, 0, ',', ' ').' руб.<br>
						  Расход: '.number_format($out, 0, ',', ' ').' руб. <br>
						  Всего денег на текущий момент: '.number_format($money, 0, ',', ' ').' руб.
						</div><br>';
			}
			
			$user->sendOperationsSum($content, date('d.m.Y', time() - 3600 * 24 - 3600 * 24*2*$isMonday));
		}

		return 'Ok';
	});

//	Cron::add('checkCalls', '30 10,17 * * *', function() {
//		$c = new CheckcallsController();
//		$c->setupProjects();
//		$c->index();
//
//		$project = Project::find(20);
//		$count	 = $project->checkcalls()->whereStatus(0)->count();
//		if ($count) {
//			$smsc = new SMSCService();
//			$smsc->sendSMS('+79033243597,+79063959102,+79875159292', "Не провереных звонков: {$count}");
//		}
//
//		return 'Ok';
//	});
//
//    Cron::add('example1', '* * * * *', function() {
//                    // Do some crazy things unsuccessfully every minute
//                    return 'Yes';
//                });
//
//    Cron::add('example2', '*/2 * * * *', function() {
//        // Do some crazy things successfully every two minute
//        return null;
//    });
//
//    Cron::add('disabled job', '0 * * * *', function() {
//        // Do some crazy things successfully every hour
//    }, false);
});
