<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\RoomType;
use App\Services\ImageOptimizationService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;
use Inertia\Response;

class RoomTypeManagementController extends Controller
{
    public function index(): Response
    {
        return Inertia::render('Admin/RoomTypes', [
            'roomTypes' => RoomType::query()
                ->withCount('rooms')
                ->orderBy('name')
                ->get()
                ->map(fn (RoomType $roomType) => [
                    'id' => $roomType->id,
                    'name' => $roomType->name,
                    'slug' => $roomType->slug,
                    'description' => $roomType->description,
                    'base_price' => (float) $roomType->base_price,
                    'capacity' => $roomType->capacity,
                    'area' => $roomType->area,
                    'amenities' => $roomType->amenities ?? [],
                    'amenities_text' => implode(', ', $roomType->amenities ?? []),
                    'image_url' => $roomType->image_path ? Storage::url($roomType->image_path) : null,
                    'rooms_count' => $roomType->rooms_count,
                ]),
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255', 'unique:room_types,name'],
            'description' => ['nullable', 'string'],
            'base_price' => ['required', 'numeric', 'min:0'],
            'capacity' => ['required', 'integer', 'min:1'],
            'area' => ['nullable', 'integer', 'min:1'],
            'amenities_text' => ['nullable', 'string'],
            'image' => ['nullable', 'image', 'max:4096'],
        ]);

        $imagePath = $request->file('image')?->store('room-types', 'public');

        // Optimize image if uploaded (temporarily disabled for debugging)
        // if ($imagePath) {
        //     $fullPath = Storage::disk('public')->path($imagePath);
        //     ImageOptimizationService::optimizeImage($fullPath);
        // }

        RoomType::create([
            'name' => $validated['name'],
            'description' => $validated['description'] ?? null,
            'base_price' => $validated['base_price'],
            'capacity' => $validated['capacity'],
            'area' => $validated['area'] ?? null,
            'amenities' => $this->parseAmenities($validated['amenities_text'] ?? ''),
            'image_path' => $imagePath,
        ]);

        return back()->with('success', 'Room type created successfully.');
    }

    public function update(Request $request, RoomType $roomType)
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255', 'unique:room_types,name,' . $roomType->id],
            'description' => ['nullable', 'string'],
            'base_price' => ['required', 'numeric', 'min:0'],
            'capacity' => ['required', 'integer', 'min:1'],
            'area' => ['nullable', 'integer', 'min:1'],
            'amenities_text' => ['nullable', 'string'],
            'image' => ['nullable', 'image', 'max:4096'],
        ]);

        $imagePath = $roomType->image_path;

        if ($request->hasFile('image')) {
            if ($imagePath) {
                // ImageOptimizationService::deleteImageVariants(Storage::disk('public')->path($imagePath));
                Storage::disk('public')->delete($imagePath);
            }

            $imagePath = $request->file('image')->store('room-types', 'public');
            
            // Optimize new image (temporarily disabled)
            // $fullPath = Storage::disk('public')->path($imagePath);
            // ImageOptimizationService::optimizeImage($fullPath);
        }

        $roomType->update([
            'name' => $validated['name'],
            'description' => $validated['description'] ?? null,
            'base_price' => $validated['base_price'],
            'capacity' => $validated['capacity'],
            'area' => $validated['area'] ?? null,
            'amenities' => $this->parseAmenities($validated['amenities_text'] ?? ''),
            'image_path' => $imagePath,
            'slug' => null,
        ]);

        return back()->with('success', 'Room type updated successfully.');
    }

    private function parseAmenities(string $text): array
    {
        return collect(explode(',', $text))
            ->map(fn (string $item) => trim($item))
            ->filter(fn (string $item) => $item !== '')
            ->values()
            ->all();
    }
}
