@extends('layouts.app')

@section('content')
<div class="w-full px-4 mx-auto py-10 max-w-[1000px]">
    <h2 class="text-2xl font-semibold mb-6">Editar Tipo de Propiedad</h2>

    <form action="{{ route('property-types.update', $propertyType) }}" method="POST" class="form-base space-y-6" enctype="multipart/form-data">
        @csrf
        @method('PUT')

        {{-- Información general --}}
        <div class="grid lg:grid-cols-3 gap-4">
            <div>
                <label class="block text-sm text-gray-600 mb-1">Nombre</label>
                <input type="text" name="name" value="{{ old('name', $propertyType->name) }}" class="w-full border-gray-300 rounded-md shadow-sm" required>
            </div>
            
            <div>
                <label class="block text-sm text-gray-600 mb-1">Precio Base</label>
                <input type="number" step="0.01" name="price" value="{{ old('price', $propertyType->price) }}" class="w-full border-gray-300 rounded-md shadow-sm" required>
            </div>

            <select name="fractional_id" class="w-full border-gray-300 rounded-md shadow-sm">
    <option value="">Selecciona un Fractional</option>
    @foreach ($fractionals as $fractional)
        <option value="{{ $fractional->id }}" {{ old('fractional_id', $propertyType->fractional_id) == $fractional->id ? 'selected' : '' }}>
            {{ $fractional->name }}
        </option>
    @endforeach
</select>


        </div>

        {{-- Áreas adicionales --}}
        <div class="grid lg:grid-cols-3 gap-4">
            <div>
                <label class="block text-sm text-gray-600 mb-1">Área Total (m²)</label>
                <input type="number" step="0.01" name="area" value="{{ old('area', $propertyType->area) }}" class="w-full border-gray-300 rounded-md shadow-sm" required>
            </div>
            <div>
                <label class="block text-sm text-gray-600 mb-1">Área Techada (m²)</label>
                <input type="number" step="0.01" name="area_roofed" value="{{ old('area_roofed', $propertyType->area_roofed) }}" class="w-full border-gray-300 rounded-md shadow-sm">
            </div>
            <div>
                <label class="block text-sm text-gray-600 mb-1">Área de Jardín (m²)</label>
                <input type="number" step="0.01" name="area_garden" value="{{ old('area_garden', $propertyType->area_garden) }}" class="w-full border-gray-300 rounded-md shadow-sm">
            </div>
        </div>


        @if($propertyType->image)
    <img src="{{ asset('storage/' . $propertyType->image) }}" alt="Imagen del tipo de propiedad" class="h-32 w-auto mb-4">
@endif

<div class="mb-4">
    <label for="image" class="block text-sm font-medium text-gray-700">Imagen representativa</label>
    <input type="file" name="image" id="image" class="mt-1 block w-full">
    @error('image')
        <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
    @enderror
</div>


        <div class="max-w-6xl mx-auto py-10">
            <h2 class="text-xl font-semibold mb-4">Editor de Polígonos SVG</h2>

        <canvas id="editor-canvas" width="900" height="500" class="border" data-image="{{ $backgroundImage }}"></canvas>


            <div class="mt-4">
                <button id="generate-svg" type="button" class="bg-indigo-600 text-white px-4 py-2 rounded">Generar SVG</button>

                <button id="reset-canvas" type="button" class="bg-red-600 text-white px-4 py-2 rounded ml-2">Reiniciar dibujo</button>

                <textarea id="svg-output" name="svg_points" rows="6" class="w-full mt-4 border rounded-md p-2">{{ old('svg_points', $propertyType->svg_points) }}</textarea>



            </div>
        </div>

        {{-- Precios por mes --}}
        <details class="mt-6 bg-gray-50 p-4 rounded-md shadow-sm open:bg-white open:ring-2 open:ring-blue-100 transition-all">
            <summary class="text-md font-medium cursor-pointer select-none mb-4 text-blue-700">
                📅 Precios por Mes (opcional)
            </summary>

            <div class="grid grid-cols-3 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                @foreach ([
                    'january' => 'Enero',
                    'february' => 'Febrero',
                    'march' => 'Marzo',
                    'april' => 'Abril',
                    'may' => 'Mayo',
                    'june' => 'Junio',
                    'july' => 'Julio',
                    'august' => 'Agosto',
                    'september' => 'Septiembre',
                    'october' => 'Octubre',
                    'november' => 'Noviembre',
                    'december' => 'Diciembre'
                ] as $key => $label)
                    <div>
                        <label class="block text-sm text-gray-600">{{ $label }}</label>
                         {{-- Input real, que Laravel usará --}}
                        <input 
                            type="number" 
                            step="0.01" 
                            inputmode="decimal" 
                            name="price_{{ $key }}" 
                            id="price_{{ $key }}"
                            value="{{ old('price_'.$key, $propertyType->{'price_'.$key}) }}" 
                            class="w-full border-gray-300 rounded-md shadow-sm real-price"
                            data-label="{{ $label }}"
                        >

                        {{-- Formato visual dinámico --}}
                        <div class="text-sm text-gray-500 mt-1" id="formatted_{{ $key }}"></div>
                     </div>
                @endforeach
            </div>
        </details>

        {{-- Botones --}}
        <div class="flex justify-center gap-4 pt-6">
            <button type="submit" class="bg-blue-600 text-white px-6 py-2 rounded hover:bg-blue-700 transition">
                💾 Actualizar
            </button>
            <a href="{{ route('property-types.index') }}" class="bg-gray-200 text-gray-800 px-6 py-2 rounded hover:bg-gray-300 transition">
                ⬅ Cancelar
            </a>
        </div>
    </form>
</div>
@endsection

    <script>
document.addEventListener('DOMContentLoaded', function () {
    const formatter = new Intl.NumberFormat('es-MX', {
        style: 'currency',
        currency: 'MXN',
        minimumFractionDigits: 2
    });

    document.querySelectorAll('.real-price').forEach(input => {
        const field = input.name;
        const key = field.replace('price_', '');
        const preview = document.getElementById(`formatted_${key}`);

        // Mostrar valor inicial formateado
        if (input.value && preview) {
            const num = parseFloat(input.value);
            if (!isNaN(num)) {
                preview.textContent = formatter.format(num);
            }
        }

        // Al escribir, actualizar valor formateado
        input.addEventListener('input', () => {
            const val = parseFloat(input.value);
            if (!isNaN(val) && preview) {
                preview.textContent = formatter.format(val);
            } else if (preview) {
                preview.textContent = '';
            }
        });
    });
});
</script>

<!-- ⚠️ Versión SIN atributo integrity ni crossorigin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.0/fabric.min.js"></script>

<!-- Carga tu script -->
@vite(['resources/js/polygon-editor.js'])


