<?php
/**
 * Pyrk safe manageable footer.
 * This file must never break the website. All database/auth errors are caught.
 */

if (!function_exists('pyrk_footer_defaults')) {
    function pyrk_footer_defaults(): array
    {
        return [
            'footer_enabled' => '1',
            'footer_logo_text' => 'PY',
            'footer_brand_name' => 'Pyrk Walking Club',
            'footer_tagline' => 'Walk together. Grow stronger. Celebrate the journey.',
            'footer_description' => 'Pyrk Walking Club brings the community together through organized walks, safe routes, checkpoints, photo contests, loyalty points, and badges.',
            'footer_address' => 'Beirut, Lebanon',
            'footer_phone' => '',
            'footer_email' => '',
            'footer_whatsapp_url' => '',
            'footer_instagram_url' => '',
            'footer_facebook_url' => '',
            'footer_copyright' => '© {year} Pyrk Walking Club. All rights reserved.',
            'footer_show_quick_links' => '1',
            'footer_show_contact' => '1',
            'footer_show_social' => '1',
            'footer_accent_note' => 'Safety, community, wellness, and memories from every walk.',
        ];
    }
}

if (!function_exists('pyrk_footer_settings')) {
    function pyrk_footer_settings(): array
    {
        static $cached = null;
        if (is_array($cached)) {
            return $cached;
        }

        $settings = pyrk_footer_defaults();

        try {
            if (class_exists('App\\Core\\Database')) {
                $pdo = \App\Core\Database::connection();
                $keys = array_keys($settings);
                $placeholders = implode(',', array_fill(0, count($keys), '?'));
                $stmt = $pdo->prepare("SELECT setting_key, setting_value FROM app_settings WHERE setting_key IN ($placeholders)");
                $stmt->execute($keys);
                foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
                    if (isset($settings[$row['setting_key']])) {
                        $settings[$row['setting_key']] = (string)$row['setting_value'];
                    }
                }
            }
        } catch (Throwable $e) {
            // Important: footer must never create a white page.
            // If table/database is missing, keep defaults.
        }

        $cached = $settings;
        return $settings;
    }
}

if (!function_exists('pyrk_footer_href_base')) {
    function pyrk_footer_href_base(string $section): string
    {
        return $section === 'admin' ? '../' : '';
    }
}

if (!function_exists('pyrk_safe_url')) {
    function pyrk_safe_url(string $url): string
    {
        $url = trim($url);
        return preg_match('~^https?://~i', $url) ? $url : '';
    }
}

if (!function_exists('pyrk_footer_current_role')) {
    function pyrk_footer_current_role(): string
    {
        try {
            if (class_exists('App\\Core\\Auth')) {
                $user = \App\Core\Auth::user();
                return (string)($user['role_name'] ?? 'guest');
            }
        } catch (Throwable $e) {
            // Never allow auth/session issues to break the footer.
        }
        return 'guest';
    }
}

