<?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\Dealership;
use App\Models\Company;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;

use Throwable;

class DealershipController extends Controller
{
    public function index(Request $request)
    {
        $keyword = $request->input('keyword', null);
        $perPage = $request->input('per_page',PHP_INT_MAX);
        $sortBy = $request->input('sortBy', null);
        $sortType = $request->input('sortType', null);
        $includes = $request->input('includes', null);
        $with = ['company','departments'];
        
        $data = Dealership::with($with)
            ->when($keyword, fn ($q) => $q->where(fn($q2) => $q2->where('name', 'like', '%' . str_replace(" ", "%", $keyword) . '%'))
            )
            ->when($sortBy, fn($q) => $q->orderBy($sortBy, $sortType));

        if($request->dealership){
            $data = $data->where('company_id', $request->dealership);
        }

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

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

    public function store(Request $request)
    {

        // Validate the incoming request data
        $validator = Validator::make($request->all(), [
            'company_id' => 'required',
            'code' => [
                Rule::unique('dealerships')->whereNull('deleted_at')
            ],
            'name' => [
                'required',
                'min:2',
                Rule::unique('dealerships')->whereNull('deleted_at')
            ],
        ]);

        /** 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 = Dealership::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)
    {
        // Find the dealership by its ID
        $data = Dealership::findOrFail($id);

        /** If not exists return with error message */
        if (!$data) {
            return response()->json(['message' => 'Record not found.'], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        // Validate the incoming request data
        $validator = Validator::make($request->all(), [
            'code' => [
                'required',
                'min:2',
                Rule::unique('dealerships')->ignore($id)->whereNull('deleted_at')
            ],
            'name' => [
                'required',
                'min:2',
                Rule::unique('dealerships')->ignore($id)->whereNull('deleted_at')
            ],
        ]);

        /** 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 = Dealership::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!"],200);

    }
    // public function companyList()
    // {
    //     $company_list = Company::where('enabled',1)->get(['id','code','name']);
    //     return $company_list;
    // }
}
