@extends('layouts.public-quote')

@section('content')

<div class="max-w-4xl mx-auto py-10 sm:px-6 lg:px-8">
    <div class="bg-black text-white p-6 rounded-xl shadow-md mb-10 text-center space-y-4">
    <h1 class="text-2xl md:text-2xl leading-snug">
        🙌 ¡Muchas Gracias por tu interés en nuestro proyecto!<br>
        <span class="text-indigo-400 block mt-2"><b>{{ $quote->property->fractional->project->name ?? 'Proyecto' }}</b></span>
    </h1>

    <p class="text-base md:text-lg text-gray-200">
        📝 Aquí tienes los detalles de tu cotización.<br>
        📞 <strong>Si tienes alguna pregunta, no dudes en contactarnos.</strong>
    </p>
</div>


    {{-- Á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;
         $fractional = $quote->property->fractional ?? null;
         $section    = $fractional?->section;
        @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">Proyecto: <b>{{ $project->name ?? '—' }}</b></h3>
            <div class="grid grid-cols-2 gap-y-2 gap-x-6 text-[15px]">
                <p><strong>Sección:</strong> {{ $section->code ?? '—' }}</p>
                <p><strong>Propiedad:</strong> {{ $quote->property->code ?? '-' }}</p>
                <p><strong>Tipo:</strong> {{ $quote->property->propertyType->name ?? '-' }}</p>
                <p><strong>Área total:</strong> {{ $quote->property->propertyType->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 del Tipo de Propiedad --}}
                @if($quote->property->propertyType?->image_url)
                <div class="mt-4 flex justify-center">
                    <img src="{{ $quote->property->propertyType->image_url }}"
                        width="450"
                        alt="Imagen de tipo de propiedad"
                        class="rounded-lg shadow max-h-[300px] object-cover">
                </div>
                @endif



        {{-- 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>


{{-- SECCIÓN 4: TABLA DE AMORTIZACIÓN --}}
<div class="mt-10" id="amortization-table">
    @php
        $total = $quote->price;  // El precio total de la propiedad
        $totalInicial = $montoEnganche + 30000;  // Total inicial (enganche + apartado)
        $principal = $total - $totalInicial; // Monto restante del préstamo
        $months = 48; // Meses de financiamiento
        $monthlyPayment = $quote->monthly_payment; // Pago mensual

        // Cálculo de la tabla de amortización
        $amortization = [];
        $remainingBalance = $principal - $monthlyPayment; // Establecemos el saldo inicial

        for ($i = 1; $i <= $months; $i++) {
            // Agregamos los datos al array de amortización
            $amortization[] = [
                'month' => $i,
                'payment' => number_format($monthlyPayment, 2),
                'principal' => number_format($monthlyPayment, 2),
                'balance' => number_format($remainingBalance, 2)
            ];

            // Ahora, en cada iteración (mes), restamos el pago mensual del saldo restante.
            $remainingBalance -= $monthlyPayment;
        }
    @endphp

    {{-- Saldo Inicial y Saldo Principal --}}
    <div class="mt-4 grid grid-cols-2 gap-8">
        <div class="text-left">
            <h3 class="text-xl font-semibold text-stone-600 border-b border-gray-200 pb-2 mb-4">Tabla de Amortización</h3>
        </div>
        <div class="text-right border-b border-gray-200 pb-2 mb-4">
            <strong>Saldo:</strong> ${{ number_format($principal, 2) }} MXN
        </div>
    </div>

    {{-- Tabla de amortización dividida en dos columnas --}}
    <div class="grid grid-cols-2 gap-8">
        {{-- Columna 1 --}}
        <div>
            <table class="min-w-full text-sm divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-4 py-2 text-left">Mes</th>
                        <th class="px-4 py-2 text-left">Pago Mensual</th>
                        <th class="px-4 py-2 text-left">Saldo Restante</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach ($amortization as $key => $item)
                        @if ($key < 24) {{-- Muestra los primeros 24 meses en la primera columna --}}
                        <tr class="{{ $key % 2 == 0 ? 'bg-white' : 'bg-gray-100' }}">
                            <td class="px-4 py-2">{{ $item['month'] }}</td>
                            <td class="px-4 py-2">${{ $item['payment'] }}</td>
                            <td class="px-4 py-2">${{ $item['balance'] }}</td>
                        </tr>
                        @endif
                    @endforeach
                </tbody>
            </table>
        </div>

        {{-- Columna 2 --}}
        <div>
            <table class="min-w-full text-sm divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-4 py-2 text-left">Mes</th>
                        <th class="px-4 py-2 text-left">Pago Mensual</th>
                        <th class="px-4 py-2 text-left">Saldo Restante</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach ($amortization as $key => $item)
                        @if ($key >= 24) {{-- Muestra los siguientes 24 meses en la segunda columna --}}
                        <tr class="{{ $key % 2 == 0 ? 'bg-white' : 'bg-gray-100' }}">
                            <td class="px-4 py-2">{{ $item['month'] }}</td>
                            <td class="px-4 py-2">${{ $item['payment'] }}</td>
                            <td class="px-4 py-2">${{ $item['balance'] }}</td>
                        </tr>
                        @endif
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>

        




    
</div>

        



       

    </div>

     {{-- BOTONES --}}
        <div class="mt-8 flex justify-center gap-4 botones">
            <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;
        }

        .botones{
        display: none !important;}



 #amortization-table {
            page-break-before: always;
        }



        table {
            width: 100%;
            font-size: 12px;
            border: 1px solid #ddd;
        }

        th, td {
            padding: 8px;
        }

        tr:nth-child(odd) {
            background-color: #ffffff;
        }

        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
    }
    </style>
            </head>
            <body>${printContent}</body>
        </html>
    `);
         win.document.close();
            setTimeout(() => {
                win.print();
                win.close();
            }, 500);   
        }
    </script>