<?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\MrfApprover;
use App\Models\RoleCompanyAccess;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use PHPUnit\Event\Code\Throwable;

class MrfApproverController 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', '');

        // Process keyword once
        $processedKeyword = str_replace(" ", "%", $keyword);

        $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 = MrfApprover::with([
            'dealership',
            'group_division',
            'department',
            'division',
            'endorser',
            'approver'
        ])
        ->whereIn('dealer_id', $dealers)
        ->when(!empty($keyword), function ($query) use ($processedKeyword) {
            $query->where(function ($q) use ($processedKeyword) {
                // Search in relationships that exist
                $q->whereHas('dealership', function ($subQuery) use ($processedKeyword) {
                    $subQuery->where('name', 'like', "%{$processedKeyword}%");
                })
                ->orWhereHas('group_division', function ($subQuery) use ($processedKeyword) {
                    $subQuery->where('name', 'like', "%{$processedKeyword}%");
                })
                ->orWhereHas('department', function ($subQuery) use ($processedKeyword) {
                    $subQuery->where('name', 'like', "%{$processedKeyword}%");
                })
                ->orWhereHas('division', function ($subQuery) use ($processedKeyword) {
                    $subQuery->where('name', 'like', "%{$processedKeyword}%");
                })
                ->orWhereHas('section', function ($subQuery) use ($processedKeyword) {
                    $subQuery->where('name', 'like', "%{$processedKeyword}%");
                });
            });
        })
        ->when(!empty($sortBy) && !empty($sortType), function ($query) use ($sortBy, $sortType) {
            $query->orderBy($sortBy, $sortType);
        })
        ->paginate($perPage);

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

    public function store(Request $request)
    {
        // Validate the incoming request data
        $validator = Validator::make($request->all(), [
            'company_id' => 'required',
            'dealer_id' => 'required',
            'group_id' => 'required',
            'division_id' => 'required',
            'department_id' => 'required',
            'endorser' => 'required',
            'approver' => '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 = MrfApprover::create($request->all());

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

            // Invalidate cache for 'mrf_approvers_list' key when a new approver is added
            Cache::forget('mrf_approvers_list');

            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 = MrfApprover::where('id', $id)->first();

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

        $validator = Validator::make($request->all(), [
            'company_id' => 'required',
            'dealer_id' => 'required',
            'group_id' => 'required',
            'division_id' => 'required',
            'department_id' => 'required',
            'endorser' => 'required',
            'approver' => '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();

            // Invalidate cache for 'mrf_approvers_list' key when an approver is updated
            Cache::forget('mrf_approvers_list');

            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 = MrfApprover::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);
    }
}
