<?php

class SalaryController extends BaseController {

	/**
	 * Constructor
	 */
	public function __construct() {
		// Establish Filters
		$this->beforeFilter('auth');
		$this->beforeFilter('hasRole:' . Role::ROLE_PROJECT_MANAGER, array('only' => 'control', 'cancel'));

		parent::__construct();
	}

	public function index() {
		$user = Auth::user();

////		foreach (Refrence::whereProjectId(20)->whereRaw("date_format(datetime_of_agree, '%Y%m') = date_format(now(), '%Y%m')")->groupBy('user_id')->get(array(DB::raw("datetime_of_agree"))) as $date) {
////			if ($user->hasAccess('admin')) {
//				foreach (Refrence::whereRaw("date_format(created_at, '%Y%m') = date_format(now(), '%Y%m')")->groupBy('sender_user_id')->get(array(DB::raw("sender_user_id"))) as $item) {
//					$user = User::find($item->sender_user_id);
//					if ($user && $user->payroll) {
//						foreach (Refrence::whereRaw("sender_user_id = {$user->id} AND date_format(created_at, '%Y%m') = date_format(now(), '%Y%m')")->groupBy(DB::raw('DATE(created_at)'))->get(array(DB::raw("DATE(created_at) as created_at"))) as $date) {
//							$timesheetday = Timesheetday::whereDate($date->created_at)->whereUserId($user->id)->first();
//							if (!$timesheetday) {
//								$timesheetday = Timesheetday::create(array('date' => $date->created_at, 'user_id' => $user->id));
//							}
//							$timesheetday->pay_percent_margin = 0;
////							$timesheetday->pay_salary_day			 = $user->pay_salary_day;
////							$timesheetday->work_start_at			 = '08:59:00';
//							if ($user->pay_percent_margin) {
//								$timesheetday->pay_percent_margin	 += round(Partner::whereUserId($user->id)->checkStatus(array('statusType' => 'agreed'))->whereRaw(DB::raw('DATE(datetime_of_agree)=DATE(?)'), array($date->created_at))->pluck(DB::raw("SUM(cartprice) - SUM(purchaseprice)")) * $user->pay_percent_margin / 100, 2);
//							}
//							if ($user->pay_percent_margin_all) {
//								$timesheetday->pay_percent_margin	 += round(Partner::whereRaw('project_id IN (SELECT project_id FROM users_projects WHERE user_id=?)', array($user->id))->checkStatus(array('statusType' => 'agreed'))->whereRaw(DB::raw('DATE(datetime_of_agree)=DATE(?)'), array($date->created_at))->pluck(DB::raw("SUM(cartprice) - SUM(purchaseprice)")) * $user->pay_percent_margin_all / 100, 2);
//							}
//							$timesheetday->save();
//						}
//					}
//				}
////			}
////		}

		$lastTimesheetdays			 = Timesheetday::whereUserId($user->id)->whereRaw("date_format(date, '%Y%m') = date_format(date_sub(now(), interval 1 month), '%Y%m')")->orderBy('date', 'ASC')->get();
		$lastTimesheetdaysSalary = Timesheetday::whereUserId($user->id)->whereRaw("date_format(date, '%Y%m') = date_format(date_sub(now(), interval 1 month), '%Y%m')")->pluck(DB::raw("SUM(pay_salary_day)+SUM(pay_percent_all)+SUM(pay_percent_margin)-SUM(fines_amount)"));
		$lastTimesheetdaysSalary = round($lastTimesheetdaysSalary / 100, 2);
		if ($user->pay_salary) {
			$lastTimesheetdaysSalary = round($lastTimesheetdaysSalary + $user->pay_salary, 2);
		}

		$lastRealSalary = round(Timesheetday::whereUserId($user->id)->whereRaw("date_format(date, '%Y%m') = date_format(date_sub(now(), interval 1 month), '%Y%m')")->pluck(DB::raw("SUM(pay_salary_day)-SUM(fines_amount)")) / 100, 2);
		if ($user->pay_percent_all) {
			$lastRealSalary += round(Partner::whereUserId($user->id)->checkStatus(array('statusType' => 'agreed'))->whereRaw("date_format(date, '%Y%m') = date_format(date_sub(now(), interval 1 month), '%Y%m')")->sum('cartprice') * $user->pay_percent_all / 100, 2);
		}
		if ($user->pay_percent_margin) {
			$lastRealSalary += round(Partner::whereUserId($user->id)->checkStatus(array('statusType' => 'agreed'))->whereRaw("date_format(datetime_of_agree, '%Y%m') = date_format(date_sub(now(), interval 1 month), '%Y%m')")->pluck(DB::raw("SUM(cartprice) - SUM(purchaseprice)")) * $user->pay_percent_margin / 100, 2);
		}
		if ($user->pay_percent_margin_all) {
			$lastRealSalary += round(Partner::whereRaw('project_id IN (SELECT project_id FROM users_projects WHERE user_id=?)', array($user->id))->checkStatus(array('statusType' => 'agreed'))->whereRaw("date_format(datetime_of_agree, '%Y%m') = date_format(date_sub(now(), interval 1 month), '%Y%m')")->pluck(DB::raw("SUM(cartprice) - SUM(purchaseprice)")) * $user->pay_percent_margin_all / 100, 2);
		}
		if ($user->pay_salary) {
			$lastRealSalary = round($lastRealSalary + $user->pay_salary, 2);
		}

		$timesheetdays			 = Timesheetday::whereUserId($user->id)->whereRaw("date_format(date, '%Y%m') = date_format(now(), '%Y%m')")->orderBy('date', 'ASC')->get();
		$timesheetdaysSalary = Timesheetday::whereUserId($user->id)->whereRaw("date_format(date, '%Y%m') = date_format(now(), '%Y%m')")->pluck(DB::raw("SUM(pay_salary_day)+SUM(pay_percent_all)+SUM(pay_percent_margin)-SUM(fines_amount)"));
		$timesheetdaysSalary = round($timesheetdaysSalary / 100, 2);
		if ($user->pay_salary) {
			$timesheetdaysSalary = round($timesheetdaysSalary + $user->pay_salary, 2);
		}

		$realSalary = round(Timesheetday::whereUserId($user->id)->whereRaw("date_format(date, '%Y%m') = date_format(now(), '%Y%m')")->pluck(DB::raw("SUM(pay_salary_day)-SUM(fines_amount)")) / 100, 2);
		if ($user->pay_percent_all) {
			$realSalary += round(Partner::whereUserId($user->id)->checkStatus(array('statusType' => 'agreed'))->whereRaw("date_format(date, '%Y%m') = date_format(now(), '%Y%m')")->sum('cartprice') * $user->pay_percent_all / 100, 2);
		}
		if ($user->pay_percent_margin) {
			$realSalary += round(Partner::whereUserId($user->id)->checkStatus(array('statusType' => 'agreed'))->whereRaw("date_format(datetime_of_agree, '%Y%m') = date_format(now(), '%Y%m')")->pluck(DB::raw("SUM(cartprice) - SUM(purchaseprice)")) * $user->pay_percent_margin / 100, 2);
		}
		if ($user->pay_percent_margin_all) {
			$realSalary += round(Partner::whereRaw('project_id IN (SELECT project_id FROM users_projects WHERE user_id=?)', array($user->id))->checkStatus(array('statusType' => 'agreed'))->whereRaw("date_format(datetime_of_agree, '%Y%m') = date_format(now(), '%Y%m')")->pluck(DB::raw("SUM(cartprice) - SUM(purchaseprice)")) * $user->pay_percent_margin_all / 100, 2);
		}
		if ($user->pay_salary) {
			$realSalary = round($realSalary + $user->pay_salary, 2);
		}

		return View::make('salary.index')
										->with('timesheetdays', $timesheetdays)
										->with('timesheetdaysSalary', $timesheetdaysSalary)
										->with('realSalary', $realSalary)
										->with('lastTimesheetdays', $lastTimesheetdays)
										->with('lastTimesheetdaysSalary', $lastTimesheetdaysSalary)
										->with('lastRealSalary', $lastRealSalary)
										->with('currentUser', $user)
										->with('user', $user);
	}

