<div class="card-custom">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4><i class="fas fa-cogs me-2"></i>Configuración del Sistema</h4>
        <button type="submit" form="formConfig" class="btn btn-primary rounded-pill shadow-sm px-4">
            <i class="fas fa-save me-2"></i> Guardar Cambios
        </button>
    </div>

    <form method="POST" id="formConfig" enctype="multipart/form-data">
        <input type="hidden" name="action" value="save_config">
        
        <div class="row g-4">
            
            <div class="col-md-6">
                <div class="card h-100 shadow-sm border-0">
                    <div class="card-header bg-white fw-bold text-primary">
                        <i class="fas fa-building me-2"></i>Identidad Corporativa
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-7 mb-3">
                                <label class="fw-bold small">Nombre Comercial</label>
                                <input name="nombre_empresa" class="form-control fw-bold" value="<?php echo h($config['nombre_empresa'] ?? ''); ?>" required>
                            </div>
                            <div class="col-md-5 mb-3">
                                <label class="fw-bold small text-danger">RUC (*)</label>
                                <input name="ruc" class="form-control fw-bold" value="<?php echo h($config['ruc'] ?? ''); ?>" required>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="fw-bold small">Dirección Fiscal</label>
                            <input name="direccion" class="form-control" value="<?php echo h($config['direccion'] ?? ''); ?>">
                        </div>
                        <div class="row">
                            <div class="col-6 mb-3">
                                <label class="fw-bold small">Moneda</label>
                                <input name="moneda" class="form-control" value="<?php echo h($config['moneda'] ?? 'S/'); ?>">
                            </div>
                            <div class="col-6 mb-3">
                                <label class="fw-bold small">WhatsApp / Teléfono</label>
                                <input name="telefono" class="form-control" value="<?php echo h($config['telefono'] ?? ''); ?>">
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-6">
                <div class="card h-100 shadow-sm border-0 border-start border-4 border-warning">
                    <div class="card-header bg-white fw-bold text-warning d-flex justify-content-between align-items-center">
                        <span><i class="fas fa-file-invoice me-2"></i>Conexión SUNAT (API)</span>
                        <span id="status-badge" class="badge bg-secondary rounded-pill small">
                            <i class="fas fa-question-circle me-1"></i> Sin Probar
                        </span>
                    </div>
                    <div class="card-body bg-light">
                        <div class="alert alert-warning py-2 small mb-3">
                            <i class="fas fa-info-circle me-1"></i> Configura aquí las credenciales de tu PSE/OSE (Ej. Nubefact/ApisPeru).
                        </div>
                        
                        <div class="mb-3">
                            <label class="fw-bold small text-muted">Ruta API (URL)</label>
                            <div class="input-group">
                                <span class="input-group-text bg-white"><i class="fas fa-link"></i></span>
                                <input id="sunat_ruta" name="sunat_ruta" class="form-control font-monospace small" value="<?php echo h($config['sunat_ruta'] ?? ''); ?>" placeholder="https://api.pse.pe/v1/...">
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="fw-bold small text-muted">Token de Acceso</label>
                            <div class="input-group">
                                <span class="input-group-text bg-white"><i class="fas fa-key"></i></span>
                                <input id="sunat_token" name="sunat_token" class="form-control font-monospace small" value="<?php echo h($config['sunat_token'] ?? ''); ?>" placeholder="eyJhbGciOiJIUzI1Ni...">
                            </div>
                        </div>

                        <div class="d-flex justify-content-between align-items-center mt-3">
                            <small class="text-muted fst-italic">Guarda antes de probar.</small>
                            <button type="button" onclick="probarConexion()" class="btn btn-warning btn-sm fw-bold text-dark shadow-sm">
                                <i class="fas fa-plug me-2"></i> PROBAR CONEXIÓN
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-6">
                <div class="card h-100 shadow-sm border-0">
                    <div class="card-header bg-white fw-bold text-info">
                        <i class="fas fa-image me-2"></i>Logos y QR
                    </div>
                    <div class="card-body">
                        <div class="row align-items-center mb-3">
                            <div class="col-8">
                                <label class="fw-bold small">Logo Ticket</label>
                                <input type="file" name="logo" class="form-control form-control-sm">
                            </div>
                            <div class="col-4 text-center">
                                <?php if(!empty($config['logo_url'])): ?>
                                    <img src="<?php echo h($config['logo_url']); ?>" height="35" class="border p-1 rounded">
                                <?php else: ?>
                                    <span class="text-muted small">Sin logo</span>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div class="row align-items-center mb-3">
                            <div class="col-8">
                                <label class="fw-bold small">Favicon (Icono Web)</label>
                                <input type="file" name="favicon" class="form-control form-control-sm">
                            </div>
                            <div class="col-4 text-center">
                                <?php if(!empty($config['favicon_url'])): ?>
                                    <img src="<?php echo h($config['favicon_url']); ?>" height="32" class="border p-1 rounded">
                                <?php endif; ?>
                            </div>
                        </div>
                        <div class="row align-items-center">
                            <div class="col-8">
                                <label class="fw-bold small text-purple" style="color:#742284">QR Yape/Plin</label>
                                <input type="file" name="qr_yape" class="form-control form-control-sm">
                            </div>
                            <div class="col-4 text-center">
                                <?php if(!empty($config['qr_yape_url'])): ?>
                                    <img src="<?php echo h($config['qr_yape_url']); ?>" height="35" class="border p-1 rounded">
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-6">
                <div class="card h-100 shadow-sm border-0">
                    <div class="card-header bg-white fw-bold text-success">
                        <i class="fas fa-receipt me-2"></i>Formato de Ticket
                    </div>
                    <div class="card-body">
                        <div class="row mb-3">
                            <div class="col-6">
                                <label class="fw-bold small">Nombre Impuesto</label>
                                <input name="impuesto_nombre" class="form-control" value="<?php echo h($config['impuesto_nombre'] ?? 'IGV'); ?>">
                            </div>
                            <div class="col-6">
                                <label class="fw-bold small">Valor %</label>
                                <input name="impuesto_valor" class="form-control" value="<?php echo h($config['impuesto_valor'] ?? '18'); ?>">
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="fw-bold small">Mensaje Pie de Página</label>
                            <textarea name="mensaje_ticket" class="form-control" rows="3" placeholder="Ej: ¡Gracias por su compra!"><?php echo h($config['mensaje_ticket'] ?? ''); ?></textarea>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-12">
                <div class="card shadow-sm border-0 border-start border-4 border-danger">
                    <div class="card-body d-flex justify-content-between align-items-center flex-wrap gap-3">
                        <div>
                            <h6 class="fw-bold text-danger mb-0"><i class="fas fa-exclamation-triangle me-2"></i>Zona de Mantenimiento</h6>
                            <small class="text-muted">Descarga copias de seguridad o reinicia la base de datos.</small>
                        </div>
                        <div class="d-flex gap-2">
                            <a href="api.php?task=backup_db" target="_blank" class="btn btn-outline-dark btn-sm">
                                <i class="fas fa-download me-2"></i> Descargar Backup
                            </a>
                            <button type="button" class="btn btn-danger btn-sm" onclick="confirmarReset()">
                                <i class="fas fa-trash me-2"></i> Resetear Base de Datos
                            </button>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </form>
