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

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

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

<div class="tef-panel">

    <h2>Nueva cotización</h2>
    <p class="text-muted">
        Cotización de envío asociada al contacto
    </p>

    <form method="post" action="<?= site_url('crm/quotes/store') ?>">

        <input type="hidden" name="FK_Contact" value="<?= esc($contact['PK_Contact']) ?>">

        <!-- ================= 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="Transporte Envio Facil">
                </div>

                <div class="tef-input-group tef-input-sm">
                    <label>Direccion</label>
                    <input type="text"
                        class="tef-input"
                        name="Origin_address"
                        value="Ignacio Allende 85, Colonia San Rafael">
                </div>

                <div class="tef-input-group tef-input-sm">
                    <label>Ciudad</label>
                    <input type="text"
                        class="tef-input"
                        name="Origin_city"
                        value="San Miguel de Allende">
                </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="Gto">
                </div>

                <div class="tef-input-group tef-input-sm">
                    <label>País</label>
                    <input type="text"
                        class="tef-input"
                        name="Origin_country"
                        value="Mexico">
                </div>

                <div class="tef-input-group tef-input-sm">
                    <label>Codigo Postal</label>
                    <input type="text"
                        class="tef-input"
                        name="Origin_zip"
                        value="37730">
                </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($contact['First_name'].' '.$contact['Last_name']) ?>">
                </div>

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

                <div class="tef-input-group tef-input-sm">
                    <label>Ciudad</label>
                    <input type="text"
                        class="tef-input"
                        name="Destination_city"
                        value="<?= esc($contact['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($contact['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($contact['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($contact['Postal_code']) ?>">
                </div>

                <div class="tef-input-group tef-input-sm">
                    <label>Telefono</label>
                    <input type="text"
                        class="tef-input"
                        name="Destination_phone"
                        value="<?= esc($contact['Phone']) ?>">
                </div>
            </div>
        </div>
        <!-- ================= EMPRESA ================= -->
        <div class="tef-card" style="margin-top:20px;">
            <h4>Empresa</h4>

            <div class="tef-form-row">
                <div class="tef-input-group tef-input-md">
                    <label>Nombre de la empresa</label>
                    <input type="text"
                        class="tef-input"
                        name="Company_name"
                        value="<?= esc($contact['Company_name'] ?? '') ?>"
                        placeholder="Empresa o razón social">
                </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">
                </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">
                </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">
                </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">
                </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">
                </div>


            </div>

        </div>

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

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

            <button type="button"
                    class="c-btn"
                    style="margin-top:12px;background:#222;color:#fff;border-radius:10px;padding:8px 14px;"
                    onclick="addService()">
                + Agregar servicio
            </button>
        </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">
                </div>
                <div class="tef-input-group tef-input-md">
                    <label>Costo administrativo (%)</label>
                    <input type="number" class="tef-input" name="Administrative_pct" step="0.01">
                </div>
                <div class="tef-input-group tef-input-sm">
                    <label>Embalaje (%)</label>
                    <input type="number" class="tef-input" name="Packaging_pct" step="0.01">
                </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_pct" step="0.01">
                </div>
                <div class="tef-input-group tef-input-sm">
                    <label>Total</label>
                    <input type="number" class="tef-input" name="Total_amount" step="0.01" readonly>
                </div>
                <div class="tef-input-group tef-input-sm">
                    <label>IVA (%)</label>
                    <input type="number"
                        class="tef-input"
                        name="Taxes_pct" step="0.01">
                </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."></textarea>
                </div>
            </div>
        </div>

        <!-- ================== CALCULADOS BACKEND ================== -->
        <input type="hidden" name="Packaging_cost">
        <input type="hidden" name="Base_cost">
        <input type="hidden" name="Margin_amount">
        <input type="hidden" name="Subtotal">
        <input type="hidden" name="Total_amount">
        <input type="hidden" name="Administrative_cost">
        <input type="hidden" name="Taxes_amount">


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

        <div class="tef-card" style="margin-top:20px;">

            <h4 style="margin-bottom:16px;">
                Desglose de costos
            </h4>

            <div class="tef-breakdown">

                <div class="tef-row">
                    <span>Costo de operación</span>
                    <strong id="bd-operation">$0.00</strong>
                </div>

                <div class="tef-row">
                    <span>Costo administrativo</span>
                    <strong id="bd-admin">$0.00</strong>
                </div>


                <div class="tef-row">
                    <span>Embalaje (<span id="bd-pack-pct">0</span>%)</span>
                    <strong id="bd-pack-cost">$0.00</strong>
                </div>

                <div class="tef-row">
                    <span>Base</span>
                    <strong id="bd-base">$0.00</strong>
                </div>

                <div class="tef-row">
                    <span>Margen (<span id="bd-margin-pct">0</span>%)</span>
                    <strong id="bd-margin">$0.00</strong>
                </div>
                <div class="tef-row">
                    <span>IVA (<span id="bd-tax-pct">0</span>%)</span>
                    <strong id="bd-tax">$0.00</strong>
                </div>

                <hr style="border-color:var(--tef-border);">

                <div class="tef-row tef-total">
                    <span>Total cotizado</span>
                    <strong id="bd-total">$0.00</strong>
                </div>

            </div>

        </div>


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

            <a href="<?= site_url('crm/contacts/view/'.$contact['PK_Contact']) ?>"
               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>
