<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\TimelogEdit;
use App\Models\ProcessedTimelog;
use App\Models\RoleCompanyAccess;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use PHPUnit\Event\Code\Throwable;

class TimelogEditController extends Controller
{
    public function index(Request $request)
    {
        //
        $user = Auth::user();
        $keyword = $request->input('keyword', '');
        $perPage = $request->input('per_page',PHP_INT_MAX);
        $sortBy = $request->input('sortBy', '');
        $sortType = $request->input('sortType', '');

        $rolesWithSystemId3 = $user->roles->filter(function($role) {
            return $role->group && $role->group->system_id === 3;
        });

        // Get dealers for ALL roles with system_id 3
        $dealers = [];
        if ($rolesWithSystemId3->isNotEmpty()) {
            $roleIds = $rolesWithSystemId3->pluck('id')->toArray();
            
            $dealers = RoleCompanyAccess::whereIn('role_id', $roleIds)
                ->pluck('dealership_id')
                ->unique()
                ->toArray();
        }

        $data = TimelogEdit::with(['employee','requested_by'])
            ->where(function ($query) use ($keyword, $dealers) {
                $keyword = str_replace(" ", "%", $keyword);
                $query->where('employee_id', 'like', $keyword . '%')->orWhere('date', 'like', $keyword . '%');
            })
            ->whereIn('dealership_id', $dealers);

        if (!empty($sortBy) && !empty($sortType)) {
            $data = $data->orderBy($sortBy, $sortType);
        }

        if ($request->date_created) {
            $dates = explode(' to ', $request->date_created); // Split into start and end date
            if (count($dates) == 2) {
                $data = $data->whereBetween('created_at', [$dates[0], $dates[1]]);
            }
        }

        if ($request->range) {
            $dates = explode(' to ', $request->range); // Split into start and end date
            if (count($dates) == 2) {
                $data = $data->whereBetween('date', [$dates[0], $dates[1]]);
            }
        }
        
        if ($request->status && is_array($request->status)) {
            $data = $data->where(function ($query) use ($request) {
                if (in_array('pending', $request->status)) {
                    $query->orWhere('approved', 0);
                }

                if (in_array('for validation', $request->status)) {
                    $query->orWhere('approved', 0);
                }
        
                if (in_array('validated', $request->status)) {
                    $query->orWhere(function ($q) {
                        $q->where('approved', 1);
                    });
                }
            });
        }        

        $data = $data->orderBy('approved', 'DESC')->get();

        return response()->json(['data' => $data]);
    }

    public function approve(int $id)
    {
        $data = TimelogEdit::find($id);

        /** If no record found return with error message */
        if (!$data) {
            return response()->json([
                'status'  => false,
                'message' => 'Record not found!',
            ], 422);
        }

        DB::beginTransaction();

        try {

            $data->fill([
                'approved' => 1,
                'approved_by' => auth()->user()->employee_id,
                'approved_at' => $this->current_datetime,
            ]);
            $data->touch();
            $data->save();

            $where =  [
                'payroll_date' => $data->payroll_date,
                'company_id' => $data->company_id,
                'dealership_id' => $data->dealership_id,
                'employee_id' => $data->employee_id,
                'date' => $data->date,
                'in_out' => $data->in_out,
            ];
            $updateData =[
                'payroll_date' => $data->payroll_date,
                'company_id' => $data->company_id,
                'dealership_id' => $data->dealership_id,
                'department_id' => $data->department_id,
                'employee_id' => $data->employee_id,
                'date' => $data->date,
                'time' => $data->time,
                'in_out' => $data->in_out,
            ];

            $timelog = ProcessedTimelog::where($where)->first();
            if(!is_null($timelog)) {
                ProcessedTimelog::where($where)->update($updateData);
            } else {
                ProcessedTimelog::create($updateData);
            }

            DB::commit();

            return response()->json([
                'message' => 'Record Successfully approved!',
                'status' => 'success',
            ],201);

        } catch (Throwable $e) {
            DB::rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        }
    }


    public function destroy(int $id)
    {
        $data = TimelogEdit::find($id);
        if(!$data)
        {
            return response()->json(['message' => "Record not found!"],204);
        }
        DB::connection()->beginTransaction();
        $data->delete();
        DB::connection()->commit();
        return response()->json(['message' => "Record successfully deleted!"],201);
    }
}
