<?php
/**
 * ASISMA CRM - Gestión de Regiones
 */
?>
<!-- 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">Regiones y Zonas Geográficas</h1>
        <p class="text-slate-400 text-sm mt-1">Regiones para la calificación territorial de franquiciados y leads.</p>
    </div>
    <button onclick="abrirModalRegion()"
            class="px-4 py-2.5 bg-blue-600 hover:bg-blue-500 text-white rounded-xl text-sm font-semibold transition-all shadow-md shadow-blue-600/10 flex items-center gap-1.5 self-start">
        <i data-lucide="plus" class="w-4 h-4"></i>
        <span>Nueva Región</span>
    </button>
</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 w-20">ID</th>
                    <th class="px-6 py-4 font-semibold w-28">Código</th>
                    <th class="px-6 py-4 font-semibold">Nombre de la Región</th>
                    <th class="px-6 py-4 font-semibold text-center">Franquiciados</th>
                    <th class="px-6 py-4 font-semibold text-center">Leads</th>
                    <th class="px-6 py-4 font-semibold text-center">Estado</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 foreach ($regiones as $reg): ?>
                    <tr class="hover:bg-slate-800/30 transition-colors">
                        <td class="px-6 py-4 font-mono text-xs text-slate-500">#<?php echo $reg['id']; ?></td>
                        <td class="px-6 py-4 font-mono text-xs text-slate-300 font-semibold"><?php echo htmlspecialchars($reg['codigo'] ? $reg['codigo'] : '—'); ?></td>
                        <td class="px-6 py-4 font-bold text-slate-100"><?php echo htmlspecialchars($reg['nombre']); ?></td>
                        <td class="px-6 py-4 text-center">
                            <span class="text-xs font-semibold <?php echo $reg['total_franquiciados'] > 0 ? 'text-blue-400' : 'text-slate-600'; ?>"><?php echo $reg['total_franquiciados']; ?></span>
                        </td>
                        <td class="px-6 py-4 text-center">
                            <span class="text-xs font-semibold <?php echo $reg['total_leads'] > 0 ? 'text-emerald-400' : 'text-slate-600'; ?>"><?php echo $reg['total_leads']; ?></span>
                        </td>
                        <td class="px-6 py-4 text-center">
                            <span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold <?php echo $reg['activa'] ? 'bg-green-500/10 text-green-400 border border-green-500/20' : 'bg-red-500/10 text-red-400 border border-red-500/20'; ?>">
                                <?php echo $reg['activa'] ? 'Activa' : 'Inactiva'; ?>
                            </span>
                        </td>
                        <td class="px-6 py-4 text-right">
                            <div class="flex items-center justify-end gap-2">
                                <button onclick='abrirModalRegion(<?php echo json_encode(array("id" => (int)$reg["id"], "nombre" => $reg["nombre"], "codigo" => $reg["codigo"]), JSON_HEX_APOS | JSON_HEX_QUOT); ?>)'
                                        class="p-2 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg transition-colors" title="Editar">
                                    <i data-lucide="pencil" class="w-3.5 h-3.5"></i>
                                </button>
                                <button onclick="toggleRegion(<?php echo $reg['id']; ?>, <?php echo $reg['activa'] ? 1 : 0; ?>)"
                                        class="p-2 bg-slate-800 hover:bg-slate-700 <?php echo $reg['activa'] ? 'text-amber-400' : 'text-emerald-400'; ?> rounded-lg transition-colors"
                                        title="<?php echo $reg['activa'] ? 'Desactivar' : 'Activar'; ?>">
                                    <i data-lucide="<?php echo $reg['activa'] ? 'power-off' : 'power'; ?>" class="w-3.5 h-3.5"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Modal Crear/Editar Región -->
<div id="modalRegion" class="hidden fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4">
    <div class="bg-slate-900 border border-slate-800 rounded-2xl shadow-2xl w-full max-w-md p-6">
        <div class="flex items-center justify-between mb-6">
            <h3 class="text-lg font-bold text-white" id="modalRegionTitulo">Nueva Región</h3>
            <button onclick="$('#modalRegion').addClass('hidden')" class="text-slate-500 hover:text-slate-300">
                <i data-lucide="x" class="w-5 h-5"></i>
            </button>
        </div>
        <form id="formRegion" class="space-y-4">
            <input type="hidden" name="id" value="0">
            <div>
                <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">Nombre *</label>
                <input type="text" name="nombre" required placeholder="ej: Región Metropolitana"
                       class="w-full px-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">
            </div>
            <div>
                <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">Código</label>
                <input type="text" name="codigo" placeholder="ej: RM" maxlength="10"
                       class="w-full px-3 py-2.5 bg-slate-950 border border-slate-800 rounded-xl text-slate-200 text-sm font-mono uppercase focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            <div class="flex justify-end gap-4 pt-2">
                <button type="button" onclick="$('#modalRegion').addClass('hidden')"
                        class="px-4 py-2.5 border border-red-500/40 hover:border-red-500/70 hover:bg-red-500/10 text-red-400 rounded-xl text-sm font-semibold transition-colors">Cancelar</button>
                <button type="submit"
                        class="px-5 py-2.5 bg-blue-600 hover:bg-blue-500 text-white rounded-xl text-sm font-semibold transition-colors">Guardar</button>
            </div>
        </form>
    </div>
</div>

<script>
function abrirModalRegion(data) {
    var form = $('#formRegion');
    form[0].reset();
    if (data) {
        $('#modalRegionTitulo').text('Editar Región');
        form.find('[name=id]').val(data.id);
        form.find('[name=nombre]').val(data.nombre);
        form.find('[name=codigo]').val(data.codigo || '');
    } else {
        $('#modalRegionTitulo').text('Nueva Región');
        form.find('[name=id]').val(0);
    }
    $('#modalRegion').removeClass('hidden');
    lucide.createIcons();
}

function toggleRegion(id, activa) {
    Swal.fire({
        title: activa ? '¿Desactivar región?' : '¿Activar región?',
        text: activa ? 'Los nuevos leads no podrán calificar en esta región.' : 'La región volverá a estar disponible.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Sí, continuar',
        cancelButtonText: 'Cancelar',
        background: '#1e293b',
        color: '#f8fafc',
        confirmButtonColor: activa ? '#d97706' : '#059669'
    }).then(function(r) {
        if (!r.isConfirmed) return;
        $.post('<?php echo APP_URL; ?>/regiones/toggle', { id: id }, function(res) {
            if (res.success) location.reload();
            else Swal.fire({ icon: 'error', title: 'No se pudo cambiar', text: res.message, background: '#1e293b', color: '#f8fafc' });
        }, 'json');
    });
}

$(document).ready(function() {
    $('#formRegion').on('submit', function(e) {
        e.preventDefault();
        var id  = $(this).find('[name=id]').val();
        var url = '<?php echo APP_URL; ?>/regiones/' + (id > 0 ? 'editar' : 'crear');
        $.post(url, $(this).serialize(), function(res) {
            if (res.success) {
                Swal.fire({ icon: 'success', title: res.message, background: '#1e293b', color: '#f8fafc', timer: 1400, showConfirmButton: false })
                    .then(function() { location.reload(); });
            } else {
                Swal.fire({ icon: 'error', title: 'Error', text: res.message, background: '#1e293b', color: '#f8fafc', confirmButtonColor: '#ef4444' });
            }
        }, 'json');
    });
});
</script>