if (!function_exists('pyrk_footer_html')) {
    function pyrk_footer_html(string $section = 'client'): string
    {
        try {
            $settings = pyrk_footer_settings();
            if (($settings['footer_enabled'] ?? '1') !== '1') {
                return '';
            }

            $safe = static function ($value): string {
                return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
            };

            $base = pyrk_footer_href_base($section);
            $year = date('Y');
            $copyright = str_replace('{year}', $year, $settings['footer_copyright'] ?? '© {year} Pyrk Walking Club. All rights reserved.');
            $role = pyrk_footer_current_role();
            $canManage = in_array($role, ['super_admin', 'event_manager'], true);

            $instagram = pyrk_safe_url($settings['footer_instagram_url'] ?? '');
            $facebook = pyrk_safe_url($settings['footer_facebook_url'] ?? '');
            $whatsapp = pyrk_safe_url($settings['footer_whatsapp_url'] ?? '');

            $html = '<footer class="pyrk-footer" aria-label="Site footer">';
            $html .= '<div class="pyrk-footer-shell">';

            $html .= '<section class="pyrk-footer-brand">';
            $html .= '<div class="pyrk-footer-logo-row">';
            $html .= '<span class="pyrk-footer-logo">' . $safe($settings['footer_logo_text'] ?: 'PY') . '</span>';
            $html .= '<div><strong>' . $safe($settings['footer_brand_name'] ?: 'Pyrk Walking Club') . '</strong>';
            $html .= '<small>' . $safe($settings['footer_tagline'] ?: 'Walk together. Grow stronger.') . '</small></div>';
            $html .= '</div>';
            $html .= '<p>' . $safe($settings['footer_description'] ?? '') . '</p>';
            if (!empty($settings['footer_accent_note'])) {
                $html .= '<div class="pyrk-footer-note">' . $safe($settings['footer_accent_note']) . '</div>';
            }
            $html .= '</section>';

            if (($settings['footer_show_quick_links'] ?? '1') === '1') {
                $html .= '<section class="pyrk-footer-col"><h3>Quick links</h3>';
                $html .= '<a href="' . $safe($base . 'index.php') . '">Client dashboard</a>';
                $html .= '<a href="' . $safe($base . 'my_qr.php') . '">My QR code</a>';
                $html .= '<a href="' . $safe($base . 'index.php#walks') . '">Upcoming walks</a>';
                if (in_array($role, ['super_admin', 'event_manager', 'walk_leader'], true)) {
                    $html .= '<a href="' . $safe($section === 'admin' ? 'dashboard.php' : 'admin/dashboard.php') . '">Admin portal</a>';
                }
                $html .= '</section>';
            }

            if (($settings['footer_show_contact'] ?? '1') === '1') {
                $html .= '<section class="pyrk-footer-col"><h3>Contact</h3>';
                if (!empty($settings['footer_address'])) {
                    $html .= '<span>' . $safe($settings['footer_address']) . '</span>';
                }
                if (!empty($settings['footer_phone'])) {
                    $phoneHref = preg_replace('/[^0-9+]/', '', (string)$settings['footer_phone']);
                    $html .= '<a href="tel:' . $safe($phoneHref) . '">' . $safe($settings['footer_phone']) . '</a>';
                }
                if (!empty($settings['footer_email'])) {
                    $html .= '<a href="mailto:' . $safe($settings['footer_email']) . '">' . $safe($settings['footer_email']) . '</a>';
                }
                if ($canManage) {
                    $html .= '<a class="pyrk-footer-manage" href="' . $safe($section === 'admin' ? 'footer.php' : 'admin/footer.php') . '">Manage footer</a>';
                }
                $html .= '</section>';
            }

            if (($settings['footer_show_social'] ?? '1') === '1') {
                $html .= '<section class="pyrk-footer-col"><h3>Social</h3><div class="pyrk-footer-socials">';
                if ($instagram) {
                    $html .= '<a href="' . $safe($instagram) . '" target="_blank" rel="noopener">Instagram</a>';
                }
                if ($facebook) {
                    $html .= '<a href="' . $safe($facebook) . '" target="_blank" rel="noopener">Facebook</a>';
                }
                if ($whatsapp) {
                    $html .= '<a href="' . $safe($whatsapp) . '" target="_blank" rel="noopener">WhatsApp</a>';
                }
                if (!$instagram && !$facebook && !$whatsapp) {
                    $html .= '<span>Add social links from Admin → Footer.</span>';
                }
                $html .= '</div></section>';
            }

            $html .= '</div>';
            $html .= '<div class="pyrk-footer-bottom"><span>' . $safe($copyright) . '</span><span>Built for safe walks, check-ins, loyalty, and community memories.</span><span class="pyrk-live-clock pyrk-footer-clock" data-pyrk-live-clock data-pyrk-server-epoch="' . time() . '" data-pyrk-timezone="Asia/Beirut"><span>Lebanon time</span><strong>--:--:--</strong><small>Asia/Beirut</small></span></div>';
            $html .= '</footer>';

            return $html;
        } catch (Throwable $e) {
            // Absolute failsafe: no footer is better than a white page.
            return '';
        }
    }
}

if (!function_exists('pyrk_render_footer')) {
    function pyrk_render_footer(string $section = 'client'): void
    {
        echo pyrk_footer_html($section);
    }
}

if (!function_exists('pyrk_capture_footer')) {
    function pyrk_capture_footer(string $section = 'client'): string
    {
        return pyrk_footer_html($section);
    }
}