	public function control() {
		$currentUser = Auth::user();

		$input = Input::all();
		if (Input::has('projectId')) {
			Session::put('salary_work_projectId', $input['projectId']);
		}
		else {
			$input['projectId'] = Session::get('salary_work_projectId');
		}
		if (!$input['projectId']) {
			$project = $currentUser->projects()->whereUsepayroll(1)->first();
			if ($project) {
				$input['projectId'] = $project->id;
				Session::put('salary_work_projectId', $input['projectId']);
			}
		}

		$workProject = Project::find(Session::get('salary_work_projectId'));
		if (!$workProject) {
			Session::forget('salary_work_projectId');
			return Redirect::to('/');
		}

		$user								 = null;
		$timesheetdays			 = array();
		$timesheetdaysSalary = 0;
		$realSalary					 = 0;

		if (Input::has('userId')) {
			Session::put('salary_work_' . $workProject->id . '_work_userId', $input['userId']);
		}
		else {
			$input['userId'] = Session::get('salary_work_' . $workProject->id . '_work_userId');
		}
		if (!$input['userId']) {
			$user = $workProject->users()->wherePayroll(1)->first();
		}
		else {
			$user = User::whereId($input['userId'])->wherePayroll(1)->first();
		}
		if ($user) {
			$input['userId'] = $user->id;
			Session::put('salary_work_' . $workProject->id . '_userId', $input['userId']);
		}

		if (!$user) {
			Session::forget('salary_work_' . $workProject->id . '_userId');
			return Redirect::to('/');
		}

		$lastTimesheetdays			 = Timesheetday::whereUserId($user->id)->whereRaw("date_format(date, '%Y%m') = date_format(date_sub(now(), interval 1 month), '%Y%m')")->orderBy('date', 'ASC')->get();
		$lastTimesheetdaysSalary = Timesheetday::whereUserId($user->id)->whereRaw("date_format(date, '%Y%m') = date_format(date_sub(now(), interval 1 month), '%Y%m')")->pluck(DB::raw("SUM(pay_salary_day)+SUM(pay_percent_all)+SUM(pay_percent_margin)-SUM(fines_amount)"));
		$lastTimesheetdaysSalary = round($lastTimesheetdaysSalary / 100, 2);
		if ($user->pay_salary) {
			$lastTimesheetdaysSalary = round($lastTimesheetdaysSalary + $user->pay_salary, 2);
		}

		$lastRealSalary = round(Timesheetday::whereUserId($user->id)->whereRaw("date_format(date, '%Y%m') = date_format(date_sub(now(), interval 1 month), '%Y%m')")->pluck(DB::raw("SUM(pay_salary_day)-SUM(fines_amount)")) / 100, 2);
		if ($user->pay_percent_all) {
			$lastRealSalary += round(Partner::whereUserId($user->id)->checkStatus(array('statusType' => 'agreed'))->whereRaw("date_format(date, '%Y%m') = date_format(date_sub(now(), interval 1 month), '%Y%m')")->sum('cartprice') * $user->pay_percent_all / 100, 2);
		}
		if ($user->pay_percent_margin) {
			$lastRealSalary += round(Partner::whereUserId($user->id)->checkStatus(array('statusType' => 'agreed'))->whereRaw("date_format(datetime_of_agree, '%Y%m') = date_format(date_sub(now(), interval 1 month), '%Y%m')")->pluck(DB::raw("SUM(cartprice) - SUM(purchaseprice)")) * $user->pay_percent_margin / 100, 2);
		}
		if ($user->pay_percent_margin_all) {
			$lastRealSalary += round(Partner::whereRaw('project_id IN (SELECT project_id FROM users_projects WHERE user_id=?)', array($user->id))->checkStatus(array('statusType' => 'agreed'))->whereRaw("date_format(datetime_of_agree, '%Y%m') = date_format(date_sub(now(), interval 1 month), '%Y%m')")->pluck(DB::raw("SUM(cartprice) - SUM(purchaseprice)")) * $user->pay_percent_margin_all / 100, 2);
		}
		if ($user->pay_salary) {
			$lastRealSalary = round($lastRealSalary + $user->pay_salary, 2);
		}

		$timesheetdays			 = Timesheetday::whereUserId($user->id)->whereRaw("date_format(date, '%Y%m') = date_format(now(), '%Y%m')")->orderBy('date', 'ASC')->get();
		$timesheetdaysSalary = Timesheetday::whereUserId($user->id)->whereRaw("date_format(date, '%Y%m') = date_format(now(), '%Y%m')")->pluck(DB::raw("SUM(pay_salary_day)+SUM(pay_percent_all)+SUM(pay_percent_margin)-SUM(fines_amount)"));
		$timesheetdaysSalary = round($timesheetdaysSalary / 100, 2);
		if ($user->pay_salary) {
			$timesheetdaysSalary = round($timesheetdaysSalary + $user->pay_salary, 2);
		}

		$realSalary = round(Timesheetday::whereUserId($user->id)->whereRaw("date_format(date, '%Y%m') = date_format(now(), '%Y%m')")->pluck(DB::raw("SUM(pay_salary_day)-SUM(fines_amount)")) / 100, 2);
		if ($user->pay_percent_all) {
			$realSalary += round(Partner::whereUserId($user->id)->checkStatus(array('statusType' => 'agreed'))->whereRaw("date_format(date, '%Y%m') = date_format(now(), '%Y%m')")->sum('cartprice') * $user->pay_percent_all / 100, 2);
		}
		if ($user->pay_percent_margin) {
			$realSalary += round(Partner::whereUserId($user->id)->checkStatus(array('statusType' => 'agreed'))->whereRaw("date_format(datetime_of_agree, '%Y%m') = date_format(now(), '%Y%m')")->pluck(DB::raw("SUM(cartprice) - SUM(purchaseprice)")) * $user->pay_percent_margin / 100, 2);
		}
		if ($user->pay_percent_margin_all) {
			$realSalary += round(Partner::whereRaw('project_id IN (SELECT project_id FROM users_projects WHERE user_id=?)', array($user->id))->checkStatus(array('statusType' => 'agreed'))->whereRaw("date_format(datetime_of_agree, '%Y%m') = date_format(now(), '%Y%m')")->pluck(DB::raw("SUM(cartprice) - SUM(purchaseprice)")) * $user->pay_percent_margin_all / 100, 2);
		}
		if ($user->pay_salary) {
			$realSalary = round($realSalary + $user->pay_salary, 2);
		}

//			foreach ($timesheetdays as $timesheetday) {
//				$workDate													 = $timesheetday->date;
//				$lastDatePayroll									 = array();
//				$lastDatePayroll['date']					 = $workDate;
//				$lastDatePayroll['sum']						 = 0;
//				$lastDatePayroll['pay_salary_day'] = 0;
//				if ($timesheetday && $timesheetday->pay_salary_day) {
//					$lastDatePayroll['pay_salary_day'] = $timesheetday->pay_salary_day;
//					$lastDatePayroll['sum'] += $lastDatePayroll['pay_salary_day'];
//				}
//				elseif ($timesheetday && $user->pay_salary_day) {
//					$lastDatePayroll['pay_salary_day'] = $user->pay_salary_day;
//					$lastDatePayroll['sum'] += $lastDatePayroll['pay_salary_day'];
//					$timesheetday->pay_salary_day			 = $lastDatePayroll['pay_salary_day'];
//				}
//				$lastDatePayroll['late_fee'] = 0;
//				if ($timesheetday && $timesheetday->late_fee) {
//					$lastDatePayroll['late_fee']			 = $timesheetday->late_fee;
//					$lastDatePayroll['work_start_at']	 = $timesheetday->work_start_at;
//					$lastDatePayroll['sum'] -= $lastDatePayroll['late_fee'];
//				}
//				$lastDatePayroll['pay_percent_all'] = 0;
//				if ($timesheetday && $user->pay_percent_all) {
//					$lastDatePayroll['pay_percent_all']	 = round(Partner::whereUserId($user->id)->checkStatus(array('statusType' => 'agreed'))->whereRaw(DB::raw('DATE(datetime_of_agree)=DATE(?)'), array($workDate))->sum('cartprice') * $user->pay_percent_all / 100, 2);
//					$lastDatePayroll['sum'] += $lastDatePayroll['pay_percent_all'];
//					$timesheetday->pay_percent_all			 = $lastDatePayroll['pay_percent_all'];
//				}
//				$lastDatePayroll['pay_percent_margin'] = 0;
//				$timesheetday->pay_percent_margin = 0;
//				if ($timesheetday && $user->pay_percent_margin) {
//					$lastDatePayroll['pay_percent_margin'] = round(Partner::whereUserId($user->id)->checkStatus(array('statusType' => 'agreed'))->whereRaw(DB::raw('DATE(datetime_of_agree)=DATE(?)'), array($workDate))->pluck(DB::raw("SUM(cartprice) - SUM(purchaseprice)")) * $user->pay_percent_margin / 100, 2);
//					$lastDatePayroll['sum'] += $lastDatePayroll['pay_percent_margin'];
//					$timesheetday->pay_percent_margin			 = $lastDatePayroll['pay_percent_margin'];
//				}
//				if ($timesheetday && $user->pay_percent_margin_all) {
//					$lastDatePayroll['pay_percent_margin'] += round(Partner::checkStatus(array('statusType' => 'agreed'))->whereRaw(DB::raw('DATE(datetime_of_agree)=DATE(?)'), array($workDate))->pluck(DB::raw("SUM(cartprice) - SUM(purchaseprice)")) * $user->pay_percent_margin_all / 100, 2);
//					$lastDatePayroll['sum'] += $lastDatePayroll['pay_percent_margin'];
//					$timesheetday->pay_percent_margin += $lastDatePayroll['pay_percent_margin'];
//				}
//				if ($timesheetday) {
//					$timesheetday->save();
//				}
//			}

		return View::make('salary.control')
										->with('workProject', $workProject)
										->with('timesheetdays', $timesheetdays)
										->with('timesheetdaysSalary', $timesheetdaysSalary)
										->with('realSalary', $realSalary)
										->with('lastTimesheetdays', $lastTimesheetdays)
										->with('lastTimesheetdaysSalary', $lastTimesheetdaysSalary)
										->with('lastRealSalary', $lastRealSalary)
										->with('user', $user)
										->with('currentUser', $currentUser);
	}

