<?= $this->extend('layouts/layout') ?>

<?= $this->section('titulo') ?>Editar cotización<?= $this->endSection() ?>

<?= $this->section('contenido') ?>

<div class="tef-panel">

    <h2>Editar cotización</h2>
    <p class="text-muted">
        Modifica la cotización antes de convertirla en orden de envío
    </p>

    <form method="post" action="<?= site_url('crm/quotes/update/'.$quote['PK_Quote']) ?>">
        <?= csrf_field() ?>
        <input type="hidden" name="_method" value="PUT">

        <!-- ================= ORIGEN ================= -->
        <div class="tef-card" style="margin-top:20px;">
            <h4>Origen</h4>

            <div class="tef-form-row">
                <div class="tef-input-group tef-input-sm">
                    <label>Nombre remitente</label>
                    <input type="text"
                        class="tef-input"
                        name="Origin_name"
                        value="<?= esc($quote['Origin_name']) ?>">
                </div>

                <div class="tef-input-group tef-input-sm">
                    <label>Direccion</label>
                    <input type="text"
                        class="tef-input"
                        name="Origin_address"
                        value="<?= esc($quote['Origin_address']) ?>">
                </div>

                <div class="tef-input-group tef-input-sm">
                    <label>Ciudad</label>
                    <input type="text"
                        class="tef-input"
                        name="Origin_city"
                        value="<?= esc($quote['Origin_city']) ?>">
                </div>
            </div>

            <div class="tef-form-row">
                <div class="tef-input-group tef-input-sm">
                    <label>Estado</label>
                    <input type="text"
                        class="tef-input"
                        name="Origin_state"
                        value="<?= esc($quote['Origin_state']) ?>">
                </div>

                <div class="tef-input-group tef-input-sm">
                    <label>País</label>
                    <input type="text"
                        class="tef-input"
                        name="Origin_country"
                        value="<?= esc($quote['Origin_country']) ?>">
                </div>

                <div class="tef-input-group tef-input-sm">
                    <label>Codigo Postal</label>
                    <input type="text"
                        class="tef-input"
                        name="Origin_zip"
                        value="<?= esc($quote['Origin_zip']) ?>">
                </div>
            </div>
        </div>

        <!-- ================= DESTINO ================= -->
        <div class="tef-card" style="margin-top:20px;">
            <h4>Destino</h4>

            <div class="tef-form-row">
                <div class="tef-input-group tef-input-sm">
                    <label>Nombre destinatario</label>
                    <input type="text"
                        class="tef-input"
                        name="Destination_name"
                        value="<?= esc($quote['Destination_name']) ?>">
                </div>

                <div class="tef-input-group tef-input-sm">
                    <label>Direccion</label>
                    <input type="text"
                        class="tef-input"
                        name="Destination_address"
                        value="<?= esc($quote['Destination_address']) ?>">
                </div>

                <div class="tef-input-group tef-input-sm">
                    <label>Ciudad</label>
                    <input type="text"
                        class="tef-input"
                        name="Destination_city"
                        value="<?= esc($quote['Destination_city']) ?>">
                </div>
            </div>

            <div class="tef-form-row">
                <div class="tef-input-group tef-input-sm">
                    <label>Estado</label>
                    <input type="text"
                        class="tef-input"
                        name="Destination_state"
                        value="<?= esc($quote['Destination_state']) ?>">
                </div>

                <div class="tef-input-group tef-input-sm">
                    <label>País</label>
                    <input type="text"
                        class="tef-input"
                        name="Destination_country"
                        value="<?= esc($quote['Destination_country']) ?>">
                </div>

                <div class="tef-input-group tef-input-sm">
                    <label>Codigo Postal</label>
                    <input type="text"
                        class="tef-input"
                        name="Destination_zip"
                        value="<?= esc($quote['Destination_zip']) ?>">
                </div>

                <div class="tef-input-group tef-input-sm">
                    <label>Telefono</label>
                    <input type="text"
                        class="tef-input"
                        name="Destination_phone"
                        value="<?= esc($quote['Destination_phone']) ?>">
                </div>
            </div>
        </div>

        <!-- ================= PAQUETE ================= -->
        <div class="tef-card" style="margin-top:20px;">
            <h4>Paquete</h4>

            <div class="tef-form-row">

                <div class="tef-input-group tef-input-sm">
                    <label>Largo (cm)</label>
                    <input type="number" class="tef-input" name="Length_cm" step="0.01" value="<?= esc($quote['Length_cm']) ?>">
                </div>

                <div class="tef-input-group tef-input-sm">
                    <label>Ancho (cm)</label>
                    <input type="number" class="tef-input" name="Width_cm" step="0.01" value="<?= esc($quote['Width_cm']) ?>">
                </div>

                <div class="tef-input-group tef-input-sm">
                    <label>Alto (cm)</label>
                    <input type="number" class="tef-input" name="Height_cm" step="0.01" value="<?= esc($quote['Height_cm']) ?>">
                </div>

                <div class="tef-input-group tef-input-sm">
                    <label>Peso (kg)</label>
                    <input type="number" class="tef-input" name="Weight_kg" step="0.01" value="<?= esc($quote['Weight_kg']) ?>">
                </div>
                <div class="tef-input-group tef-input-sm">
                    <label>Valor declarado ($)</label>
                    <input type="number"
                        class="tef-input"
                        step="0.01"
                        name="Declared_value" value="<?= esc($quote['Declared_value']) ?>">
                </div>


            </div>

        </div>

        <!-- ================= SERVICIOS ================= -->
        <div class="tef-card" style="margin-top:20px;">
            <h4>Servicios cotizados</h4>

            <div id="services-container"></div>
        </div>



        <div class="tef-card">
            <h4>Costos</h4>

            <div class="tef-form-row">

                <div class="tef-input-group tef-input-md">
                    <label>Costo de operación</label>
                    <input type="number" class="tef-input" name="Operation_cost" step="0.01"
                        value="<?= esc($quote['Operation_cost']) ?>">
                </div>
                <div class="tef-input-group tef-input-md">
                    <label>Costo administrativo</label>
                    <input type="number" class="tef-input" name="Administrative_cost" step="0.01"
                        value="<?= esc($quote['Administrative_cost']) ?>"
                        >
                </div>
                <div class="tef-input-group tef-input-sm">
                    <label>Embalaje</label>
                    <input type="number" class="tef-input" name="Packaging_cost" step="0.01"
                        value="<?= esc($quote['Packaging_cost']) ?>">
                </div>
                
            </div>

            <div class="tef-form-row">

                <div class="tef-input-group tef-input-sm">
                    <label>Margen</label>
                    <input type="number" class="tef-input" name="Margin_amount" step="0.01"
                        value="<?= esc($quote['Margin_amount']) ?>">
                </div>
                
                <div class="tef-input-group tef-input-sm">
                    <label>IVA </label>
                    <input type="number" class="tef-input" name="Taxes" step="0.01"
                        value="<?= esc($quote['Taxes']) ?>">
                </div>
                <div class="tef-input-group tef-input-sm">
                    <label>SubTotal</label>
                    <input type="number" class="tef-input" name="Subtotal" step="0.01" value="<?= esc($quote['Subtotal']) ?>">
                </div>
                
            </div>
            
            <div class="tef-form-row">
                <div class="tef-input-group tef-input-sm">
                    <label>Total</label>
                    <input type="number" class="tef-input" name="Total_amount" step="0.01" value="<?= esc($quote['Total_amount']) ?>">
                </div>
                <div class="tef-input-group tef-input-sm">
                    <label>Comments</label>
                    <textarea name="Comments"
                        class="tef-input"
                        rows="4"
                        placeholder="Información adicional, notas, direcciones, tracking, etc."><?= esc($quote['Comments']) ?></textarea>
                </div>
            </div>
        </div>


        <!-- ================== OTROS DEFAULT ================== -->
        <input type="hidden" name="Currency" value="MXN">

        <!-- ================= ACCIONES ================= -->
        <div style="margin-top:30px;display:flex;gap:12px;">
            <button type="submit"
                class="c-btn"
                style="padding:12px 20px;
                    background:var(--tef-gold);
                    color:#000;
                    border-radius:12px;
                    font-weight:600;">
                Guardar cambios
            </button>


            <a href="<?= site_url('crm/quotes/') ?>"
               class="c-btn"
               style="padding:12px 20px;background:#222;color:#fff;border-radius:12px;">
                Cancelar
            </a>
        </div>

    </form>

