<?php

namespace App\Modules\Hr\controllers\api\v2;

use Illuminate\Support\Facades\Response;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\Exceptions\PermissionDeniedException;
use App\Http\Controllers\BaseController;

class TimeLogControllerRESTv2 extends BaseController
{
    public function index(Request $request)
    {
        $userId =  Auth::user()->id;
        if ($request->input('userId')) {
            $userId = $request->input('userId');
        }

        $this->isAdminOrMe($userId);
        $query = TimeLog::query()->with('pending_change_requests')->where('user_id', $userId);
        if ($request->input('start') && $request->input('end')) {
            $from = new Carbon($request->input('start'));
            $to   = new Carbon($request->input('end'));
            $query->whereBetween('time', [$from, $to]);
        }

        $query = $query->paginate($request->input('limit', 100));

        return [
            'data'         => $query->getCollection()->toArray(),
            'total'        => $query->total(),
            'current_page' => $query->currentPage(),
            'last_page'    => $query->lastPage(),
            'per_page'     => $query->perPage(),
            'from'         => $query->firstItem(),
            'to'           => $query->lastItem(),
        ];
    }

    public function store(Request $request)
    {
        if ($request->input('lunch') && !$request->input('time')) {
            return $this->storeLunch($request);
        }
        $lunch = $request->input('lunch');
        $type = $request->input('type');
        $isRequest = false;
        $time =  new Carbon($request->input('time'));
        $userId =  Auth::user()->id;


        $record = new TimeLog(
            [
                'user' => $userId,
                'type' => $type,
                'time' => $time,
                'lunch' => $lunch
            ]
        );
        if (!$record->save()) {
            return Response::json(['errors' => $record->errors->all()], 400);
        }

        if (!Auth::user()->hasPermission('access_hr') && $request->input('time')) {
            TimeLogChangeRequest::create(['time_log_id' => $record->id, 'time' => $record->time]);
            $record->pending_change_request = true;
        }

        if (!$record->save()) {
            return Response::json(['errors' => $record->errors->all()], 400);
        }

        return $record;
    }

    public function storeLunch(Request $request)
    {
        $lastRecord = TimeLog::query()->lastRecord()->first();
        if (!$lastRecord) {
            return Response::json(['error' => 'You need to be clocked in to go to lunch.'], 400);
        }
        //lunch clockin
        if ($request->input('lunch') && $request->input('type') == 'in'  && $lastRecord->lunch) {

            $end = new carbon($request->input('time'));
            $end->addMinutes(30);

            //to late 
            if ($end < Carbon::now()) {
                $out =  TimeLog::create(['type' => 'out', 'lunch' => 1, 'time' => $end]);
                $in = TimeLog::create(['type' => 'in', 'time' => Carbon::now()->addSeconds(1)]);
                return  Response::json($in);
            } else {
                //on time
                $out = TimeLog::create(['type' => 'out', 'lunch' => 1, 'time' => Carbon::now()]);
                $in = TimeLog::create(['type' => 'in', 'time' => Carbon::now()->addSeconds(1)]);
                return  Response::json($in);
            }
        }
        //if has had lunch today
        $lastLunch = TimeLog::query()->LastlunchRecord()->first();
        if ($lastLunch) {
            $lastLunchTime = new carbon($request->input('time'));
            if ($lastLunchTime->isToday()) {
                return Response::json(['error' => 'You have had your lunch for today.'], 400);
            }
        }

        //lunch clockout
        if ($request->input('lunch') && $request->input('type') == 'out' && !$lastRecord->lunch && $lastRecord->type == 'in') {
            //lunch clockout
            $out = TimeLog::create(['type' => 'out']);
            $in = TimeLog::create(['type' => 'in', 'lunch' => 1, 'time' => Carbon::now()->addSeconds(1)]);
            return  Response::json($in);
        }


        return Response::json(['error' => 'You need to be clocked in to go to lunch.'], 400);
    }
    public function show($id)
    {
        $record = TimeLog::query()->where('id', $id)->first();
        if (!$record) {
            abort(404);
        }
        if (Auth::id() == $record->user_id) {
            return $record;
        }

        if (Auth::user()->hasPermission('access_hr')) {
            return $record;
        }
    }
    public function update(Request $request, $id)
    {

        $record = TimeLog::query()->where('id', $id)->first();

        if (!$record) {
            abort(404);
        }
        if ($request->get('status')) {
            if ($request->get('status') == "approved") {

                $timeLogChangeRequest = TimeLogChangeRequest::query()->where('time_log_id', $id);
                $timeLogChangeRequest->update(['completed' => 1]);
                $record->time = $timeLogChangeRequest->first()->time;
            } else if ($request->get('status') == "decline") {
                TimeLogChangeRequest::query()->where('time_log_id', $id)->update(['declined' => 1]);
            }
            $record->pending_change_request = false;
            $record->save();
            return $record;
        }
        if (Auth::id() == $record->user_id || Auth::user()->hasPermission('access_hr')) {
            return $this->request($request, $id, $record);
        }

        throw new PermissionDeniedException();
    }
    public function request(Request $request, $id, $record)
    {
        $record->time = $request->get('time');
        $record->pending_change_request = true;
        TimeLogChangeRequest::create(['time_log_id' => $record->id, 'time' => $record->time]);
        return $record;
    }
    private function isAdminOrMe($requestUserId)
    {
        $userId = Auth::id();
        if (
            Auth::user()->hasPermission('access_hr') ||
            $userId == $requestUserId
        ) {
            return true;
        }

        throw new PermissionDeniedException();
    }
}
