<?php
/**
 * SEO Helper Class
 * Auto-generates meta tags, Open Graph, Schema markup for all pages
 */

class SEO {
    private static $instance = null;
    private $settings = [];
    private $pageData = null;
    private $keywords = [];
    
    private function __construct() {
        $this->loadSettings();
        $this->loadPageSEO();
    }
    
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function loadSettings() {
        try {
            $data = dbFetchAll("SELECT setting_key, setting_value FROM seo_settings");
            foreach ($data as $row) {
                $key = str_replace('seo_', '', $row['setting_key']);
                $this->settings[$key] = $row['setting_value'];
            }
        } catch (Exception $e) {
            // Tables might not exist yet
        }
    }
    
    private function loadPageSEO() {
        $currentUrl = $_SERVER['REQUEST_URI'] ?? '/';
        $currentUrl = strtok($currentUrl, '?'); // Remove query string
        
        try {
            $this->pageData = dbFetch(
                "SELECT * FROM seo_pages WHERE page_url = :url AND status = 'active'",
                ['url' => $currentUrl]
            );
        } catch (Exception $e) {
            // Table might not exist
        }
    }
    
    /**
     * Get page title
     */
    public function getTitle($default = '') {
        if ($this->pageData && !empty($this->pageData['page_title'])) {
            return htmlspecialchars($this->pageData['page_title']);
        }
        
        $siteTitle = $this->settings['site_title'] ?? 'BinaryTrade Pro';
        
        if ($default) {
            return htmlspecialchars($default) . ' | ' . htmlspecialchars($siteTitle);
        }
        
        return htmlspecialchars($siteTitle);
    }
    
    /**
     * Get meta description
     */
    public function getDescription() {
        if ($this->pageData && !empty($this->pageData['meta_description'])) {
            return htmlspecialchars($this->pageData['meta_description']);
        }
        return htmlspecialchars($this->settings['meta_description'] ?? '');
    }
    
    /**
     * Get meta keywords
     */
    public function getKeywords() {
        if ($this->pageData && !empty($this->pageData['meta_keywords'])) {
            return htmlspecialchars($this->pageData['meta_keywords']);
        }
        return htmlspecialchars($this->settings['meta_keywords'] ?? '');
    }
    
    /**
     * Generate all meta tags
     */
    public function renderMetaTags($pageTitle = '') {
        $title = $this->getTitle($pageTitle);
        $description = $this->getDescription();
        $keywords = $this->getKeywords();
        $ogImage = $this->pageData['og_image'] ?? $this->settings['og_image'] ?? '';
        $canonical = $this->pageData['canonical_url'] ?? '';
        $robots = $this->pageData['robots'] ?? 'index,follow';
        
        $currentUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        
        $html = '';
        
        // Basic Meta Tags
        $html .= "<title>{$title}</title>\n";
        $html .= "<meta name=\"description\" content=\"{$description}\">\n";
        if ($keywords) {
            $html .= "<meta name=\"keywords\" content=\"{$keywords}\">\n";
        }
        $html .= "<meta name=\"robots\" content=\"{$robots}\">\n";
        
        // Canonical URL
        if ($canonical) {
            $html .= "<link rel=\"canonical\" href=\"{$canonical}\">\n";
        }
        
        // Open Graph Tags
        $ogTitle = $this->pageData['og_title'] ?? $title;
        $ogDesc = $this->pageData['og_description'] ?? $description;
        
        $html .= "<meta property=\"og:type\" content=\"website\">\n";
        $html .= "<meta property=\"og:title\" content=\"{$ogTitle}\">\n";
        $html .= "<meta property=\"og:description\" content=\"{$ogDesc}\">\n";
        $html .= "<meta property=\"og:url\" content=\"{$currentUrl}\">\n";
        if ($ogImage) {
            $html .= "<meta property=\"og:image\" content=\"{$ogImage}\">\n";
        }
        
        // Twitter Card Tags
        $html .= "<meta name=\"twitter:card\" content=\"summary_large_image\">\n";
        $html .= "<meta name=\"twitter:title\" content=\"{$ogTitle}\">\n";
        $html .= "<meta name=\"twitter:description\" content=\"{$ogDesc}\">\n";
        if ($ogImage) {
            $html .= "<meta name=\"twitter:image\" content=\"{$ogImage}\">\n";
        }
        if (!empty($this->settings['twitter_handle'])) {
            $html .= "<meta name=\"twitter:site\" content=\"{$this->settings['twitter_handle']}\">\n";
        }
        
        // Google Search Console Verification
        if (!empty($this->settings['google_search_console'])) {
            $html .= "<meta name=\"google-site-verification\" content=\"{$this->settings['google_search_console']}\">\n";
        }
        
        // Bing Webmaster Verification
        if (!empty($this->settings['bing_webmaster'])) {
            $html .= "<meta name=\"msvalidate.01\" content=\"{$this->settings['bing_webmaster']}\">\n";
        }
        
        return $html;
    }
    