</div>

<script>
// --- FUNCIÓN DE RESETEO (CON CLAVE DE ADMIN) ---
function confirmarReset(){ 
    Swal.fire({
        title: '¿BORRAR TODO?',
        text: "Se eliminarán todas las ventas, productos, clientes y cajas. ¡No hay vuelta atrás!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Sí, borrar todo',
        cancelButtonText: 'Cancelar'
    }).then((r) => {
        if(r.isConfirmed){
            Swal.fire({
                title: 'Seguridad',
                text: 'Ingresa la contraseña de Administrador para confirmar:',
                input: 'password',
                showCancelButton: true,
                confirmButtonText: 'Confirmar Borrado',
                confirmButtonColor: '#d33',
                showLoaderOnConfirm: true,
                preConfirm: (pass) => {
                    let fd = new FormData();
                    fd.append('password_confirm', pass);
                    return fetch(`api.php?task=reset_db`, {method:'POST', body:fd})
                        .then(response => {
                            if (!response.ok) throw new Error(response.statusText);
                            return response.json();
                        })
                        .catch(error => {
                            Swal.showValidationMessage(`Error: ${error}`);
                        });
                },
                allowOutsideClick: () => !Swal.isLoading()
            }).then((result) => {
                if (result.isConfirmed && result.value.success) {
                    Swal.fire('¡Reseteado!', 'El sistema ha sido limpiado correctamente.', 'success')
                        .then(() => location.reload());
                } else if (result.isConfirmed && !result.value.success) {
                    Swal.fire('Error', 'Contraseña incorrecta', 'error');
                }
            });
        }
    });
}

// --- FUNCIÓN DE TESTEO DE CONEXIÓN SUNAT ---
function probarConexion() {
    let ruta = document.getElementById('sunat_ruta').value;
    let token = document.getElementById('sunat_token').value;
    let badge = document.getElementById('status-badge');

    if(!ruta || !token) {
        Swal.fire('Faltan datos', 'Ingresa Ruta y Token primero', 'warning');
        return;
    }

    // Cambiar estado a cargando
    badge.className = 'badge bg-primary rounded-pill small';
    badge.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Probando...';

    let fd = new FormData();
    fd.append('ruta', ruta);
    fd.append('token', token);

    // Llamada a la API interna que hace el puente
    fetch('api.php?task=test_sunat', { method: 'POST', body: fd })
    .then(r => r.json())
    .then(res => {
        if (res.success) {
            badge.className = 'badge bg-success rounded-pill small shadow';
            badge.innerHTML = '<i class="fas fa-check-circle me-1"></i> CONECTADO';
            Swal.fire({
                title: '¡Conexión Exitosa!',
                text: res.msg,
                icon: 'success',
                timer: 2000,
                showConfirmButton: false
            });
        } else {
            throw new Error(res.error || 'Error desconocido');
        }
    })
    .catch(err => {
        console.error(err);
        badge.className = 'badge bg-danger rounded-pill small shadow';
        badge.innerHTML = '<i class="fas fa-times-circle me-1"></i> ERROR';
        Swal.fire('Falló la conexión', err.message, 'error');
    });
}
</script>