<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Services\VinDecoderService;

class VehicleController extends Controller
{
    protected $vinDecoder;

    public function __construct(VinDecoderService $vinDecoder)
    {
        $this->vinDecoder = $vinDecoder;
    }
    public function index(Request $request)
    {
        $query = \App\Models\Vehicle::query();

        if ($request->filled('search')) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('make', 'like', "%{$search}%")
                    ->orWhere('model', 'like', "%{$search}%")
                    ->orWhere('stock_number', 'like', "%{$search}%");
            });
        }

        if ($request->filled('category') && $request->category !== 'all') {
            $query->where('category', $request->category);
        }

        if ($request->filled('status') && $request->status !== 'all') {
            $query->where('status', $request->status);
        }

        $vehicles = $query->with(['pricing', 'images'])->latest()->paginate(10);

        return view('admin.vehicles.index', compact('vehicles'));
    }

    public function create()
    {
        return view('admin.vehicles.create');
    }

    public function show(\App\Models\Vehicle $vehicle)
    {
        $vehicle->load(['branch', 'images', 'specifications', 'pricing']);

        return view('admin.vehicles.show', compact('vehicle'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'make' => 'required|string',
            'model' => 'required|string',
            'year' => 'required|integer|min:1900|max:'.(date('Y') + 1),
            'price' => 'required|numeric|min:0',
            'stock_number' => 'required|string|unique:vehicles,stock_number',
            'stock_quantity' => 'required|integer|min:0',
            'vin' => 'nullable|string|unique:vehicles,vin',
            'description' => 'nullable|string',
            'category' => 'required|string',
            'fuel_type' => 'required|string',
            'transmission' => 'required|string',
            'mileage' => 'nullable|integer|min:0',
            'color' => 'nullable|string',
            'status' => 'required|string',
            'featured' => 'boolean',
            'features' => 'nullable|array',
            'images' => 'nullable|array',
            'images.*.image_url' => 'required|string',
            'specifications' => 'nullable|array',
            'specifications.*.key' => 'required|string',
            'specifications.*.value' => 'required|string',
        ]);

        $vehicle = \App\Models\Vehicle::create($validated);

        if ($request->has('images')) {
            $vehicle->images()->createMany($request->images);
        }

        if ($request->has('specifications')) {
            $vehicle->specifications()->createMany($request->specifications);
        }

        $vehicle->pricing()->create([
            'base_price' => $validated['price'],
            'total_price' => $validated['price'],
            'currency' => 'EGP',
        ]);

        return redirect()->route('admin.vehicles.index')->with('success', 'Vehicle created successfully.');
    }

    public function edit(\App\Models\Vehicle $vehicle)
    {
        $vehicle->load(['images', 'specifications', 'pricing']);

        return view('admin.vehicles.edit', compact('vehicle'));
    }

    public function update(Request $request, \App\Models\Vehicle $vehicle)
    {
        $validated = $request->validate([
            'make' => 'required|string',
            'model' => 'required|string',
            'year' => 'required|integer',
            'price' => 'required|numeric',
            'stock_number' => 'required|string|unique:vehicles,stock_number,'.$vehicle->id,
            'stock_quantity' => 'required|integer',
            'vin' => 'nullable|string|unique:vehicles,vin,'.$vehicle->id,
            'description' => 'nullable|string',
            'category' => 'required|string',
            'fuel_type' => 'required|string',
            'transmission' => 'required|string',
            'mileage' => 'nullable|integer',
            'color' => 'nullable|string',
            'status' => 'required|string',
            'featured' => 'boolean',
            'features' => 'nullable|array',
        ]);

        $vehicle->update($validated);

        // Update pricing
        $vehicle->pricing()->updateOrCreate(
            ['vehicle_id' => $vehicle->id],
            [
                'base_price' => $validated['price'],
                'total_price' => $validated['price'],
            ]
        );

        return redirect()->route('admin.vehicles.index')->with('success', 'Vehicle updated successfully.');
    }

    public function destroy(\App\Models\Vehicle $vehicle)
    {
        $vehicle->delete();

        return redirect()->route('admin.vehicles.index')->with('success', 'Vehicle deleted successfully.');
    }


    public function decodeVin(Request $request)
    {
        $request->validate(['vin' => 'required|string|min:17']);

        $details = $this->vinDecoder->decode($request->vin);

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