    /**
     * Render Schema.org JSON-LD markup
     */
    public function renderSchema() {
        // Custom schema for page
        if ($this->pageData && !empty($this->pageData['schema_markup'])) {
            return "<script type=\"application/ld+json\">\n" . $this->pageData['schema_markup'] . "\n</script>\n";
        }
        
        // Default Organization schema
        $schema = [
            "@context" => "https://schema.org",
            "@type" => $this->settings['schema_type'] ?? "Organization",
            "name" => $this->settings['site_title'] ?? "BinaryTrade Pro",
            "description" => $this->settings['meta_description'] ?? "",
            "url" => SITE_URL ?? "http://localhost",
        ];
        
        if (!empty($this->settings['og_image'])) {
            $schema["logo"] = $this->settings['og_image'];
        }
        
        return "<script type=\"application/ld+json\">\n" . json_encode($schema, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n</script>\n";
    }
    
    /**
     * Render Google Analytics code
     */
    public function renderAnalytics() {
        $html = '';
        
        // Google Analytics
        if (!empty($this->settings['google_analytics'])) {
            $gaId = $this->settings['google_analytics'];
            
            if (strpos($gaId, 'G-') === 0) {
                // GA4
                $html .= "<!-- Google Analytics 4 -->\n";
                $html .= "<script async src=\"https://www.googletagmanager.com/gtag/js?id={$gaId}\"></script>\n";
                $html .= "<script>\nwindow.dataLayer = window.dataLayer || [];\nfunction gtag(){dataLayer.push(arguments);}\ngtag('js', new Date());\ngtag('config', '{$gaId}');\n</script>\n";
            } else {
                // Universal Analytics
                $html .= "<!-- Google Analytics -->\n";
                $html .= "<script async src=\"https://www.google-analytics.com/analytics.js\"></script>\n";
                $html .= "<script>\nwindow.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;\nga('create', '{$gaId}', 'auto');\nga('send', 'pageview');\n</script>\n";
            }
        }
        
        // Facebook Pixel
        if (!empty($this->settings['facebook_pixel'])) {
            $pixelId = $this->settings['facebook_pixel'];
            $html .= "<!-- Facebook Pixel -->\n";
            $html .= "<script>!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','https://connect.facebook.net/en_US/fbevents.js');fbq('init','{$pixelId}');fbq('track','PageView');</script>\n";
        }
        
        return $html;
    }
    
    /**
     * Get H1 tag for page
     */
    public function getH1($default = '') {
        if ($this->pageData && !empty($this->pageData['h1_tag'])) {
            return htmlspecialchars($this->pageData['h1_tag']);
        }
        return htmlspecialchars($default);
    }
    
    /**
     * Get focus keyword for page
     */
    public function getFocusKeyword() {
        return $this->pageData['focus_keyword'] ?? '';
    }
    
    /**
     * Get setting value
     */
    public function getSetting($key, $default = '') {
        return $this->settings[$key] ?? $default;
    }
}

/**
 * Helper function to get SEO instance
 */
function seo() {
    return SEO::getInstance();
}

/**
 * Handle URL redirects
 */
function handleSEORedirects() {
    $currentUrl = $_SERVER['REQUEST_URI'] ?? '/';
    $currentUrl = strtok($currentUrl, '?');
    
    try {
        $redirect = dbFetch(
            "SELECT * FROM seo_redirects WHERE from_url = :url AND status = 'active'",
            ['url' => $currentUrl]
        );
        
        if ($redirect) {
            // Update hit count
            dbQuery("UPDATE seo_redirects SET hits = hits + 1 WHERE id = :id", ['id' => $redirect['id']]);
            
            // Perform redirect
            $code = (int)$redirect['redirect_type'];
            http_response_code($code);
            header("Location: " . $redirect['to_url'], true, $code);
            exit;
        }
    } catch (Exception $e) {
        // Table might not exist
    }
}