</div>

<?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script>
    const existingServices = <?= json_encode($services ?? []) ?>;
</script>

<script>
function recalculateServices() {
    let subtotal = 0;

    document.querySelectorAll('[data-service]').forEach(service => {
        const qty = parseFloat(service.querySelector('[name*="[Quantity]"]').value) || 0;
        const price = parseFloat(service.querySelector('[name*="[Unit_price]"]').value) || 0;
        const total = qty * price;

        service.querySelector('[name*="[Total]"]').value = total.toFixed(2);
        subtotal += total;
    });

    document.querySelector('[name="Operation_cost"]').value = subtotal.toFixed(2);
}
</script>

<script>
let serviceIndex = 0;

function renderService(service) {

    const container = document.getElementById('services-container');

    const html = `
    <div class="tef-card" style="margin-top:12px;" data-service>

        <input type="hidden"
               name="services[${serviceIndex}][PK_Quote_Service]"
               value="${service.PK_Quote_Service}">

        <div class="tef-form-row">

            <div class="tef-input-group tef-input-md">
                <label>Tipo de servicio</label>
                <input type="text"
                       class="tef-input"
                       name="services[${serviceIndex}][Service_type]"
                       value="${service.Service_type}"
                       >
            </div>

            <div class="tef-input-group tef-input-md">
                <label>Nombre del servicio</label>
                <input type="text"
                       class="tef-input"
                       name="services[${serviceIndex}][Service_name]"
                       value="${service.Service_name}">
            </div>

        </div>

        <div class="tef-form-row">

            <div class="tef-input-group tef-input-sm">
                <label>Cantidad</label>
                <input type="number"
                       class="tef-input"
                       step="0.01"
                       name="services[${serviceIndex}][Quantity]"
                       value="${service.Quantity}">
            </div>

            <div class="tef-input-group tef-input-sm">
                <label>Precio unitario</label>
                <input type="number"
                       class="tef-input"
                       step="0.01"
                       name="services[${serviceIndex}][Unit_price]"
                       value="${service.Unit_price}">
            </div>

            <div class="tef-input-group tef-input-sm">
                <label>Total</label>
                <input type="number"
                       class="tef-input"
                       name="services[${serviceIndex}][Total]"
                       value="${service.Total}"
                       >
            </div>

        </div>

    </div>`;

    container.insertAdjacentHTML('beforeend', html);
    serviceIndex++;
}
</script>

