<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Car;
use App\Models\CarPhoto;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\File;

class AdminCarController extends Controller
{
    /**
     * Base path for car photos (inside public dash/ folder)
     */
    private function carPhotoDir($carId)
    {
        return 'dash/cars/' . $carId;
    }
    /**
     * List all cars
     */
    public function index()
    {
        $title = 'Car Inventory';
        $cars = Car::withCount('orders')
            ->with(['photos' => fn($q) => $q->orderBy('sort_order')])
            ->orderBy('created_at', 'desc')
            ->get();

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

    /**
     * Show create car form
     */
    public function create()
    {
        $title = 'Add New Car';
        return view('admin.cars.create', compact('title'));
    }

    /**
     * Store a new car
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'make' => 'required|string|max:255',
            'model' => 'required|string|max:255',
            'year' => 'required|integer|min:1900|max:' . (date('Y') + 2),
            'color' => 'required|string|max:255',
            'engine' => 'nullable|string|max:255',
            'transmission' => 'required|in:automatic,manual',
            'price' => 'required|numeric|min:0',
            'quantity' => 'required|integer|min:0',
            'description' => 'nullable|string',
            'status' => 'required|in:available,unavailable',
            'featured' => 'sometimes|boolean',
            'specs' => 'nullable|array',
            'photos.*' => 'image|mimes:jpeg,png,jpg,gif,webp|max:5120',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $car = Car::create([
            'name' => $request->name,
            'make' => $request->make,
            'model' => $request->model,
            'year' => $request->year,
            'color' => $request->color,
            'engine' => $request->engine,
            'transmission' => $request->transmission,
            'price' => $request->price,
            'quantity' => $request->quantity,
            'description' => $request->description,
            'status' => $request->status,
            'featured' => $request->has('featured'),
            'specs' => $request->specs,
        ]);

        // Handle photo uploads — store in storage/app/public/cars/{id}/
        if ($request->hasFile('photos')) {
            $dir = $this->carPhotoDir($car->id);
            if (!File::isDirectory($dir)) {
                File::makeDirectory($dir, 0755, true);
            }
            foreach ($request->file('photos') as $index => $photo) {
                $filename = uniqid() . '.' . $photo->getClientOriginalExtension();
                $photo->move($dir, $filename);
                CarPhoto::create([
                    'car_id' => $car->id,
                    'photo_path' => 'cars/' . $car->id . '/' . $filename,
                    'is_primary' => $index === 0,
                    'sort_order' => $index,
                ]);
            }
        }

        return redirect()->route('admin.cars.index')
            ->with('success', 'Car added successfully.');
    }

    /**
     * View car details
     */
    public function show(Car $car)
    {
        $title = 'Car Details - ' . $car->name;
        $car->load('photos', 'orders');
        return view('admin.cars.show', compact('title', 'car'));
    }

    /**
     * Edit car form
     */
    public function edit(Car $car)
    {
        $title = 'Edit Car - ' . $car->name;
        $car->load('photos');
        return view('admin.cars.edit', compact('title', 'car'));
    }

    /**
     * Update a car
     */
    public function update(Request $request, Car $car)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'make' => 'required|string|max:255',
            'model' => 'required|string|max:255',
            'year' => 'required|integer|min:1900|max:' . (date('Y') + 2),
            'color' => 'required|string|max:255',
            'engine' => 'nullable|string|max:255',
            'transmission' => 'required|in:automatic,manual',
            'price' => 'required|numeric|min:0',
            'quantity' => 'required|integer|min:0',
            'description' => 'nullable|string',
            'status' => 'required|in:available,unavailable',
            'featured' => 'sometimes|boolean',
            'specs' => 'nullable|array',
            'photos.*' => 'image|mimes:jpeg,png,jpg,gif,webp|max:5120',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $car->update([
            'name' => $request->name,
            'make' => $request->make,
            'model' => $request->model,
            'year' => $request->year,
            'color' => $request->color,
            'engine' => $request->engine,
            'transmission' => $request->transmission,
            'price' => $request->price,
            'quantity' => $request->quantity,
            'description' => $request->description,
            'status' => $request->status,
            'featured' => $request->has('featured'),
            'specs' => $request->specs,
        ]);

        // Handle new photo uploads — store in storage/app/public/cars/{id}/
        if ($request->hasFile('photos')) {
            $dir = $this->carPhotoDir($car->id);
            if (!File::isDirectory($dir)) {
                File::makeDirectory($dir, 0755, true);
            }
            $maxSort = $car->photos()->max('sort_order') ?? -1;
            foreach ($request->file('photos') as $index => $photo) {
                $filename = uniqid() . '.' . $photo->getClientOriginalExtension();
                $photo->move($dir, $filename);
                CarPhoto::create([
                    'car_id' => $car->id,
                    'photo_path' => 'cars/' . $car->id . '/' . $filename,
                    'is_primary' => $car->photos()->count() === 0 && $index === 0,
                    'sort_order' => $maxSort + $index + 1,
                ]);
            }
        }

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

    /**
     * Soft-delete car and remove photos from disk
     */
    public function destroy(Car $car)
    {
        // Delete photo files from storage/app/public/
        $dir = $this->carPhotoDir($car->id);
        if (File::isDirectory($dir)) {
            File::deleteDirectory($dir);
        }
        $car->photos()->delete();
        $car->delete();

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

    /**
     * Toggle car available/unavailable
     */
    public function toggleStatus(Car $car)
    {
        $car->status = $car->status === 'available' ? 'unavailable' : 'available';
        $car->save();

        return redirect()->back()
            ->with('success', 'Car status updated to ' . $car->status . '.');
    }

    /**
     * Delete a single photo (AJAX)
     */
    public function deletePhoto($photoId)
    {
        $photo = CarPhoto::findOrFail($photoId);
        $filePath = public_path('dash/' . $photo->photo_path);
        if (File::exists($filePath)) {
            File::delete($filePath);
        }
        $photo->delete();

        return response()->json(['success' => true, 'message' => 'Photo deleted.']);
    }
}
