<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Vehicle;
use App\Models\AuditLog;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class InventoryAdminController extends Controller
{
    public function index(Request $request)
    {
        $query = Vehicle::query();

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

        $vehicles = $query->orderBy('id', 'desc')->paginate(15)->withQueryString();
        $makes = Vehicle::distinct()->pluck('make')->filter();

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

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

    public function store(Request $request)
    {
        $validated = $request->validate([
            'make' => 'required|string|max:100',
            'model' => 'required|string|max:100',
            'variant' => 'nullable|string|max:150',
            'year' => 'required|integer|min:2000|max:' . (date('Y') + 1),
            'chassis_number' => 'required|string|max:100|unique:vehicles',
            'engine_cc' => 'required|integer|min:500|max:8000',
            'fuel_type' => 'required|string|max:50',
            'transmission' => 'required|string|max:50',
            'drive_type' => 'required|string|max:20',
            'body_type' => 'required|string|max:50',
            'color' => 'required|string|max:50',
            'mileage' => 'required|integer|min:0',
            'auction_grade' => 'required|string|max:10',
            'selling_price_bdt' => 'required|numeric|min:0',
            'discount_bdt' => 'nullable|numeric|min:0',
            'main_image' => 'required|url',
            'status' => 'required|in:available,reserved,sold,arriving,hidden',
            'is_featured' => 'nullable|boolean',
            'description' => 'nullable|string',
        ]);

        $finalPrice = $validated['selling_price_bdt'] - ($validated['discount_bdt'] ?? 0);
        $stockNumber = 'MS-STK-' . date('Y') . '-' . rand(100, 999);
        $slug = Str::slug("{$validated['make']}-{$validated['model']}-{$validated['year']}-{$stockNumber}");

        $vehicle = Vehicle::create(array_merge($validated, [
            'stock_number' => $stockNumber,
            'slug' => $slug,
            'final_price_bdt' => $finalPrice,
            'is_featured' => $request->boolean('is_featured'),
            'gallery' => [$validated['main_image']],
        ]));

        AuditLog::record('admin_created_vehicle', $vehicle);

        return redirect()->route('admin.inventory.index')->with('success', "Ready stock vehicle {$vehicle->full_name} added successfully.");
    }

    public function edit(string $id)
    {
        $vehicle = Vehicle::findOrFail($id);
        return view('admin.inventory.edit', compact('vehicle'));
    }

    public function update(Request $request, string $id)
    {
        $vehicle = Vehicle::findOrFail($id);

        $validated = $request->validate([
            'make' => 'required|string|max:100',
            'model' => 'required|string|max:100',
            'variant' => 'nullable|string|max:150',
            'year' => 'required|integer|min:2000|max:' . (date('Y') + 1),
            'chassis_number' => 'required|string|max:100|unique:vehicles,chassis_number,' . $vehicle->id,
            'engine_cc' => 'required|integer|min:500|max:8000',
            'fuel_type' => 'required|string|max:50',
            'transmission' => 'required|string|max:50',
            'drive_type' => 'required|string|max:20',
            'body_type' => 'required|string|max:50',
            'color' => 'required|string|max:50',
            'mileage' => 'required|integer|min:0',
            'auction_grade' => 'required|string|max:10',
            'selling_price_bdt' => 'required|numeric|min:0',
            'discount_bdt' => 'nullable|numeric|min:0',
            'main_image' => 'required|url',
            'status' => 'required|in:available,reserved,sold,arriving,hidden',
            'is_featured' => 'nullable|boolean',
            'description' => 'nullable|string',
        ]);

        $finalPrice = $validated['selling_price_bdt'] - ($validated['discount_bdt'] ?? 0);

        $vehicle->update(array_merge($validated, [
            'final_price_bdt' => $finalPrice,
            'is_featured' => $request->boolean('is_featured'),
        ]));

        AuditLog::record('admin_updated_vehicle', $vehicle);

        return redirect()->route('admin.inventory.index')->with('success', "Vehicle {$vehicle->full_name} updated successfully.");
    }

    public function destroy(string $id)
    {
        $vehicle = Vehicle::findOrFail($id);
        $name = $vehicle->full_name;
        $vehicle->delete();

        AuditLog::record('admin_deleted_vehicle', null, ['name' => $name]);

        return back()->with('success', "Vehicle {$name} deleted.");
    }
}
