<?php

namespace App\Http\Controllers\Api\cms\Masters;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\cms\Masters\VehicleBrand;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class VehicleBrandsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
  public function index(Request $request)
    {
        $types = VehicleBrand::query();

        // Filtering based on 'id'
        if (!empty($request->id) && $request->id > 0) {
            $types->where('id', $request->id);
        }

        // Filtering based on 'active' status
        if (isset($request->active) && $request->active !== '') {
            $types->where('active', $request->active);
        }

        // Searching based on 'search' keyword (id or name)
        if (!empty($request->search)) {
            $search = $request->search;
            $types->where(function ($query) use ($search) {
                $query->where('id', 'LIKE', "%{$search}%")
                    ->orWhere('name', 'LIKE', "%{$search}%");
            });
        }

        // Counting total records before pagination
        $count = $types->count();

        // Sorting logic with 'id' and 'name'
        $sortBy = $request->sort_by ?? 'id';
        $sortOrder = isset($request->sort_order) && $request->sort_order == 1 ? 'asc' : 'desc';

        if (in_array($sortBy, ['id', 'name'])) {
            $types->orderBy($sortBy, $sortOrder);
        } else {
            $types->orderBy('id', 'desc'); // Default sorting
        }

        // Pagination with 'noofrec' and 'currentpage'
        $noOfRec = $request->noofrec ?? 100;
        $currentPage = $request->currentpage ?? 1;

        $types = $types->skip($noOfRec * ($currentPage - 1))
            ->take($noOfRec)
            ->get();

        // Response structure
        return response()->json([
            'success' => true,
            'total' => $count,
            'data' => $types,
        ]);
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // Validate the request
        $validator = validator($request->all(), [
            'name' => 'required|string|unique:vehicle_brands,name',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first(),
            ], 400);
        }

        try {
            // Check for duplicate entry
            $duplicateCheck = VehicleBrand::where('name', $request->input('name'))->first();

            if ($duplicateCheck) {
                return response()->json([
                    'success' => false,
                    'message' => 'Vehicle Brand with name ' . $request->input('name') . ' already exists.',
                ], 409);
            }

            // Create new Vehicle Brand
            $type = VehicleBrand::create(['name' => $request->input('name')]);

            // Prepare response
            return response()->json([
                'success' => true,
                'message' => 'Vehicle Brand added successfully.',
                'data' => $type,
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'An error occurred while adding the Vehicle Brand: ' . $e->getMessage(),
            ], 500);
        }
    }


    public function update(Request $request)
    {
        // Validate the request
        $validator = validator($request->all(), [
            'id' => 'required|integer',
            'name' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first(),
            ], 400);
        }

        try {
            // Find the record by ID
            $brand = VehicleBrand::findOrFail($request->input('id'));

            // Check for duplicate name excluding current ID
            $duplicateCheck = VehicleBrand::where('name', $request->input('name'))
                ->where('id', '!=', $request->input('id'))
                ->first();

            if ($duplicateCheck) {
                return response()->json([
                    'success' => false,
                    'message' => 'Duplicate name "' . $request->input('name') . '" already exists.',
                ], 409);
            }

            // Update name
            $brand->update(['name' => $request->input('name')]);

            // Prepare response
            return response()->json([
                'success' => true,
                'message' => 'Brand updated successfully.',
                'data' => $brand,
            ]);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid ID to update.',
            ], 404);
        }
    }


    public function destroy(Request $request)
    {
        // Validate the request
        $validator = validator($request->all(), [
            'id' => 'required|exists:vehicle_brands,id', // Ensure ID exists in the table
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first(),
            ]);
        }

        try {
            // Find the VehicleBrand by ID or fail
            $type = VehicleBrand::findOrFail($request->input('id'));

            // Delete the record
            $type->delete();

            return response()->json([
                'success' => true,
                'message' => 'Brand deleted successfully.',
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid ID to delete.',
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'An error occurred while deleting the brand.',
            ], 500);
        }
    }
}
