<?php /** ASISMA CRM - Marcas CRUD */ ?>
<?php
$puedeEditarCatalogo = SessionHelper::isAdmin();
?>

<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">Marcas Representadas</h1>
        <p class="text-slate-400 text-sm mt-1">Directorio de marcas asociadas a verticales de negocio.</p>
    </div>
    <?php if ($puedeEditarCatalogo): ?>
    <button onclick="openModal()" class="inline-flex items-center gap-2 px-4 py-2.5 bg-blue-600 hover:bg-blue-500 text-white text-sm font-semibold rounded-xl transition-colors shadow-lg">
        <i data-lucide="plus" class="w-4 h-4"></i> Nueva Marca
    </button>
    <?php endif; ?>
</div>

<div class="mb-4 flex justify-end">
    <a href="?inactivos=<?php echo $mostrarInactivos ? '0' : '1'; ?>" class="inline-flex items-center gap-1.5 text-xs font-semibold text-slate-400 hover:text-slate-200 transition-colors">
        <i data-lucide="<?php echo $mostrarInactivos ? 'eye-off' : 'eye'; ?>" class="w-3.5 h-3.5"></i>
        <?php echo $mostrarInactivos ? 'Ocultar inactivos (mostrar solo activos)' : 'Mostrar tambien los inactivos'; ?>
    </a>
</div>

