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

<?= $this->section('titulo') ?>
Cotización <?= esc($quote['Quote_number']) ?>
<?= $this->endSection() ?>

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

<div class="tef-panel">

<?php
$statusClass = match($quote['Status']) {
    'Orden de Envio' => 'success',
    'Apartado' => 'info',
    default => 'info'
};
?>

<div class="tef-form-row" style="justify-content:space-between;align-items:center;margin-bottom:20px;">

    <div>
        <h2 class="tef-panel-title">
            Cotización <?= esc($quote['Quote_number']) ?>
        </h2>

        <span class="tef-status <?= $statusClass ?>">
            <?= esc($quote['Status'] ?? 'Borrador') ?>
        </span>
    </div>

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

        <?php if ($quote['Status'] === 'Cotizacion'): ?>
            <!-- <button type="button"
                    class="tef-btn tef-btn-secondary"
                    onclick="openPaymentModal('Apartado')">
                Aprobar como Apartado
            </button> -->

            <button type="button"
                    class="tef-btn tef-btn-success"
                    onclick="openPaymentModal('Orden de Envio')">
                Aprobar como Orden de Envío
            </button>
        <?php endif; ?>

        <?php if ($quote['Status'] === 'Apartado'): ?>
            <button type="button"
                    class="tef-btn tef-btn-success"
                    onclick="openPaymentModal('Orden de Envio')">
                Convertir a Orden de Envío
            </button>
        <?php endif; ?>

                <a class="tef-btn tef-btn-primary" href="<?= base_url('crm/quotes/edit/' . $quote['PK_Quote']) ?>">
                    Editar
                </a>
        
        

        <div class="tef-dropdown">
            <button class="tef-btn tef-btn-primary">
                Descargar PDF ▾
            </button>

            <div class="tef-dropdown-menu">
                <a href="<?= site_url('crm/quotes/pdf/'.$quote['PK_Quote'].'?lang=es') ?>" target="_blank">
                    Español
                </a>
                <a href="<?= site_url('crm/quotes/pdf/'.$quote['PK_Quote'].'?lang=en') ?>" target="_blank">
                    English
                </a>
            </div>
        </div>

    </div>

</div>


<!-- Cliente -->
<div class="tef-card" style="margin-bottom:20px;">
    <h4>Cliente</h4>
    <p>
        <b><?= esc($contact['First_name'].' '.$contact['Last_name']) ?></b><br>
        <?= esc($contact['Email']) ?>
    </p>
</div>


<!-- Origen / Destino -->
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px;">
    <div class="tef-card">
        <h4>Origen</h4>
        <p>
            <?= esc($quote['Origin_name']) ?><br>
            <?= esc($quote['Origin_city']) ?>, <?= esc($quote['Origin_country']) ?>
        </p>
    </div>

    <div class="tef-card">
        <h4>Destino</h4>
        <p>
            <?= esc($quote['Destination_name']) ?><br>
            <?= esc($quote['Destination_city']) ?>, <?= esc($quote['Destination_country']) ?>
        </p>
    </div>
</div>


<!-- Costos -->
<div class="tef-card">
    <h4>Desglose de costos</h4>

    <table class="c-table">
        <tbody>
            <tr><td>Costo operación</td>
                <td style="text-align:right;">$<?= number_format($quote['Operation_cost'], 2) ?></td></tr>

            <tr><td>Embalaje (<?= $quote['Packaging_pct'] ?>%)</td>
                <td style="text-align:right;">$<?= number_format($quote['Packaging_cost'], 2) ?></td></tr>

            <tr><td>Costo administrativo</td>
                <td style="text-align:right;">$<?= number_format($quote['Administrative_cost'], 2) ?></td></tr>

            <tr><td>Base envío</td>
                <td style="text-align:right;">$<?= number_format($quote['Base_cost'], 2) ?></td></tr>

            <tr><td>Seguro</td>
                <td style="text-align:right;">$<?= number_format($quote['Insurance_cost'], 2) ?></td></tr>

            <tr><td>Margen (<?= $quote['Margin_pct'] ?>%)</td>
                <td style="text-align:right;">$<?= number_format($quote['Margin_amount'], 2) ?></td></tr>

            <tr><td><b>Subtotal</b></td>
                <td style="text-align:right;"><b>$<?= number_format($quote['Subtotal'], 2) ?></b></td></tr>
                
            <tr><td>Impuestos</td>
                <td style="text-align:right;">$<?= number_format($quote['Taxes'], 2) ?></td></tr>
        </tbody>
    </table>
</div>


<div style="margin-top:20px;text-align:right;">
    <h3 style="color:var(--tef-gold);">
        TOTAL: $<?= number_format($quote['Total_amount'], 2) ?>
        <?= esc($quote['Currency']) ?>
    </h3>
</div>

</div>


<!-- MODAL PAGO -->
<div class="tef-modal-overlay" id="paymentModal">