	public function cancel() {
		$input						 = Input::all();
		$timesheetdayFine	 = TimesheetdayFine::find($input['id']);
		if (!is_numeric($input['id']) || !$timesheetdayFine) {
			$response = array('status' => 'fail');
			return Response::json($response);
		}

		$timesheetdayFine->comment				 = $input['comment'];
		$timesheetdayFine->delete_user_id	 = Auth::user()->id;
		$timesheetdayFine->save();

		$timesheetday = Timesheetday::whereDate($timesheetdayFine->date)->whereUserId($timesheetdayFine->user_id)->first();
		if ($timesheetday) {
			$timesheetday->fines_amount -= $timesheetdayFine->value;
			$timesheetday->save();
		}

		$timesheetdayFine->delete();

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

	public function restore() {
		$input						 = Input::all();
		$timesheetdayFine	 = TimesheetdayFine::withTrashed()->find($input['id']);
		if (!is_numeric($input['id']) || !$timesheetdayFine) {
			$response = array('status' => 'fail');
			return Response::json($response);
		}

		$timesheetdayFine->restore();

		$timesheetday = Timesheetday::whereDate($timesheetdayFine->date)->whereUserId($timesheetdayFine->user_id)->first();
		if ($timesheetday) {
			$timesheetday->fines_amount += $timesheetdayFine->value;
			$timesheetday->save();
		}

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

}
