<?php
/**
 * Header compartido para todas las páginas
 */

// Obtener configuración dinámica del sistema
$company_name = APP_NAME; // Valor por defecto
$company_logo = '';

try {
    if (isset($pdo)) {
        $stmt = $pdo->prepare("SELECT config_key, config_value FROM system_config WHERE config_key IN ('company_name', 'company_logo')");
        $stmt->execute();
        $config_items = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        foreach ($config_items as $item) {
            if ($item['config_key'] === 'company_name' && !empty($item['config_value'])) {
                $company_name = $item['config_value'];
            } elseif ($item['config_key'] === 'company_logo' && !empty($item['config_value'])) {
                $company_logo = $item['config_value'];
            }
        }
    }
} catch (Exception $e) {
    // En caso de error, usar valores por defecto
    $company_name = APP_NAME;
    $company_logo = '';
}
?>

<header class="header">
    <div class="header-content">
        <button class="mobile-menu-toggle" aria-label="Abrir menú" aria-controls="sidebar" aria-expanded="false"><span class="sr-only">Menú</span><i class="fas fa-bars"></i></button>
        <div class="logo">
            <a href="<?php echo route_url(['module'=>'dashboard']); ?>" style="color: white; text-decoration: none; display: flex; align-items: center; gap: 0.5rem;">
                <?php if (!empty($company_logo)): ?>
                    <img src="<?php echo htmlspecialchars($company_logo); ?>" alt="Logo" style="height: 32px; max-width: 120px; object-fit: contain;">
                <?php endif; ?>
                <?php
                    $logo_src = '';
                    if (!empty($company_logo)) {
                        if (preg_match('/^https?:\/\//', $company_logo) || str_starts_with($company_logo, '/')) {
                            $logo_src = $company_logo;
                        } else {
                            $logo_src = asset('public/uploads/' . $company_logo);
                        }
                    } else {
                        $logo_src = asset('public/branding/profix_logo.svg');
                    }
                ?>
                <img src="<?php echo htmlspecialchars($logo_src); ?>" alt="Logo" style="height: 32px; max-width: 160px; object-fit: contain;">
                <span><?php echo htmlspecialchars($company_name); ?></span>
            </a>
        </div>
        
        <div class="user-info">
            <div class="user-avatar">
                <div class="avatar-circle"><?php echo strtoupper(substr($_SESSION['user_name'] ?? 'U', 0, 1)); ?></div>
            </div>
            <span>Hola, <?php echo htmlspecialchars($_SESSION['user_name'] ?? 'Usuario'); ?></span>
            <a href="<?php echo route_url(['module'=>'auth','action'=>'logout']); ?>" class="btn btn-small">Salir</a>
        </div>
    </div>
</header>
