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

use App\Models\CompanyWorkerTimesheet;
use App\Models\Projects;
use App\Traits\UserTraits;
use App\Traits\ValidatorTraits;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class ManageTimelogs
{
    use UserTraits, ValidatorTraits;

    public function getTimelogs($payload)
    {
        $currentDate = Carbon::parse($payload->params['currentDate'] ? $payload->params['currentDate'] : $this->getServerTodayDate())->toDateString();
        $worker_id = Auth::user()->id;

        $projects = Projects::where('project_manager_id', $worker_id)
            ->where(function ($query) use ($currentDate) {
                $query->where('date_start', $currentDate)
                    ->orWhere('date_end', $currentDate)
                    ->orWhereBetween('date_start', [$currentDate, $currentDate])
                    ->orWhereBetween('date_end', [$currentDate, $currentDate])
                    ->orWhereRaw('? BETWEEN date_start and date_end', [$currentDate])
                    ->orWhereRaw('? BETWEEN date_start and date_end', [$currentDate]);
            })
            ->get();

        $data = [];
        if (!$projects->isEmpty()) {
            foreach ($projects as $project) {
                $timesheet = CompanyWorkerTimesheet::select(
                    'company_workers_timesheet.id',
                    'company_workers_timesheet.date',
                    'company_workers_timesheet.total_hours',
                    'company_workers_timesheet.time_in',
                    'company_workers_timesheet.time_out',
                    'company_workers_timesheet.status',
                    'company_workers_timesheet.reference_id',
                    'companies.name as company_name'
                )
                    ->join('companies', 'companies.id', 'company_workers_timesheet.company_id')
                    ->whereDate('date', $currentDate)
                    ->where('worker_id', $worker_id)
                    ->where('reference_id', $project->id)
                    ->where('company_workers_timesheet.role', 'manager')
                    ->first();

                if ($timesheet) {
                    array_push($data, [
                        "id" => $timesheet->id,
                        "project_id" => $project->id,
                        "project_name" => $project->name,
                        "date" => $timesheet->date,
                        "total_hours" => $timesheet->total_hours,
                        "company_name" => $this->getCurrentUserCompanyName()->name,
                        "time_in" => $timesheet->time_in,
                        "time_out" => $timesheet->time_out,
                        "status" => $timesheet->status,
                    ]);
                } else {
                    array_push($data, [
                        "project_id" => $project->id,
                        "project_name" => $project->name,
                        "date" => $currentDate,
                        "total_hours" => 0,
                        "company_name" => $this->getCurrentUserCompanyName()->name,
                        "time_in" => '09:00',
                        "time_out" => '18:00',
                        "status" => "pending",
                        "warning" => [
                            "type" => "warning",
                            "message" => "Please enter your rendered hours for the day.",
                        ],
                    ]);
                }
            }
        } else {
            array_push($data, [
                "project_id" => null,
                "project_name" => "N/A",
                "date" => $currentDate,
                "total_hours" => 0,
                "company_name" => $this->getCurrentUserCompanyName()->name,
                "time_in" => '09:00',
                "time_out" => '18:00',
                "status" => "pending",
                "warning" => [
                    "type" => "warning",
                    "message" => "No project assigned for this date.",
                ],
            ]);
        }

        return $data;
    }

    public function submitTimelog($payload, $id = 0)
    {
        $worker_rate = $this->getCurrentUserRate();

        Log::info("Timelog reference ID: " . $id); // 0: new data, > 0: updating data

        $rules = array(
            'time_in' => 'required',
            'time_out' => 'required',
        );
        $validate = $this->validateRequest($payload, $rules);
        if ($validate) {
            return $validate;
        }

        $data = array(
            'worker_id' => Auth::user()->id,
            'company_id' => $this->getCurrentUser()->company_id,
            'date' => Carbon::parse($payload->date),
            'reference_id' => $payload->ref_id,
            'rate' => $worker_rate,
            'description' => "Hours rendered for company (regular work)",
            'request_modification_message' => '',
            'status' => 'approved',
            'time_in' => $payload->time_in,
            'time_out' => $payload->time_out,
            'total_hours' => $payload->total_hours,
            'type' => $payload->type,
            'role' => 'manager',
        );

        if ($id != 0) {
            // Update data
            $submitTimelog = CompanyWorkerTimesheet::where('id', $id)->first();
            $submitTimelog->time_in = $payload->time_in;
            $submitTimelog->time_out = $payload->time_out;
            $submitTimelog->total_hours = $payload->total_hours;
            $submitTimelog->save();
        } else {
            // Create new data
            $submitTimelog = CompanyWorkerTimesheet::create($data);
        }

        return $submitTimelog;
    }
}