(function () {

    function val(name) {
        return parseFloat(document.querySelector(`[name="${name}"]`)?.value) || 0;
    }

    function set(name, value) {
        const el = document.querySelector(`[name="${name}"]`);
        if (el) el.value = value.toFixed(2);
    }

    window.calculate = function () {

        const operation     = val('Operation_cost');
        const adminPct      = val('Administrative_pct');
        const packPct       = val('Packaging_pct');
        const marginPct     = val('Margin_pct');
        const taxPct        = val('Taxes_pct');

        const adminCost = operation * (adminPct / 100);
        const baseBeforePack = operation + adminCost;
        const packagingCost = baseBeforePack * (packPct / 100);
        const baseCost = baseBeforePack + packagingCost;
        const marginAmount = baseCost * (marginPct / 100);
        const subtotal = baseCost + marginAmount;
        const taxAmount = subtotal * (taxPct / 100);
        const total = subtotal + taxAmount;

        set('Administrative_cost', adminCost);
        set('Packaging_cost', packagingCost);
        set('Base_cost', baseCost);
        set('Margin_amount', marginAmount);
        set('Subtotal', subtotal);
        set('Taxes_amount', taxAmount);
        set('Total_amount', total);

        document.getElementById('bd-operation').innerText = `$${operation.toFixed(2)}`;
        document.getElementById('bd-admin').innerText = `$${adminCost.toFixed(2)}`;
        document.getElementById('bd-pack-pct').innerText = packPct.toFixed(2);
        document.getElementById('bd-pack-cost').innerText = `$${packagingCost.toFixed(2)}`;
        document.getElementById('bd-base').innerText = `$${baseCost.toFixed(2)}`;
        document.getElementById('bd-margin-pct').innerText = marginPct.toFixed(2);
        document.getElementById('bd-margin').innerText = `$${marginAmount.toFixed(2)}`;
        document.getElementById('bd-tax-pct').innerText = taxPct.toFixed(2);
        document.getElementById('bd-tax').innerText = `$${taxAmount.toFixed(2)}`;
        document.getElementById('bd-total').innerText = `$${total.toFixed(2)}`;
    };

    [
        'Operation_cost',
        'Administrative_pct',
        'Packaging_pct',
        'Margin_pct',
        'Taxes_pct'
    ].forEach(name => {
        document.querySelector(`[name="${name}"]`)
            ?.addEventListener('input', calculate);
    });

})();
</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);
    calculate();
}
</script>

<script>
let serviceIndex = 0;

function addService(data = {}) {

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

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

        <div class="tef-form-row">
            <div class="tef-input-group tef-input-md">
                <label>Tipo de servicio</label>
                <select class="tef-input" name="services[${serviceIndex}][Service_type]">
                    <option value="Envio nacional">Envío nacional</option>
                    <option value="Envio nacional express">Envío nacional express</option>
                    <option value="Envio internacional">Envío internacional</option>
                    <option value="Envio internacional express">Envío internacional express</option>
                    <option value="Embalaje">Embalaje</option>
                    <option value="Restauracion">Restauración</option>
                    <option value="Instalacion">Instalación</option>
                    <option value="Asesoria">Asesoría</option>
                </select>
            </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]">
            </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"
                       value="1"
                       name="services[${serviceIndex}][Quantity]"
                       oninput="recalculateServices()">
            </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]"
                       oninput="recalculateServices()">
            </div>

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

        <button type="button"
                class="c-btn"
                style="margin-top:8px;color:#c55;"
                onclick="this.closest('[data-service]').remove(); recalculateServices();">
            Eliminar servicio
        </button>

    </div>`;

    container.insertAdjacentHTML('beforeend', html);
    serviceIndex++;
}
</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_amount') || 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() ?>