<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">Nombre</th>
                    <th class="px-6 py-4 font-semibold">Vertical</th>
                    <th class="px-6 py-4 font-semibold">Contacto</th>
                    <th class="px-6 py-4 font-semibold text-center">Estado</th>
                    <?php if ($puedeEditarCatalogo): ?>
                    <th class="px-6 py-4 font-semibold text-right">Acciones</th>
                    <?php endif; ?>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-800 text-slate-300">
                <?php if (empty($marcas)): ?>
                <tr><td colspan="6" class="px-6 py-10 text-center text-slate-500">No hay marcas registradas.</td></tr>
                <?php else: ?>
                <?php foreach ($marcas as $m): ?>
                <tr class="hover:bg-slate-800/30 transition-colors">
                    <td class="px-6 py-4 font-bold text-slate-100"><?php echo htmlspecialchars($m['nombre']); ?></td>
                    <td class="px-6 py-4">
                        <span class="inline-flex items-center rounded-md bg-slate-800 px-2 py-0.5 text-xs font-semibold text-slate-300 border border-slate-700"><?php echo htmlspecialchars($m['vertical_nombre']); ?></span>
                    </td>
                    <td class="px-6 py-4 text-xs">
                        <div class="text-slate-300 font-semibold"><?php echo htmlspecialchars(isset($m['contacto_nombre']) ? $m['contacto_nombre'] : '-'); ?></div>
                        <div class="text-slate-500 mt-0.5"><?php echo htmlspecialchars(isset($m['contacto_email']) ? $m['contacto_email'] : ''); ?></div>
                    </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 $m['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 $m['activa'] ? 'Activa' : 'Inactiva'; ?>
                        </span>
                    </td>
                    <?php if ($puedeEditarCatalogo): ?>
                    <td class="px-6 py-4 text-right space-x-2">
                        <button onclick='openModal(<?php echo json_encode($m); ?>)' class="px-3 py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-200 rounded-lg text-xs font-semibold transition-colors border border-slate-700">Editar</button>
                        <button onclick="toggleEstado(<?php echo $m['id']; ?>, <?php echo $m['activa'] ? 0 : 1; ?>)"
                                class="px-3 py-1.5 <?php echo $m['activa'] ? 'bg-red-950/30 hover:bg-red-950/50 text-red-400 border border-red-900/30' : 'bg-green-950/30 hover:bg-green-950/50 text-green-400 border border-green-900/30'; ?> rounded-lg text-xs font-semibold transition-colors">
                            <?php echo $m['activa'] ? 'Desactivar' : 'Activar'; ?>
                        </button>
                    </td>
                    <?php endif; ?>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Modal -->
<div id="modalOverlay" class="fixed inset-0 z-50 flex items-start justify-center hidden bg-slate-950/70 backdrop-blur-sm px-4 overflow-y-auto py-8">
    <div class="bg-slate-900 border border-slate-800 rounded-2xl w-full max-w-3xl p-6 shadow-2xl">
        <h3 id="modalTitle" class="text-lg font-bold text-white mb-5">Nueva Marca</h3>
        <form id="modalForm" class="space-y-4">
            <input type="hidden" id="fId" name="id" value="">

            <!-- Tabs: Datos / Branding de cotizaciones -->
            <div class="flex gap-1 bg-slate-950 border border-slate-800 rounded-xl p-1 text-xs font-semibold">
                <button type="button" data-tab-marca="datos" class="tab-marca flex-1 px-3 py-2 rounded-lg bg-blue-600 text-white">Datos</button>
                <button type="button" data-tab-marca="branding" class="tab-marca flex-1 px-3 py-2 rounded-lg text-slate-400 hover:text-white">Cotizaciones / Branding</button>
            </div>

            <!-- Tab: Datos -->
            <div data-panel-marca="datos" class="panel-marca grid grid-cols-2 gap-4">
                <div class="col-span-2">
                    <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-1.5">Vertical *</label>
                    <select id="fVerticalId" name="vertical_id" required
                            class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-700 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="">-- Seleccionar --</option>
                        <?php foreach ($verticales as $v): ?>
                        <option value="<?php echo $v['id']; ?>"><?php echo htmlspecialchars($v['nombre']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-span-2">
                    <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-1.5">Nombre *</label>
                    <input type="text" id="fNombre" name="nombre" required
                           class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-700 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-1.5">Nombre Contacto</label>
                    <input type="text" id="fContactoNombre" name="contacto_nombre"
                           class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-700 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-1.5">Telefono Contacto *</label>
                    <input type="text" id="fContactoTelefono" name="contacto_telefono" required
                           class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-700 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
                <div class="col-span-2">
                    <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-1.5">Email Contacto *</label>
                    <input type="email" id="fContactoEmail" name="contacto_email" required
                           class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-700 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <p class="text-[11px] text-slate-500 mt-1">A este correo se le notifica cada venta de productos de la marca.</p>
                </div>
            </div>

            <!-- Tab: Branding de cotizaciones (aplica a TODO lo que la marca vende) -->
            <div data-panel-marca="branding" class="panel-marca hidden space-y-4">
                <p class="text-[11px] text-slate-500">Esta identidad aplica a TODAS las cotizaciones de la marca (productos y servicios). El contenido de cada oferta (párrafos, garantía, planes) se edita en el servicio.</p>

                <!-- Diseño del documento: 5 pre-configurados -->
                <div>
                    <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">Diseño del documento</label>
                    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">
                        <?php foreach (IdentidadHelper::disenos() as $claveDiseno => $d): ?>
                        <label class="diseno-card flex flex-col gap-1 p-3 bg-slate-950 border border-slate-700 rounded-xl cursor-pointer hover:border-blue-500 transition-colors">
                            <span class="flex items-center gap-2">
                                <input type="radio" name="diseno_documento" value="<?php echo $claveDiseno; ?>" <?php echo $claveDiseno === 'ejecutivo' ? 'checked' : ''; ?>>
                                <span class="text-sm font-bold text-slate-200"><?php echo htmlspecialchars($d['nombre']); ?></span>
                            </span>
                            <span class="text-[11px] text-slate-500 leading-snug"><?php echo htmlspecialchars($d['descripcion']); ?></span>
                        </label>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                    <div>
                        <label class="block text-[11px] font-semibold text-slate-500 uppercase tracking-wider mb-1">Color primario</label>
                        <input type="color" id="fColorPrimario" name="color_primario" value="#1c2430" class="block w-full h-10 bg-slate-950 border border-slate-700 rounded-xl cursor-pointer">
                    </div>
                    <div>
                        <label class="block text-[11px] font-semibold text-slate-500 uppercase tracking-wider mb-1">Color secundario</label>
                        <input type="color" id="fColorSecundario" name="color_secundario" value="#334155" class="block w-full h-10 bg-slate-950 border border-slate-700 rounded-xl cursor-pointer">
                    </div>
                    <div class="col-span-2">
                        <label class="block text-[11px] font-semibold text-slate-500 uppercase tracking-wider mb-1">Logo (ruta en public/)</label>
                        <input type="text" id="fLogoRuta" name="logo_ruta" placeholder="assets/img/logo_marca.png"
                               class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-700 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                        <label class="block text-[11px] font-semibold text-slate-500 uppercase tracking-wider mb-1">Eslogan</label>
                        <input type="text" id="fEslogan" name="eslogan" class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-700 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    <div>
                        <label class="block text-[11px] font-semibold text-slate-500 uppercase tracking-wider mb-1">Teléfono contacto (documento)</label>
                        <input type="text" id="fTelefonoContacto" name="telefono_contacto" placeholder="+56 9 ..." class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-700 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    <div>
                        <label class="block text-[11px] font-semibold text-slate-500 uppercase tracking-wider mb-1">Ciudad de firma</label>
                        <input type="text" id="fCiudadFirma" name="ciudad_firma" class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-700 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                </div>

                <div class="border-t border-slate-800 pt-3">
                    <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">Datos de transferencia</label>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div><input type="text" id="fTransTitular" name="transferencia_titular" placeholder="Titular" class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-700 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"></div>
                        <div><input type="text" id="fTransRut" name="transferencia_rut" placeholder="RUT del titular" class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-700 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"></div>
                        <div><input type="text" id="fTransBanco" name="transferencia_banco" placeholder="Banco" class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-700 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"></div>
                        <div><input type="text" id="fTransTipo" name="transferencia_tipo_cuenta" placeholder="Tipo de cuenta" class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-700 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"></div>
                        <div><input type="text" id="fTransNumero" name="transferencia_numero_cuenta" placeholder="N° de cuenta" class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-700 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"></div>
                        <div><input type="email" id="fTransCorreo" name="transferencia_correo" placeholder="Correo para comprobantes" class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-700 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"></div>
                    </div>
                </div>

                <div>
                    <label class="block text-[11px] font-semibold text-slate-500 uppercase tracking-wider mb-1">Condiciones comerciales <span class="normal-case text-slate-600">(una por línea: Título | texto)</span></label>
                    <textarea id="fCondiciones" name="condiciones" rows="3" placeholder="Vigencia | Esta cotización es válida hasta el {vencimiento}."
                              class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-700 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
                </div>

                <button type="button" onclick="previsualizarMarca()" class="inline-flex items-center gap-1.5 px-4 py-2 bg-slate-950 hover:bg-slate-800 border border-slate-700 text-slate-300 text-xs font-semibold rounded-lg transition-colors">
                    <i data-lucide="eye" class="w-3.5 h-3.5"></i> Vista previa del documento
                </button>
            </div>

            <div class="flex justify-end gap-4 pt-4 border-t border-slate-800">
                <button type="button" onclick="closeModal()" class="px-4 py-2 bg-slate-950 border border-red-500/40 hover:border-red-500/70 hover:bg-red-500/10 text-red-400 text-xs font-semibold rounded-lg transition-colors">Cancelar</button>
                <button type="submit" class="px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white text-xs font-semibold rounded-lg transition-colors">Guardar</button>
            </div>
        </form>
    </div>
</div>

<script>
var APP_URL = '<?php echo APP_URL; ?>';

// Tabs del modal (Datos / Branding)
$(document).on('click', '.tab-marca', function() {
    var tab = $(this).data('tab-marca');
    $('.tab-marca').removeClass('bg-blue-600 text-white').addClass('text-slate-400');
    $(this).addClass('bg-blue-600 text-white').removeClass('text-slate-400');
    $('.panel-marca').addClass('hidden');
    $('.panel-marca[data-panel-marca="' + tab + '"]').removeClass('hidden');
});

function llenarBrandingMarca(data) {
    var b = {};
    try { b = data && data.branding_json ? JSON.parse(data.branding_json) : {}; } catch (e) { b = {}; }
    document.getElementById('fColorPrimario').value  = b.color_primario || '#1c2430';
    document.getElementById('fColorSecundario').value = b.color_secundario || '#334155';
    document.getElementById('fLogoRuta').value        = b.logo_ruta || '';
    document.getElementById('fEslogan').value         = b.eslogan || '';
    document.getElementById('fTelefonoContacto').value = b.telefono_contacto || '';
    document.getElementById('fCiudadFirma').value     = b.ciudad_firma || '';
    document.getElementById('fTransTitular').value    = b.transferencia_titular || '';
    document.getElementById('fTransRut').value        = b.transferencia_rut || '';
    document.getElementById('fTransBanco').value      = b.transferencia_banco || '';
    document.getElementById('fTransTipo').value       = b.transferencia_tipo_cuenta || '';
    document.getElementById('fTransNumero').value     = b.transferencia_numero_cuenta || '';
    document.getElementById('fTransCorreo').value     = b.transferencia_correo || '';

    var diseno = (data && data.diseno_documento) ? data.diseno_documento : 'ejecutivo';
    var radio = document.querySelector('input[name="diseno_documento"][value="' + diseno + '"]');
    if (radio) radio.checked = true;

    // Condiciones JSON → "Titulo | texto" por línea
    var lineas = [];
    try {
        var conds = data && data.condiciones_json ? JSON.parse(data.condiciones_json) : [];
        (conds || []).forEach(function(c) { lineas.push((c.titulo || '') + (c.texto ? ' | ' + c.texto : '')); });
    } catch (e) {}
    document.getElementById('fCondiciones').value = lineas.join('\n');
}

function openModal(data) {
    if (data) {
        document.getElementById('modalTitle').textContent = 'Editar Marca';
        document.getElementById('fId').value = data.id;
        document.getElementById('fVerticalId').value = data.vertical_id;
        document.getElementById('fNombre').value = data.nombre;
        document.getElementById('fContactoNombre').value = data.contacto_nombre || '';
        document.getElementById('fContactoEmail').value = data.contacto_email || '';
        document.getElementById('fContactoTelefono').value = data.contacto_telefono || '';
        llenarBrandingMarca(data);
    } else {
        document.getElementById('modalTitle').textContent = 'Nueva Marca';
        document.getElementById('modalForm').reset();
        document.getElementById('fId').value = '';
        llenarBrandingMarca(null);
    }
    document.getElementById('modalOverlay').classList.remove('hidden');
    lucide.createIcons();
}

// Vista previa del documento con el branding y diseño del formulario (sin guardar)
function previsualizarMarca() {
    var $form = $('<form>', { method: 'POST', action: APP_URL + '/cotizaciones/previsualizar-producto', target: '_blank' });
    var datos = $('#modalForm').serializeArray();
    datos.forEach(function(campo) {
        $form.append($('<input>', { type: 'hidden', name: campo.name, value: campo.value }));
    });
    $form.appendTo('body').submit().remove();
}

function closeModal() {
    document.getElementById('modalOverlay').classList.add('hidden');
}

document.getElementById('modalForm').addEventListener('submit', function(e) {
    e.preventDefault();
    var id  = document.getElementById('fId').value;
    var url = id ? APP_URL + '/marcas/editar' : APP_URL + '/marcas/crear';
    $.ajax({
        url: url, type: 'POST', data: $(this).serialize(), dataType: 'json',
        success: function(r) {
            if (r.success) {
                Swal.fire({ icon: 'success', title: 'Listo', text: r.message, background: '#1e293b', color: '#f8fafc', confirmButtonColor: '#3b82f6', timer: 1400, showConfirmButton: false })
                    .then(function() { location.reload(); });
            } else {
                Swal.fire({ icon: 'error', title: 'Error', text: r.message, background: '#1e293b', color: '#f8fafc', confirmButtonColor: '#ef4444' });
            }
        }
    });
});

function toggleEstado(id, nuevoEstado) {
    var msg = nuevoEstado === 0 ? 'desactivar esta marca' : 'activar esta marca';
    Swal.fire({
        title: 'Confirmar', text: '¿Deseas ' + msg + '?', icon: 'question',
        showCancelButton: true, confirmButtonText: 'Si, continuar', cancelButtonText: 'Cancelar',
        background: '#1e293b', color: '#f8fafc', confirmButtonColor: '#3b82f6'
    }).then(function(result) {
        if (result.isConfirmed) {
            $.post(APP_URL + '/marcas/toggle', { id: id }, function(r) {
                if (r.success) { location.reload(); }
                else { Swal.fire({ icon: 'error', title: 'Error', text: r.message, background: '#1e293b', color: '#f8fafc' }); }
            }, 'json');
        }
    });
}
</script>