<script>
    if (existingServices.length) {
        existingServices.forEach(service => renderService(service));
    }
</script>

<script>
function quotePreviewHTML() {

    const v = name =>
        document.querySelector(`[name="${name}"]`)?.value || '';

    let services = '';
    document.querySelectorAll('[data-service]').forEach(service => {
        services += `
            <tr>
                <td>${service.querySelector('[name*="[Service_name]"]').value}</td>
                <td style="text-align:center">${service.querySelector('[name*="[Quantity]"]').value}</td>
                <td style="text-align:right">$${parseFloat(service.querySelector('[name*="[Unit_price]"]').value || 0).toFixed(2)}</td>
                <td style="text-align:right">$${parseFloat(service.querySelector('[name*="[Total]"]').value || 0).toFixed(2)}</td>
            </tr>
        `;
    });

    return `
    <div style="text-align:left;font-size:14px">
        <h3>Vista previa de cotización</h3>
        <hr>

        <strong>Origen</strong><br>
        ${v('Origin_name')}<br>
        ${v('Origin_address')}<br>
        ${v('Origin_city')}, ${v('Origin_state')}<br><br>

        <strong>Destino</strong><br>
        ${v('Destination_name')}<br>
        ${v('Destination_address')}<br>
        ${v('Destination_city')}, ${v('Destination_state')}<br>

        <hr>

        <strong>Servicios</strong>
        <table width="100%" style="border-collapse:collapse;margin-top:6px">
            <thead>
                <tr>
                    <th align="left">Servicio</th>
                    <th>Cant.</th>
                    <th align="right">Precio</th>
                    <th align="right">Total</th>
                </tr>
            </thead>
            <tbody>${services}</tbody>
        </table>

        <hr>

        <table width="100%">
            <tr><td>Subtotal</td><td align="right">$${parseFloat(v('Subtotal') || 0).toFixed(2)}</td></tr>
            <tr><td>IVA</td><td align="right">$${parseFloat(v('Taxes') || 0).toFixed(2)}</td></tr>
            <tr style="font-weight:bold">
                <td>Total</td>
                <td align="right">$${parseFloat(v('Total_amount') || 0).toFixed(2)}</td>
            </tr>
        </table>
    </div>`;
}
</script>

<script>
document.querySelector('form').addEventListener('submit', function (e) {
    e.preventDefault();

    if (!document.querySelector('[data-service]')) {
        Swal.fire({
            icon: 'warning',
            title: 'Falta información',
            text: 'Agrega al menos un servicio para continuar'
        });
        return;
    }

    Swal.fire({
        title: 'Vista previa de la cotización',
        html: quotePreviewHTML(),
        width: 800,
        showCancelButton: true,
        confirmButtonText: 'Guardar cotización',
        cancelButtonText: 'Seguir editando',
        confirmButtonColor: '#C6A34F'
    }).then(result => {
        if (result.isConfirmed) {
            this.submit();
        }
    });
});
</script>
<script>
<?php if (session()->getFlashdata('success')): ?>
    Swal.fire({
        icon: 'success',
        title: 'Éxito',
        text: <?= json_encode(session()->getFlashdata('success')) ?>,
        confirmButtonColor: '#C6A34F'
    });
<?php endif; ?>

<?php if (session()->getFlashdata('error')): ?>
    Swal.fire({
        icon: 'error',
        title: 'Error',
        text: <?= json_encode(session()->getFlashdata('error')) ?>,
        confirmButtonColor: '#C6A34F'
    });
<?php endif; ?>

<?php if (session()->getFlashdata('warning')): ?>
    Swal.fire({
        icon: 'warning',
        title: 'Atención',
        text: <?= json_encode(session()->getFlashdata('warning')) ?>,
        confirmButtonColor: '#C6A34F'
    });
<?php endif; ?>

<?php if (session()->getFlashdata('info')): ?>
    Swal.fire({
        icon: 'info',
        title: 'Información',
        text: <?= json_encode(session()->getFlashdata('info')) ?>,
        confirmButtonColor: '#C6A34F'
    });
<?php endif; ?>
</script>
<?= $this->endSection() ?>
