@extends('layouts.app')

@section('content')

<div class="max-w-4xl mx-auto py-10 sm:px-6 lg:px-8">

    {{-- ÁREA A IMPRIMIR --}}
    <div id="quote-print-area" class="bg-white p-10 rounded-xl shadow-xl border border-gray-200 text-gray-800 max-w-3xl mx-auto py-10 sm:px-6 lg:px-8">

        {{-- ENCABEZADO CON LOGO Y DATOS DE LA EMPRESA DEL PROYECTO --}}
        @php
        $project = $quote->property->fractional->project;
        @endphp

        <div class="grid grid-cols-3 items-center border-b pb-6 mb-8 gap-4">
            {{-- Columna 1: Logo --}}
            <div class="flex justify-start">
                @if($project?->company_logo)
                <div class="items-center">
                    <img src="{{ asset('storage/' . $project->company_logo) }}"
                        alt="Logotipo" width="250"
                        class="object-contain" />
                </div>

                @else
                <img src="{{ asset('images/logo.svg') }}" alt="Logo" class="h-14 object-contain">
                @endif
            </div>

            {{-- Columna 2: Vacía --}}
            <div></div>

            {{-- Columna 3: Datos de contacto --}}
            <div class="text-sm text-right leading-5 text-gray-600">
                <p class="font-semibold text-lg text-gray-800">{{ $project->company_name ?? 'Fractional SJ' }}</p>
                @if($project?->company_address)<p>{{ $project->company_address }}</p>@endif
                @if($project?->company_phone)<p>📞 {{ $project->company_phone }}</p>@endif
                @if($project?->company_email)<p>✉️ {{ $project->company_email }}</p>@endif
            </div>
        </div>



        {{-- TÍTULO --}}
        <h2 class="text-3xl font-bold text-center text-stone-600 mb-10 tracking-tight">Cotización #{{ $quote->slug }}</h2>

        {{-- SECCIÓN 1: CLIENTE --}}
        <div class="mb-8">
            <h3 class="text-xl font-semibold text-stone-600 border-b border-gray-200 pb-2 mb-4">Datos del Cliente</h3>
            <div class="grid grid-cols-2 gap-y-2 gap-x-6 text-[15px]">
                <p><strong>Nombre:</strong> {{ $quote->lead->form_data['name'] ?? '-' }} {{ $quote->lead->form_data['last_name'] ?? '' }}</p>
                <p><strong>Email:</strong> {{ $quote->lead->form_data['email'] ?? '-' }}</p>
                <p><strong>Teléfono:</strong> {{ $quote->lead->form_data['country_code'] ?? '' }} {{ $quote->lead->form_data['phone_number'] ?? '' }}</p>
                <p><strong>Ubicación:</strong> {{ $quote->lead->form_data['location'] ?? '-' }}</p>
                <p><strong>Broker:</strong> {{ $quote->lead->form_data['is_broker'] ?? '-' }}</p>
                <p><strong>Intención de compra:</strong> {{ $quote->lead->form_data['purchase_intent'] ?? '-' }}</p>
            </div>
        </div>

        {{-- SECCIÓN 2: PROPIEDAD --}}
        <div class="mb-8">
            <h3 class="text-xl font-semibold text-text-stone-600 border-b border-gray-200 pb-2 mb-4">Propiedad</h3>
            <div class="grid grid-cols-2 gap-y-2 gap-x-6 text-[15px]">
                <p><strong>Nombre:</strong> {{ $quote->property->name ?? '-' }}</p>
                <p><strong>Código:</strong> {{ $quote->property->code ?? '-' }}</p>
                <p><strong>Tipo:</strong> {{ $quote->property->propertyType->name ?? '-' }}</p>
                <p><strong>Área total:</strong> {{ $quote->property->area }} m²</p>
                <p><strong>Área techada:</strong> {{ $quote->property->propertyType->area_roofed ?? '-' }} m²</p>
                @if(($quote->property->propertyType->area_garden ?? 0) > 0)
                <p><strong>Área de jardín:</strong> {{ $quote->property->propertyType->area_garden }} m²</p>
                @endif
            </div>

            {{-- Imagen --}}
            @if($quote->property->fractional?->image)
            <div class="mt-4 flex justify-center">
                <img src="{{ asset('storage/' . $quote->property->fractional->image->path) }}" width="450" alt="{{ $quote->property->fractional->image->alt }}" class="rounded-lg shadow max-h-[300px] object-cover">
            </div>
            @endif
        </div>


        {{-- SECCIÓN 3: COTIZACIÓN --}}
        @php
        $montoEnganche = $quote->price * ($quote->advance_percentage / 100);
        $totalInicial = $montoEnganche + 30000;


        @endphp


        <div class="divide-y divide-gray-200 text-[15px] mt-8">
            <div class="flex justify-between py-1">
                <span><strong>Mes de ocupación:</strong></span>
                <span>{{ $meses[$quote->month] ?? ucfirst($quote->month) }}</span>

            </div>
            <div class="flex justify-between py-1">
                <span><strong>Precio total de la propiedad:</strong></span>
                <span>${{ number_format($quote->price, 2) }} MXN</span>
            </div>
            <div class="flex justify-between py-1">
                <span><strong>Apartado no reembolsable:</strong></span>
                <span>$30,000.00 MXN</span>
            </div>
            <div class="flex justify-between py-1">
                <span><strong>Enganche:</strong></span>
                <span>${{ number_format($montoEnganche, 2) }} MXN ({{ $quote->advance_percentage }}%)</span>
            </div>
            <div class="flex justify-between py-1">
                <span><strong>Total inicial (enganche + apartado):</strong></span>
                <span>${{ number_format($totalInicial, 2) }} MXN</span>
            </div>
            <div class="flex justify-between py-1">
                <span><strong>Pago mensual (hasta 48 meses):</strong></span>
                <span>${{ number_format($quote->monthly_payment, 2) }} MXN</span>
            </div>
        </div>





    </div>

    {{-- BOTONES CONTACTO --}}

    <div class="flex flex-wrap gap-4 my-4 justify-center">
        {{-- Enviar por WhatsApp --}}
        @php
        $code = preg_replace('/[^0-9]/', '', $quote->lead->form_data['country_code'] ?? '');
        $phone = preg_replace('/[^0-9]/', '', $quote->lead->form_data['phone_number'] ?? '');
        $waNumber = $code . $phone;
        $waMessage = urlencode("Hola {$quote->name}, gracias por cotizar. Aquí tienes tu cotización: " . route('public.quotes.show', $quote->slug));
        @endphp

        <a href="https://wa.me/{{ $waNumber }}?text={{ $waMessage }}"
            target="_blank"
            class="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600 transition">
            📱 WhatsApp
        </a>
        {{-- Llamar --}}
        <a href="tel:{{ $quote->lead->form_data['country_code'] ?? '' }} {{ $quote->lead->form_data['phone_number'] ?? '' }}"
            class="bg-neutral-700 text-white px-4 py-2 rounded hover:bg-neutral-600 transition">
            📞 Llamar
        </a>

        {{-- Copiar URL de cotización pública --}}
        <button onclick="copyToClipboard('{{ route('public.quotes.show', $quote->slug) }}')"
            class="bg-gray-800 text-white px-4 py-2 rounded hover:bg-gray-900 transition">
            🔗 Copiar URL de cotización
        </button>

        {{-- Copiar correo --}}
        <button onclick="copyToClipboard('{{ $quote->email }}')"
            class="bg-yellow-500 text-white px-4 py-2 rounded hover:bg-yellow-600 transition">
            ✉️ Copiar email
        </button>
    </div>

    <script>
        function copyToClipboard(text) {
            navigator.clipboard.writeText(text).then(function() {
                alert("Copiado al portapapeles: " + text);
            }, function(err) {
                alert("Error al copiar: ", err);
            });
        }
    </script>



    {{-- BOTONES --}}
    <div class="mt-8 flex justify-center gap-4">
        <a href="{{ route('quotes.index') }}" class="px-6 py-2 rounded-lg text-stone-600 border border-indigo-600 hover:bg-indigo-50 transition">
            ← Volver al listado
        </a>
        <button onclick="printQuote()" class="px-6 py-2 rounded-lg bg-indigo-600 text-white hover:bg-indigo-700 transition">
            🖨️ Imprimir o Guardar PDF
        </button>
    </div>


    @endsection


    <script>
        function printQuote() {
            const printContent = document.getElementById('quote-print-area').innerHTML;
            const win = window.open('', '', 'width=900,height=700');
            win.document.write(`
        <html>
            <head>
                <title>Cotización</title>
                <style>
        body {
            font-family: 'Arial', sans-serif;
            padding: 30px;
            color: #111;
            font-size: 14px;
        }

        h2 {
            font-size: 24px;
            text-align: center;
            color: #2d2d2d;
            margin-bottom: 20px;
        }

        h3 {
            font-size: 18px;
            border-bottom: 1px solid #ddd;
            padding-bottom: 5px;
            margin: 20px 0 10px;
            color: #4a4a4a;
        }

        .grid {
            display: grid;
            gap: 0.1rem;
        }

        .grid-cols-2 {
            grid-template-columns: repeat(2, 1fr);
        }

        .grid-cols-3 {
            grid-template-columns: repeat(3, 1fr);
        }

        .text-right {
            text-align: right;
        }

        .text-center {
            text-align: center;
        }

        .text-left {
            text-align: left;
        }

        .mb-8 {
            margin-bottom: 1rem;
        }

        .pb-6 {
            padding-bottom: 1rem;
        }

        .rounded-lg {
            border-radius: 8px;
        }

        .shadow, .shadow-xl {
            box-shadow: none;
        }

            .flex.justify-between.py-1 {
    padding: 5px 0;
}

   

        p {
            margin: 4px 0;
        }

        .flex {
            display: flex;
            justify-content: space-between;
        }

        .justify-center {
            justify-content: center;
        }

        .divide-y > * + * {
            border-top: 1px solid #e5e5e5;
        }
    </style>
            </head>
            <body>${printContent}</body>
        </html>
    `);
            win.document.close();
            setTimeout(() => {
                win.print();
                win.close();
            }, 500);
        }
    </script>