<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;
use App\Models\Timelog;
use App\Models\Employee;
use App\Models\TimelogSync;
use App\Models\EmployeeSync;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use PHPUnit\Event\Code\Throwable;

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

    //     // Generate a unique cache key based on request parameters
    //     $cacheKey = 'companies_' . md5(json_encode([
    //         'keyword' => $keyword,
    //         'perPage' => $perPage,
    //         'sortBy' => $sortBy,
    //         'sortType' => $sortType,
    //     ]));

    //     // Check if data exists in cache, otherwise execute the query and cache the result
    //     $data = Cache::remember($cacheKey, 60, function () use ($keyword, $perPage, $sortBy, $sortType) {
    //         return Timelog::where(function ($query) use ($keyword) {
    //                 $keyword = str_replace(" ", "%", $keyword);
    //                 $query->where('name', 'like', '%' . $keyword . '%')
    //                     ->orWhere('code', 'like', '%' . $keyword . '%');
    //             })
    //             ->when(!empty($sortBy) && !empty($sortType), function ($query) use ($sortBy, $sortType) {
    //                 $query->orderBy($sortBy, $sortType);
    //             })
    //             ->paginate($perPage);
    //     });

    //     return response()->json($data);
    // }

    public function getEmployeeTimelogs(string $id)
    {
        try {
            $id = Crypt::decrypt($id);
        } catch (\Illuminate\Contracts\Encryption\DecryptException $e) {
            $id = $id;
        }

        $year = date('Y');

        $data = Timelog::where('employee_id', '=', $id)->whereYear('datetimelog', $year)->get();

        // dd($data);
        return response()->json($data);
    }

    public function store(Request $request)
    {
        // Validate the incoming request data
        $validator = Validator::make($request->all(), [
            'employee_id' => [
                'required',
            ],
            'time_keeping_id' => [
                'required',
            ],
            'datetimelog' => [
                'required',
            ],
        ]);
        
        /** If validation fails return with error message */
        if ($validator->fails()) {
            $errors = $validator->errors();
            $first = $errors->getMessages();
            return response()->json([
                'status'  => false,
                'message' => (reset($first))[0],
                'errors'  => $errors
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }
        dd($request->all());
        DB::connection()->beginTransaction();

        try {

            $data = Timelog::create($request->all());

            DB::connection()->commit();

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

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

    public function sync_bio(Request $request)
    {
        
        $employee = EmployeeSync::where('employee_id', '=', $request->time_keeping_id)->first();

        if ($employee) {
            $request['employee_id'] = $employee->employee_id;
        } else {
            $request['employee_id'] = $request->time_keeping_id;
        }

        // dd($request->all());
        // Validate the incoming request data
        $validator = Validator::make($request->all(), [
            'time_keeping_id' => [
                'required',
            ],
            'datetimelog' => [
                'required',
            ],
        ]);
        
        /** If validation fails return with error message */
        if ($validator->fails()) {
            $errors = $validator->errors();
            $first = $errors->getMessages();
            return response()->json([
                'status'  => false,
                'message' => (reset($first))[0],
                'errors'  => $errors
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        // dd($request->all());

        DB::connection()->beginTransaction();

        try {

            $data = TimelogSync::create($request->all());

            DB::connection()->commit();

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

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


    public function show(Request $request)
    {
        $dateTo = date('Y-m-d', strtotime($request->dateTo . '+1 day'));

        $query = Employee::with([
            'timelog' => function ($query) use ($request, $dateTo) {
                $query->whereBetween('datetimelog', [$request->dateFrom, $dateTo]);
            },
            'company',
            'department'
        ])->where(['enabled' => 1]);

        if (!empty($request->employee_id)) {
            $query->where('employee_id', $request->employee_id);
        }

        if (!empty($request->department_id)) {
            $query->where('department_id', $request->department_id);
        }

        $data = $query->get();

        return response()->json($data);
    }

    public function destroy(int $id)
    {
        $data = Timelog::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);
    }

    public function timelogFromOtherDealer(Request $request)
    {
        $employee_id = $request->input('employee_id',null);
        $company_id = $request->input('company_id', null);
        $dealer_id = $request->input('dealer_id', null);
        $date_from = $request->input('date_from', null);
        $date_to = $request->input('date_to', null);

        $query = Timelog::select('employees.employee_id', 'employees.lastname', 'employees.firstname', 'employees.dealer_id', 'dealerships.name as dealership_name', 'timelogs.datetimelog', 'timelogs.machine_id', 'log_from.name AS login_from_dealer', 'log_from.id as login_from_id')
            ->join('employees','timelogs.employee_id','=','employees.employee_id')
            ->join('dealerships','employees.dealer_id','=','dealerships.id')
            ->join('dealerships AS log_from',function($q) {
                $q->whereRaw(
                'FIND_IN_SET(timelogs.machine_id, log_from.machine_sn)');
            })
            ->when($employee_id, fn($q) =>
                $q->where('timelogs.employee_id',$employee_id)
            )
            ->when($company_id, fn($q) =>
                $q->where('employees.company_id',$company_id)
            )
            ->when($dealer_id, fn($q) =>
                $q->whereIn('employees.dealer_id', explode(',', $dealer_id) )
            )
            ->when($date_from, fn($q)=> $q->whereDate('datetimelog', '>=', $date_from))
            ->when($date_to, fn($q)=> $q->whereDate('datetimelog', '<=', $date_to))
            ->whereRaw("employees.dealer_id != log_from.id");

        $data = $query->get();

        return response()->json($data);
    }
}