<div class="tef-modal">

<div class="tef-modal-header">
    <div class="tef-modal-title">Registrar pago</div>
    <button class="tef-modal-close" onclick="closePaymentModal()">✕</button>
</div>

<div class="tef-modal-body">

<div class="tef-card kpi-card">
    <div class="kpi-label">Cotización</div>
    <div class="kpi-value" id="modalQuoteNumber">—</div>
</div>

<div class="tef-card">
    <div class="kpi-label">Total</div>
    <div class="kpi-value">
        $<?= number_format($quote['Total_amount'],2) ?>
        <?= esc($quote['Currency']) ?>
    </div>
</div>

<form id="paymentForm"
      method="post"
      action="<?= site_url('crm/quotes/approve/'.$quote['PK_Quote']) ?>">

<?= csrf_field() ?>

<input type="hidden" name="status" id="modalStatus">

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

<div class="tef-input-group tef-input-md">
<label>Método de pago</label>
<select id="paymentType" name="payment_method" class="tef-select" >
<option value="">Seleccionar…</option>
<option value="Transferencia">Transferencia</option>
<option value="Efectivo">Efectivo</option>
<option value="Tarjeta">Tarjeta</option>
<option value="Cheque">Cheque</option>
<option value="Clip">Clip</option>
</select>
<div id="clipDisclaimer" style="color:orange; font-size:0.9em; margin-top:5px; display:none;">
    ⚠️ Recuerda que Clip cobra comisión sobre el pago.
</div>
</div>

<div class="tef-input-group tef-input-sm">
    <label>Moneda</label>
    <select name="Currency" class="tef-select">
        <?php 
        $currencies = ['MXN' => 'Pesos', 'USD' => 'Dólares', 'EUR' => 'Euros'];
        $current = $quote['Currency'] ?? 'MXN';
        foreach ($currencies as $code => $name): ?>
            <option value="<?= esc($code) ?>" <?= $current === $code ? 'selected' : '' ?>>
                <?= esc($name) ?>
            </option>
        <?php endforeach; ?>
    </select>
</div>


</div>

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

<div class="tef-input-group tef-input-md">
<label>Monto pagado</label>
<input id="paymentAmount"
       type="number"
       step="0.01"
       name="amount_paid"
       class="tef-input"
       >
</div>

<div class="tef-input-group tef-input-md">
<label>Referencia</label>
<input type="text"
       name="reference"
       class="tef-input"
       placeholder="Folio / operación">
</div>

</div>

<div class="tef-input-group">
<label>Notas</label>
<textarea name="notes"
          class="tef-textarea"
          rows="3"></textarea>
</div>

<div class="tef-input-group">
    <label style="display:flex;align-items:center;gap:10px;">
        <input type="checkbox" id="allowCredit" name="allow_credit" value="1">
        Permitir crédito (autorizar orden sin pago completo)
    </label>
</div>

</form>

</div>

<div class="tef-modal-footer">
<button class="tef-btn tef-btn-muted" onclick="closePaymentModal()">Cancelar</button>
<button type="submit" form="paymentForm" class="tef-btn tef-btn-success">
Guardar pago
</button>
</div>

</div>
</div>


<?= $this->endSection() ?>

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

<script>
    
function openPaymentModal(status) {
    document.getElementById('modalStatus').value = status;
    document.getElementById('modalQuoteNumber').innerText =
        "<?= esc($quote['Quote_number']) ?>";

    document.getElementById('paymentAmount').value =
        <?= (float)$quote['Total_amount'] ?>;

    document.getElementById('paymentModal').classList.add('is-open');
}

function closePaymentModal() {
    document.getElementById('paymentModal').classList.remove('is-open');
}

const paymentTypeSelect = document.getElementById('paymentType');
const clipDisclaimer = document.getElementById('clipDisclaimer');

paymentTypeSelect.addEventListener('change', function() {
    if (this.value === 'Clip') {
        clipDisclaimer.style.display = 'block';
    } else {
        clipDisclaimer.style.display = 'none';
    }
});

</script>

<?php if (session()->getFlashdata('swal')): ?>
<script>
Swal.fire({
    icon: '<?= session('swal.icon') ?>',
    title: '<?= session('swal.title') ?>',
    text: '<?= session('swal.text') ?>',
    confirmButtonColor: '#C6A34F'
});
</script>
<?php endif; ?>
<script>
const total = <?= (float)$quote['Total_amount'] ?>;

document.getElementById('paymentAmount').addEventListener('input', function() {
    const paid = parseFloat(this.value || 0);
    const allowCredit = document.getElementById('allowCredit');

    if (paid < total) {
        allowCredit.parentElement.style.opacity = 1;
    } else {
        allowCredit.checked = false;
        allowCredit.parentElement.style.opacity = 0.4;
    }
});
</script>
<?= $this->endSection() ?>
