<?php

namespace App\Http\Controllers\API\v1;
use App\Http\Controllers\Controller;
use App\Models\Employee;
use App\Models\EmployeeBenefits;
use App\Models\RoleCompanyAccess;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Throwable;

class EmployeeBenefitsController 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', '');
        $dealership_id = $request->input('dealership', null);

        $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();
        }

        DB::enableQueryLog();
        $data = EmployeeBenefits::with(['employee', 'benefit'])
            ->where(function ($query) use ($keyword, $dealers) {
                $keyword = str_replace(" ", "%", $keyword);
                $query->whereIn('dealer_id', $dealers)
                    ->where(function ($q) use ($keyword) {
                        $q->where('employee_id', 'like', '%' . $keyword . '%')
                            ->orWhereHas('employee', fn($subQ) => $subQ->where('firstname', 'like', '%' . $keyword . '%')
                                ->orWhere('middlename', 'like', '%' . $keyword . '%')
                                ->orWhere('lastname', 'like', '%' . $keyword . '%'))
                            ->orWhereHas('benefit', fn($subQ) => $subQ->where('name', 'like', '%' . $keyword . '%'));
                    });
            })
            ->whereHas('benefit');

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

        if ($request->id) {
            try {
                $id = Crypt::decrypt($request->id);
            } catch (\Illuminate\Contracts\Encryption\DecryptException $e) {
                $id = $request->id;
            }
            $data->where('employee_id', $id);
        }

        // if ($user->roles[0]->group_id != 1 && $user->roles[0]->group_id != 2) {
        //     $data->whereHas('employee', fn($q) => $q->where('dealer_id', $dealership_id));
        // }

        $data = $data->paginate($perPage);

        // dd(DB::getQueryLog());

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

    public function store(Request $request)
    {
        // Validate the incoming request data
        $validator = Validator::make($request->all(), [
            'employee_id' => [
                'required',
            ],
            'date_from' => [
                '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);
        }

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

        try {

            foreach ($request->employee_id as $employee) {

                try {
                    $request['employee_id'] = Crypt::decrypt($employee);
                    $employee = Crypt::decrypt($employee);
                } catch (\Illuminate\Contracts\Encryption\DecryptException $e) {
                    $request['employee_id'] = $employee;
                }

                $employee_info = Employee::select('company_id', 'dealer_id')->where('employee_id', $employee)->first();

                $request['company_id'] = $employee_info->company_id;
                $request['dealer_id'] = $employee_info->dealer_id;

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

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

            // $data = EmployeeBenefits::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 update(Request $request, int $id)
    {
        $data = EmployeeBenefits::where('id', $id)->first();

        if (!$data) {
            return response()->json(['messages' => 'No data found.'], 404);
        }

        $validator = Validator::make($request->all(), [
            'employee_id' => [
                'required',
            ],
            'date_from' => [
                '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);
        }

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

        try {

            $data->fill($request->all());
            $data->save();

            $data->touch();

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

            return response()->json([
                'message' => 'Record Successfully updated!',
                'status' => 'success',
                'data' => $data,
            ],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 destroy(int $id)
    {
        $data = EmployeeBenefits::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);
    }
}
