<?php

namespace App\Http\Controllers;

use App\Models\Property;
use App\Models\PropertyImage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class PropertyImageController extends Controller
{
    public function store(Request $request, Property $property)
    {
        $request->validate([
            'images' => 'required|array',
            'images.*' => 'image|max:5120', // 5MB máximo
        ]);

        $lastLevel = $property->images()->max('level') ?? -1;

        foreach ($request->file('images') as $index => $image) {
            $path = $image->store('properties/' . date('Y/m'), 'public');
            
            PropertyImage::create([
                'property_id' => $property->id,
                'image' => $path,
                'level' => $lastLevel + $index + 1,
            ]);
        }

        return redirect()
            ->route('filament.admin.resources.properties.view', $property)
            ->with('success', count($request->file('images')) . ' imágenes guardadas');
    }

    public function destroy(Property $property, PropertyImage $image)
    {
        // Verificar que la imagen pertenece a la propiedad
        if ($image->property_id !== $property->id) {
            abort(403, 'La imagen no pertenece a esta propiedad');
        }

        // Eliminar archivo físico
        if (Storage::disk('public')->exists($image->image)) {
            Storage::disk('public')->delete($image->image);
        }

        $image->delete();

        // Reordenar los niveles restantes
        $property->images()->orderBy('level')->get()->each(function ($img, $index) {
            $img->update(['level' => $index]);
        });

        return redirect()
            ->route('filament.admin.resources.properties.view', $property)
            ->with('success', 'Imagen eliminada correctamente');
    }
}