<?php
/**
 * Template de Páginas Personalizadas - MontaLoja Modern Template
 * Usa os mesmos header e footer das outras páginas
 */

// Verificar se foi chamado corretamente
if (!defined('BARBERFLOW')) {
    die('Acesso negado');
}

// Variáveis esperadas: $store, $pdo, $currentStoreId, $storeName, $logo

// Buscar slug da página
$pageSlug = $_GET['slug'] ?? '';

if (empty($pageSlug)) {
    // Redirecionar para home se não houver slug
    header('Location: ' . ($baseUrl ?? '/'));
    exit;
}

// Buscar página do banco de dados
try {
    $pageStmt = $pdo->prepare("SELECT * FROM store_pages WHERE store_id = ? AND slug = ? AND is_active = 1");
    $pageStmt->execute([$currentStoreId, $pageSlug]);
    $page = $pageStmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$page) {
        // Página não encontrada
        http_response_code(404);
        $page = [
            'title' => 'Página não encontrada',
            'content' => '<p>A página que você procura não existe ou foi removida.</p>',
            'meta_description' => ''
        ];
    }
} catch (PDOException $e) {
    http_response_code(500);
    $page = [
        'title' => 'Erro',
        'content' => '<p>Ocorreu um erro ao carregar a página.</p>',
        'meta_description' => ''
    ];
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo htmlspecialchars($page['title']); ?> - <?php echo htmlspecialchars($storeName); ?></title>
<meta name="description" content="<?php echo htmlspecialchars($page['meta_description'] ?? ''); ?>">
<meta name="theme-color" content="#ffffff">
<?php if (!empty($faviconUrl)): ?>
<link rel="icon" type="image/png" href="<?php echo htmlspecialchars($faviconUrl); ?>?v=<?php echo time(); ?>">
<link rel="shortcut icon" type="image/png" href="<?php echo htmlspecialchars($faviconUrl); ?>?v=<?php echo time(); ?>">
<link rel="apple-touch-icon" href="<?php echo htmlspecialchars($faviconUrl); ?>">
<?php endif; ?>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/iconify-icon@1.0.7/dist/iconify-icon.min.js"></script>
<link rel="stylesheet" href="/pages/storefront/templates/retail/modern/includes/styles.css?v=1.0.4">
<?php include __DIR__ . "/includes/dynamic-styles.php"; ?>
<!-- Dynamic Theme Colors -->
<?php
// Detectar se é tema escuro baseado na cor de fundo
$bgHex = $bgColor ?? '#FAFBFC';
$bgR = hexdec(substr($bgHex, 1, 2));
$bgG = hexdec(substr($bgHex, 3, 2));
$bgB = hexdec(substr($bgHex, 5, 2));
$bgLuminance = ($bgR * 0.299 + $bgG * 0.587 + $bgB * 0.114);
$isDarkTheme = $bgLuminance < 128;

// Variáveis calculadas para tema claro/escuro
if ($isDarkTheme) {
    $borderColor = 'rgba(255,255,255,0.12)';
    $borderLight = 'rgba(255,255,255,0.08)';
    $mutedColor = '#808080';
    $shadowSm = '0 1px 2px rgba(0,0,0,0.3)';
    $shadowMd = '0 4px 12px rgba(0,0,0,0.4)';
    $shadowLg = '0 12px 40px rgba(0,0,0,0.5)';
    $surfaceHover = 'rgba(255,255,255,0.05)';
} else {
    $borderColor = '#E5E7EB';
    $borderLight = '#F3F4F6';
    $mutedColor = '#9CA3AF';
    $shadowSm = '0 1px 2px rgba(0,0,0,0.04)';
    $shadowMd = '0 4px 12px rgba(0,0,0,0.05)';
    $shadowLg = '0 12px 40px rgba(0,0,0,0.08)';
    $surfaceHover = '#F8F9FA';
}
?>
</head>
<body>

<?php
    // Configurações do cabeçalho
    $headerSettings = $headerSettings ?? [
        'logo_type' => 'text',
        'logo_text' => $storeName,
        'logo_image' => $logo,
        'show_search' => true,
        'show_cart' => true,
        'show_wishlist' => true,
        'sticky' => true
    ];
    $stickyClass = ($headerSettings['sticky'] ?? true) ? ' sticky-header' : '';

    // Variáveis para o header.php
    $logoType = $headerSettings['logo_type'] ?? 'text';
    $logoImage = $headerSettings['logo_image'] ?? $logo;
    $logoText = $headerSettings['logo_text'] ?? $storeName;
    $storeSlug = $store['slug'] ?? '';

    // Detectar URL base dinamicamente - sem domínio hardcoded
    $currentHost = $_SERVER['HTTP_HOST'] ?? '';
    $isLojaPathAccess = strpos($_SERVER['REQUEST_URI'] ?? '', '/loja/') !== false;

    // Montar URL base da loja baseado em COMO o usuário está acessando
    if (!isset($baseUrl) || empty($baseUrl)) {
        if (function_exists('get_store_url') && !empty($store)) {
            $baseUrl = get_store_url($store);
        } elseif ($isLojaPathAccess) {
            $baseUrl = '/loja/' . ($store['slug'] ?? '');
        } else {
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
            $baseUrl = $protocol . $currentHost;
        }
    }

    // Menu dinâmico - Itens fixos SEMPRE aparecem primeiro
    // Itens fixos que SEMPRE aparecem (Início e Produtos)
    $fixedMenuItems = [
        ['id' => 1, 'name' => 'Início', 'link' => $baseUrl, 'icon' => 'solar:home-2-bold'],
        ['id' => 2, 'name' => 'Produtos', 'link' => $baseUrl . '/produtos', 'icon' => 'solar:bag-3-bold'],
    ];

    // Itens customizáveis - filtrar Início e Produtos
    $savedMenuItems = $customSettings['menu'] ?? [];
    $customMenuItems = [];
    if (!empty($savedMenuItems)) {
        foreach ($savedMenuItems as $item) {
            $itemName = strtolower(trim($item['name'] ?? ''));
            if (!in_array($itemName, ['início', 'inicio', 'produtos', 'home', 'products'])) {
                $customMenuItems[] = $item;
            }
        }
    }
    if (empty($customMenuItems)) {
        $customMenuItems = [
            ['id' => 3, 'name' => 'Categorias', 'link' => $baseUrl . '#categorias', 'icon' => 'solar:widget-4-bold'],
            ['id' => 4, 'name' => 'Contato', 'link' => $baseUrl . '#contato', 'icon' => 'solar:phone-bold']
        ];
    }
    $menuItems = array_merge($fixedMenuItems, $customMenuItems);
    // Corrigir links relativos do menu
    foreach ($menuItems as &$item) {
        $link = $item['link'] ?? '';
        if (strpos($link, '#') === 0) {
            $item['link'] = $baseUrl . $link;
        }
    }
    unset($item);
?>

<?php include __DIR__ . '/../../../includes/cart.php'; ?>

<?php include __DIR__ . '/includes/header.php'; ?>

<!-- Page Header Banner -->
<section class="page-header-banner">
    <div class="page-header-content">
        <nav class="page-breadcrumb">
            <a href="<?php echo htmlspecialchars($baseUrl); ?>">Início</a>
            <iconify-icon icon="solar:alt-arrow-right-linear"></iconify-icon>
            <span><?php echo htmlspecialchars($page['title']); ?></span>
        </nav>
        <h1 class="page-header-title">
                    <?php echo htmlspecialchars($page['title']); ?></h1>
    </div>
</section>

<main class="page-content" style="min-height: 60vh; padding: 2rem 0;">
    <div class="container" style="max-width: 900px; margin: 0 auto; padding: 0 1.5rem;">
        <article class="page-article" style="background: var(--color-surface); border-radius: 12px; padding: 2rem; box-shadow: var(--shadow-sm);">
            
            <div class="page-body" style="color: var(--color-text); line-height: 1.8; font-size: 1rem;">
                <?php echo $page['content']; ?>
            </div>
        </article>
        
        <div style="margin-top: 2rem; text-align: center;">
            <a href="<?php echo htmlspecialchars($baseUrl); ?>" 
               style="display: inline-flex; align-items: center; gap: 0.5rem; color: var(--color-primary); text-decoration: none; font-weight: 500; padding: 0.75rem 1.5rem; border: 1px solid var(--color-primary); border-radius: 8px; transition: all 0.2s ease;">
                <iconify-icon icon="solar:arrow-left-linear"></iconify-icon>
                Voltar para a loja
            </a>
        </div>
    </div>
</main>

<style>
.page-body h1, .page-body h2, .page-body h3, .page-body h4, .page-body h5, .page-body h6 {
    margin-top: 1.5em;
    margin-bottom: 0.75em;
    font-weight: 600;
    color: var(--color-text);
}
.page-body h1 { font-size: 1.75rem; }
.page-body h2 { font-size: 1.5rem; }
.page-body h3 { font-size: 1.25rem; }
.page-body p {
    margin-bottom: 1rem;
}
.page-body ul, .page-body ol {
    margin-bottom: 1rem;
    padding-left: 1.5rem;
}
.page-body li {
    margin-bottom: 0.5rem;
}
.page-body a {
    color: var(--color-primary);
    text-decoration: underline;
}
.page-body a:hover {
    text-decoration: none;
}
.page-body img {
    max-width: 100%;
    height: auto;
    border-radius: 8px;
    margin: 1rem 0;
}
.page-body blockquote {
    border-left: 4px solid var(--color-primary);
    padding-left: 1rem;
    margin: 1rem 0;
    color: var(--color-muted);
    font-style: italic;
}
.page-body table {
    width: 100%;
    border-collapse: collapse;
    margin: 1rem 0;
}
.page-body th, .page-body td {
    border: 1px solid var(--color-border);
    padding: 0.75rem;
    text-align: left;
}
.page-body th {
    background: var(--color-surface-hover);
    font-weight: 600;
}
.page-body pre {
    background: var(--color-surface-hover);
    padding: 1rem;
    border-radius: 8px;
    overflow-x: auto;
    margin: 1rem 0;
}
.page-body code {
    background: var(--color-surface-hover);
    padding: 0.2em 0.4em;
    border-radius: 4px;
    font-size: 0.9em;
}

@media (max-width: 768px) {
    .page-content {
        padding: 1rem 0 !important;
    }
    .page-article {
        padding: 1.25rem !important;
    }
    .page-article h1 {
        font-size: 1.5rem !important;
    }
}
/* Esconder elementos de edicao de imagem */
.img-resize-wrapper { display: contents !important; }
.img-resize-handle, .img-toolbar { display: none !important; }
.page-article img { max-width: 100%; height: auto; border-radius: 8px; }
</style>

<?php include __DIR__ . '/includes/footer.php'; ?>

<!-- Toast Notification -->
<div class="toast" id="toast"></div>

<?php include __DIR__ . '/../../../includes/scripts.php'; ?>

</body>
</html>
