<?php
/**
 * Footer Component - MontaLoja Modern Template
 * Requer variáveis: $store, $storeName, $whatsapp, $address, $city, $logoType, $logoImage, $logoText
 */

$logoType = $logoType ?? 'text';
$logoImage = $logoImage ?? ($logo ?? '');
$logoText = $logoText ?? ($storeName ?? 'Loja');
$storeSlug = $store['slug'] ?? '';
$whatsapp = $whatsapp ?? '';
$address = $address ?? '';
$city = $city ?? '';

// Buscar redes sociais
$customSettings = !empty($store['template_settings']) ? json_decode($store['template_settings'], true) : [];
$socialLinks = $customSettings['social_links'] ?? [];

// Sanitize and format social links
$instagramUrl = trim($socialLinks['instagram'] ?? '');
if ($instagramUrl && strpos($instagramUrl, 'http') !== 0) {
    $instagramUrl = 'https://www.instagram.com/' . ltrim($instagramUrl, '@');
}

$facebookUrl = trim($socialLinks['facebook'] ?? '');
if ($facebookUrl && strpos($facebookUrl, 'http') !== 0) {
    // Facebook pages might not have @, but usually work with /username
    $facebookUrl = 'https://www.facebook.com/' . ltrim($facebookUrl, '@');
}

$tiktokUrl = trim($socialLinks['tiktok'] ?? '');
if ($tiktokUrl && strpos($tiktokUrl, 'http') !== 0) {
    $tiktokUrl = 'https://www.tiktok.com/@' . ltrim($tiktokUrl, '@');
} elseif ($tiktokUrl && strpos($tiktokUrl, 'tiktok.com/') !== false && strpos($tiktokUrl, '@') === false) {
    $tiktokUrl = str_replace('tiktok.com/', 'tiktok.com/@', $tiktokUrl);
}

// Priority: Social Link WhatsApp > Store WhatsApp
if (!empty($socialLinks['whatsapp'])) {
    $whatsapp = $socialLinks['whatsapp'];
}
?>

<!-- FOOTER -->
<footer class="site-footer">
    <div class="footer-inner">
        <div class="footer-grid">
            <div class="footer-brand">
                <a href="<?php echo htmlspecialchars($baseUrl ?? storeUrl()); ?>" class="brand">
                    <?php if ($logoType === 'image' || $logoType === 'both'): ?>
                        <?php if (!empty($logoImage)): ?>
                        <div class="brand-logo has-image">
                            <img src="<?php echo htmlspecialchars($logoImage); ?>" alt="<?php echo htmlspecialchars($logoText); ?>">
                        </div>
                        <?php else: ?>
                        <div class="brand-logo">
                            <?php echo strtoupper(substr($logoText, 0, 1)); ?>
                        </div>
                        <?php endif; ?>
                    <?php endif; ?>
                    <?php if ($logoType === 'text'): ?>
                    <div class="brand-logo">
                        <?php echo strtoupper(substr($logoText, 0, 1)); ?>
                    </div>
                    <?php endif; ?>
                    <?php if ($logoType === 'text' || $logoType === 'both'): ?>
                        <span class="brand-name"><?php echo htmlspecialchars($logoText); ?></span>
                    <?php endif; ?>
                </a>
                <p>Sua loja online de confiança. Produtos de qualidade com os melhores preços e entrega rápida para todo o Brasil.</p>
            </div>
            <div>
                <h4 class="footer-title">Links</h4>
                <ul class="footer-links">
                    <li><a href="<?php echo htmlspecialchars($baseUrl ?? storeUrl()); ?>">Início</a></li>
                    <li><a href="<?php echo htmlspecialchars($baseUrl ?? storeUrl()); ?>/produtos">Produtos</a></li>
                    <li><a href="#">Ofertas</a></li>
                    <li><a href="#">Sobre nós</a></li>
                </ul>
            </div>
            <div>
                <h4 class="footer-title">Ajuda</h4>
                <ul class="footer-links">
                    <li><a href="#">FAQ</a></li>
                    <li><a href="#">Entregas</a></li>
                    <li><a href="#">Trocas</a></li>
                    <li><a href="#">Contato</a></li>
                </ul>
            </div>
            <div>
                <h4 class="footer-title">Contato</h4>
                <ul class="footer-links">
                    <?php if ($whatsapp): ?>
                    <li><a href="https://wa.me/55<?php echo preg_replace('/\D/', '', $whatsapp); ?>"><?php echo htmlspecialchars($whatsapp); ?></a></li>
                    <?php endif; ?>
                    <?php if ($address || $city): ?>
                    <li><a href="#"><?php echo htmlspecialchars(trim($address . ($city ? ', ' . $city : ''))); ?></a></li>
                    <?php endif; ?>
                </ul>
            </div>
        </div>
        <div class="footer-bottom">
            <span>&copy; <?php echo date('Y'); ?> <?php echo htmlspecialchars($storeName ?? 'Loja'); ?>. Todos os direitos reservados.</span>
            <div class="footer-social">
                <?php if (!empty($instagramUrl)): ?>
                <a href="<?php echo htmlspecialchars($instagramUrl); ?>" title="Instagram" target="_blank" rel="noopener"><iconify-icon icon="mdi:instagram" style="font-size: 1.2rem;"></iconify-icon></a>
                <?php endif; ?>

                <?php if (!empty($facebookUrl)): ?>
                <a href="<?php echo htmlspecialchars($facebookUrl); ?>" title="Facebook" target="_blank" rel="noopener"><iconify-icon icon="mdi:facebook" style="font-size: 1.2rem;"></iconify-icon></a>
                <?php endif; ?>
                
                <?php if (!empty($tiktokUrl)): ?>
                <a href="<?php echo htmlspecialchars($tiktokUrl); ?>" title="TikTok" target="_blank" rel="noopener"><iconify-icon icon="ic:baseline-tiktok" style="font-size: 1.2rem;"></iconify-icon></a>
                <?php endif; ?>

                <?php if ($whatsapp): ?>
                <a href="https://wa.me/55<?php echo preg_replace('/\D/', '', $whatsapp); ?>" title="WhatsApp" target="_blank" rel="noopener"><iconify-icon icon="mdi:whatsapp" style="font-size: 1.2rem;"></iconify-icon></a>
                <?php endif; ?>
            </div>
        </div>
    </div>
</footer>

<?php
// Tracking de visitantes
$storeIdForTracking = $store['id'] ?? ($storeId ?? null);
if (!empty($storeIdForTracking) && isset($pdo)) {
    try {
        $visitorIp = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
        $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        
        // Verificar se já registrou visita nas últimas 4 horas
        $checkStmt = $pdo->prepare("SELECT id FROM store_visitors WHERE store_id = ? AND visitor_ip = ? AND visited_at > DATE_SUB(NOW(), INTERVAL 4 HOUR)");
        $checkStmt->execute([$storeIdForTracking, $visitorIp]);
        
        if (!$checkStmt->fetch()) {
            // Registrar nova visita
            $insertStmt = $pdo->prepare("INSERT INTO store_visitors (store_id, visitor_ip, user_agent) VALUES (?, ?, ?)");
            $insertStmt->execute([$storeIdForTracking, $visitorIp, $userAgent]);
        }
    } catch (Exception $e) {
        // Silenciar erros de tracking
    }
}
?>
