<?php
/**
 * ASISMA CRM - Listado de Cotizaciones
 */
?>
<!-- Header -->
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-8">
    <div>
        <h1 class="text-3xl font-extrabold text-white tracking-tight">Cotizaciones</h1>
        <p class="text-slate-400 text-sm mt-1">Historial de ofertas comerciales enviadas y su estado de lectura.</p>
    </div>
</div>

<!-- Filters Bar -->
<div class="bg-slate-900 border border-slate-800 rounded-2xl p-6 shadow-xl mb-8">
    <form method="GET" action="<?php echo APP_URL; ?>/cotizaciones" class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <!-- Search Query -->
        <div>
            <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">Buscar</label>
            <div class="relative">
                <span class="absolute inset-y-0 left-0 pl-3 flex items-center text-slate-500">
                    <i data-lucide="search" class="w-4 h-4"></i>
                </span>
                <input type="text" name="q" value="<?php echo htmlspecialchars($filters['q']); ?>"
                       class="block w-full pl-9 pr-3 py-2.5 bg-slate-950 border border-slate-800 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                       placeholder="Cliente, RUT, ejecutivo...">
            </div>
        </div>

        <!-- Filter by State -->
        <div>
            <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">Estado</label>
            <select name="estado" class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-800 rounded-xl text-slate-300 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                <option value="">-- Todos los Estados --</option>
                <option value="borrador" <?php echo $filters['estado'] === 'borrador' ? 'selected' : ''; ?>>Borrador</option>
                <option value="enviada" <?php echo $filters['estado'] === 'enviada' ? 'selected' : ''; ?>>Enviada</option>
                <option value="vista" <?php echo $filters['estado'] === 'vista' ? 'selected' : ''; ?>>Vista / Leída</option>
                <option value="aceptada" <?php echo $filters['estado'] === 'aceptada' ? 'selected' : ''; ?>>Aceptada</option>
                <option value="pagada" <?php echo $filters['estado'] === 'pagada' ? 'selected' : ''; ?>>Pagada</option>
                <option value="rechazada" <?php echo $filters['estado'] === 'rechazada' ? 'selected' : ''; ?>>Rechazada</option>
                <option value="vencida" <?php echo $filters['estado'] === 'vencida' ? 'selected' : ''; ?>>Vencida</option>
            </select>
        </div>

        <!-- Actions -->
        <div class="flex items-end gap-3 md:col-span-2">
            <button type="submit" class="flex-1 py-2.5 bg-slate-800 hover:bg-slate-700 text-slate-200 font-semibold rounded-xl text-sm transition-colors border border-slate-700">
                Filtrar
            </button>
            <a href="<?php echo APP_URL; ?>/cotizaciones" class="flex-1 py-2.5 bg-slate-950 hover:bg-slate-900 text-slate-400 text-center font-medium rounded-xl text-sm transition-colors border border-slate-800/80">
                Limpiar
            </a>
        </div>
    </form>
</div>

