<?php
namespace App\Modules\Mobile\Supervisor;

use App\Models\Projects;
use App\Models\ProjectSupervisors;
use App\Models\CompanyWorkerTimesheet;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\Traits\UserTraits;
use App\Traits\CreateMobileNotificationTraits;

class ManageTimelogs extends Controller {

	use UserTraits, CreateMobileNotificationTraits;

	public function getProjects($payload){
		$current_date = Carbon::parse($payload->currentDate)->toDateString();
		$dateWithFormat = Carbon::parse($payload->currentDate)->format('Y-m-d');
		$worker_id    = Auth::user()->id; //supervisor id

		return ProjectSupervisors::select(
			'project_supervisors.id as project_supervisor_id',
			'projects.id as project_id',
			'projects.name',
			'projects.clock_in',
			'projects.clock_out',
			'projects.location',
			'projects.date_end',
			'company_workers_timesheet.id',
			'company_workers_timesheet.date',
			'company_workers_timesheet.status',
			'company_workers_timesheet.total_hours',
			'company_workers_timesheet.time_in',
			'company_workers_timesheet.time_out',
			'company_workers_timesheet.time_out',
			'company_workers_timesheet.request_modification_message as message',
			DB::raw('IFNULL(company_workers_timesheet.id, null) as timesheet_id'),
		)
		->join('projects', 'projects.id', 'project_supervisors.project_id')
		->leftJoin('company_workers_timesheet', function ($query) use ($current_date){
			$query->on('company_workers_timesheet.reference_id', '=', 'projects.id')
			->where('company_workers_timesheet.date', $current_date)
			->distinct();
		})
		->where('user_id', $worker_id)
    	->where('project_supervisors.date_to', '>=', $current_date)
		->where('projects.date_end', '>=', $current_date)
		->where('projects.deleted_at', null)
		->where('company_workers_timesheet.deleted_at', null)	
		->get();
	}   

	public function submitTimelog($payload, $id = 0) {
		// Log::info("Timelog reference ID: " . $id); // 0: new data, > 0: updating data

		$this->validate($payload, [
			'time_in' => 'required',
			'time_out' => 'required'
		]);

		$data = array(
			'worker_id'    => Auth::user()->id,
			'company_id'   => $this->getCurrentUser()->company_id,
			'date'         => Carbon::parse($payload->date),
			'reference_id' => $payload->project_id,
			'rate'         => $this->getCurrentUserRate(),
			'description'  => "Hours rendered for project " . $payload->name,
			'status'       => $payload->status,
			'time_in'      => $payload->time_in,
			'time_out'     => $payload->time_out,
			'total_hours'  => $payload->total_hours,
			'type'         => $payload->type,
			'role'         => 'supervisor'
		);

		//check parameter need to be used : date and project id
		$hasDuplicate = CompanyWorkerTimesheet::where('date', Carbon::parse($payload->date)->format('Y-m-d'))
			->where('reference_id', $payload->project_id)
			->where('worker_id', Auth::user()->id)
			->where('role', 'supervisor')
			->count() > 1;

		if ($id != 0 || !$hasDuplicate) 
		{
			// Update data
			$submitTimelog = CompanyWorkerTimesheet::findOrFail($id);
			$submitTimelog->time_in = $payload->time_in;
			$submitTimelog->time_out = $payload->time_out;
			$submitTimelog->total_hours  = $payload->total_hours;
			$submitTimelog->save();
		} 
		else 
		{
			$submitTimelog = CompanyWorkerTimesheet::create($data);
		}

		$workerFullName = Auth::user()->first_name ." ". Auth::user()->first_name;

		$mobileNotificationData = array(
			'worker_id' => $this->fetchProjectManagerID($payload->project_id),
			'message'   => $workerFullName .' submitted a Time Log.',
			'type'      => 'user',
			'link'      => '/company/manager/supervisor/timelog',
		);

		$this->createMobileNotification($mobileNotificationData);
		
		return $submitTimelog;
	}

	function getSupervisorsProject($worker_id, $existing_project_id, $date) {
		$pendingSchedules = array();
		
		$projects = ProjectSupervisors::select(
			'projects.clock_in as time_in',
			'projects.clock_out as time_out',
			'projects.id as project_id',
			'projects.name',
			'projects.description',
			'projects.clock_in',
			'projects.clock_out',
			'projects.location'                                        
		)
		->leftJoin('projects','projects.id', 'project_supervisors.project_id')
		->join('workers' ,'workers.id', 'project_supervisors.user_id')
		->whereRaw('? BETWEEN project_supervisors.date_from and project_supervisors.date_to', [$date])
		->where('project_supervisors.user_id', $worker_id)
		->get()
		->toArray();
		
		foreach ($projects as $project) {
			if (!in_array($project['project_id'], $existing_project_id)) {
				// Log::debug('TRUE');
				array_push($pendingSchedules, [
					'timesheet_id'        => null,
					'name'                => $project['name'],
					'date'                => $date,  
					'clock_in'            => $project['clock_in'],
					'clock_out'           => $project['clock_out'],
					'time_in'             => $project['time_in'],
					'time_out'            => $project['time_out'],
					'total_hours'         => 0,
					'status'              => 'pending',
					'project_id'          => $project['project_id']
				]);
			}
			# code...
		}

		return $pendingSchedules;
	}

	public function GeneratePeriod($date_from,$date_to){
		$datePreiod = CarbonPeriod::create(Carbon::parse($date_from), Carbon::parse($date_to));

		return [
			'period' => $datePreiod
		] ;
	}

	public function fetchProjectManagerID($projectID){
		$project = Projects::where('id', $projectID)->first();
		return $project->project_manager_id;
	}
}