<!-- Table Card -->
<div class="bg-slate-900 border border-slate-800/80 rounded-2xl overflow-hidden shadow-xl">
    <div class="overflow-x-auto">
        <table class="w-full text-left text-sm border-collapse">
            <thead>
                <tr class="bg-slate-950 border-b border-slate-800 text-slate-400 uppercase text-xs tracking-wider">
                    <th class="px-6 py-4 font-semibold">N° Cotización</th>
                    <th class="px-6 py-4 font-semibold">Cliente / Empresa</th>
                    <th class="px-6 py-4 font-semibold">Monto Total</th>
                    <th class="px-6 py-4 font-semibold">Estado</th>
                    <th class="px-6 py-4 font-semibold">Ejecutivo</th>
                    <th class="px-6 py-4 font-semibold">Emisión / Vencimiento</th>
                    <th class="px-6 py-4 font-semibold text-right">Acciones</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-850 text-slate-300">
                <?php if (empty($cotizaciones)): ?>
                    <tr>
                        <td colspan="7" class="px-6 py-12 text-center text-slate-500">
                            <div class="w-12 h-12 rounded-xl bg-slate-950 border border-slate-850 flex items-center justify-center mx-auto mb-3">
                                <i data-lucide="file-text" class="w-6 h-6"></i>
                            </div>
                            <span class="text-sm font-semibold">No se encontraron cotizaciones</span>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($cotizaciones as $c): ?>
                        <tr class="hover:bg-slate-800/30 transition-colors">
                            <!-- ID / N° -->
                            <td class="px-6 py-4 font-mono text-xs font-bold text-slate-400">
                                <?php echo folio_cotizacion($c); ?>
                            </td>

                            <!-- Cliente -->
                            <td class="px-6 py-4">
                                <div class="font-bold text-slate-100"><?php echo htmlspecialchars($c['cliente_razon_social']); ?></div>
                                <div class="text-xs text-slate-500 mt-0.5">Contacto: <?php echo htmlspecialchars($c['cliente_contacto']); ?></div>
                            </td>

                            <!-- Total -->
                            <td class="px-6 py-4 font-mono text-sm text-slate-200 font-bold">
                                $<?php echo number_format($c['total'], 0, ',', '.'); ?> <span class="text-[10px] text-slate-500"><?php echo $c['moneda']; ?></span>
                            </td>

                            <!-- Estado Badge -->
                            <td class="px-6 py-4">
                                <?php
                                $badgeColor = 'bg-slate-800 text-slate-300 border-slate-700';
                                switch ($c['estado']) {
                                    case 'borrador': $badgeColor = 'bg-slate-800 text-slate-300 border-slate-700'; break;
                                    case 'enviada': $badgeColor = 'bg-blue-500/10 text-blue-400 border border-blue-500/20'; break;
                                    case 'vista': $badgeColor = 'bg-amber-500/10 text-amber-400 border border-amber-500/20'; break;
                                    case 'aceptada': $badgeColor = 'bg-green-500/10 text-green-400 border border-green-500/20'; break;
                                    case 'pagada': $badgeColor = 'bg-emerald-500/15 text-emerald-300 border border-emerald-500/30 font-bold'; break;
                                    case 'rechazada': $badgeColor = 'bg-red-500/10 text-red-400 border border-red-500/20'; break;
                                    case 'vencida': $badgeColor = 'bg-slate-950 text-slate-600 border border-slate-900'; break;
                                }
                                ?>
                                <span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold border <?php echo $badgeColor; ?> capitalize">
                                    <?php echo $c['estado']; ?>
                                </span>
                            </td>

                            <!-- Ejecutivo -->
                            <td class="px-6 py-4 text-xs">
                                <div class="font-semibold text-slate-200"><?php echo htmlspecialchars($c['ejecutivo_nombre']); ?></div>
                                <div class="text-[10px] text-slate-500 mt-0.5"><?php echo htmlspecialchars($c['franquiciado_nombre']); ?></div>
                            </td>

                            <!-- Fechas -->
                            <td class="px-6 py-4 text-xs font-mono text-slate-400">
                                <div>Emi: <?php echo date('d-m-Y', strtotime($c['created_at'])); ?></div>
                                <div class="text-red-400/80 mt-0.5">Venc: <?php echo date('d-m-Y', strtotime($c['vencimiento_at'])); ?></div>
                            </td>

                            <!-- Acciones -->
                            <td class="px-6 py-4 text-right">
                                <div class="flex justify-end items-center gap-2">
                                    <?php if ($c['estado'] === 'aceptada'): ?>
                                    <button onclick="marcarComoPagada(<?php echo $c['id']; ?>, '<?php echo folio_cotizacion($c); ?>')"
                                            class="inline-flex items-center gap-1.5 px-3 py-2 bg-emerald-600 hover:bg-emerald-500 text-white rounded-lg text-xs font-black uppercase tracking-wide transition-colors shadow-lg shadow-emerald-600/20"
                                            title="Confirmar el pago: genera la factura en Control Empresas y notifica a la marca">
                                        <i data-lucide="badge-dollar-sign" class="w-4 h-4"></i> Marcar como pagado
                                    </button>
                                    <?php endif; ?>
                                    <a href="<?php echo APP_URL; ?>/cotizaciones/ver?id=<?php echo $c['id']; ?>"
                                       class="p-2 bg-slate-850 hover:bg-slate-800 text-slate-300 rounded-lg hover:text-white transition-colors border border-slate-700/60"
                                       title="Ver Cotización">
                                        <i data-lucide="eye" class="w-4 h-4"></i>
                                    </a>
                                    <a href="<?php echo APP_URL; ?>/cotizaciones/ver?id=<?php echo $c['id']; ?>&pdf=1" target="_blank"
                                       class="p-2 bg-slate-850 hover:bg-slate-800 text-red-400 rounded-lg hover:text-red-300 transition-colors border border-slate-700/60"
                                       title="Descargar PDF">
                                        <i data-lucide="file-text" class="w-4 h-4"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php include dirname(__FILE__) . '/_marcar_pagada_js.php'; ?>

    <!-- Paginación -->
    <?php if ($totalPages > 1): ?>
        <div class="bg-slate-950 border-t border-slate-800 px-6 py-4 flex items-center justify-between">
            <span class="text-xs text-slate-500">Mostrando página <?php echo $page; ?> de <?php echo $totalPages; ?></span>
            <div class="flex gap-2">
                <a href="<?php echo $page > 1 ? APP_URL . '/cotizaciones?' . http_build_query(array_merge($_GET, ['page' => $page - 1])) : '#'; ?>" 
                   class="px-3 py-1.5 bg-slate-900 border border-slate-800 text-slate-400 hover:text-white text-xs font-semibold rounded-lg transition-colors <?php echo $page <= 1 ? 'opacity-50 pointer-events-none' : ''; ?>">
                    Anterior
                </a>
                <a href="<?php echo $page < $totalPages ? APP_URL . '/cotizaciones?' . http_build_query(array_merge($_GET, ['page' => $page + 1])) : '#'; ?>" 
                   class="px-3 py-1.5 bg-slate-900 border border-slate-800 text-slate-400 hover:text-white text-xs font-semibold rounded-lg transition-colors <?php echo $page >= $totalPages ? 'opacity-50 pointer-events-none' : ''; ?>">
                    Siguiente
                </a>
            </div>
        </div>
    <?php endif; ?>
</div>
