<?php
class SiteSettings {
    private $db;

    public function __construct() {
        $database = new Database();
        $this->db = $database->getConnection();

        // Create settings table if it doesn't exist
        $this->createSettingsTable();
    }

    private function createSettingsTable() {
        // Check database type
        $dbType = $_ENV['DB_TYPE'] ?? 'sqlite';

        if ($dbType === 'mysql') {
            // MySQL syntax
            $sql = "CREATE TABLE IF NOT EXISTS site_settings (
                id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                setting_key VARCHAR(255) UNIQUE NOT NULL,
                setting_value TEXT,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
        } else {
            // SQLite syntax
            $sql = "CREATE TABLE IF NOT EXISTS site_settings (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                setting_key TEXT UNIQUE NOT NULL,
                setting_value TEXT,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )";
        }

        $this->db->exec($sql);

        // Initialize default settings if they don't exist
        $this->initializeDefaultSettings();
    }

    private function initializeDefaultSettings() {
        $defaultSettings = [
            'site_title' => 'Moowin Casino',
            'site_description' => 'Play the best free online games on our gaming portal. New games added daily!',
            'favicon_path' => '/public/images/favicon.ico',
            'logo_path' => '/public/images/logo.png',
            'hero_title' => 'Welcome to Our Gaming Portal',
            'hero_description' => 'Discover the best free online games and enjoy hours of entertainment.',
            'hero_image_path' => '/public/images/hero-default.jpg',
            'footer_description' => '© ' . date('Y') . ' Moowin Casino. All rights reserved. Our gaming portal offers free online games for entertainment purposes only.',
            'show_blog_section' => '1', // Enable blog section by default
            'blog_section_title' => 'Latest Blog Posts',
            'blog_section_description' => 'Check out our latest articles and updates',
            // SEO title templates
            'seo_title_homepage' => '{{site_title}} - Play Free Online Games',
            'seo_title_page' => '{{page_title}} - {{site_title}}',
            'seo_title_category' => '{{category_name}} Games - {{site_title}}',
            'seo_title_blog' => 'Blog - {{site_title}}',
            'seo_title_blog_post' => '{{post_title}} - Blog - {{site_title}}',
            'seo_title_game' => 'Play {{game_title}} - {{site_title}}',
            // Code injection settings
            'head_code' => '', // Custom code for the <head> section
            'body_start_code' => '', // Custom code after the opening <body> tag
            'body_end_code' => '', // Custom code before the closing </body> tag
            // Ad settings
            'enable_ads' => '0', // Disable ads by default
            'header_ad' => '', // Ad code for header
            'footer_ad' => '', // Ad code for footer
            'sidebar_ad' => '', // Ad code for sidebar
            'between_content_ad' => '', // Ad code for between content
            'game_page_ad' => '', // Ad code for game page
            'category_page_ad' => '', // Ad code for category page
            'blog_page_ad' => '', // Ad code for blog page
            'blog_post_ad' => '', // Ad code for blog post
            'search_page_ad' => '', // Ad code for search page
            // GamePix settings
            'gamepix_affiliate_id' => '', // GamePix affiliate ID
            // Ads.txt settings
            'gamepix_ads_txt' => '', // GamePix ads.txt content
            'gamemonitize_ads_txt' => '', // GameMonitize ads.txt content
            'custom_ads_txt' => '', // Custom ads.txt content
            // Cloudflare Turnstile settings
            'enable_turnstile' => '0', // Disable Turnstile by default
            // Cookie Banner settings
            'enable_cookie_banner' => '0', // Disable cookie banner by default
            // Points/Coins system settings
            'enable_points_system' => '0', // Disable points system by default
            'points_per_minute' => '10', // Points earned per minute of gameplay
            'minimum_withdrawal' => '1000', // Minimum points required for withdrawal
            'withdrawal_rate' => '100', // Points per dollar (100 points = $1)
            'withdrawal_methods' => 'PayPal,Bank Transfer,Cryptocurrency' // Available withdrawal methods (comma-separated)
        ];

        foreach ($defaultSettings as $key => $value) {
            $this->setSetting($key, $value, true);
        }
    }

    public function getSetting($key, $default = null) {
        $stmt = $this->db->prepare("SELECT setting_value FROM site_settings WHERE setting_key = :key");
        $stmt->bindParam(':key', $key);
        $stmt->execute();

        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        return $result ? $result['setting_value'] : $default;
    }

    public function setSetting($key, $value, $skipIfExists = false) {
        if ($skipIfExists) {
            $stmt = $this->db->prepare("SELECT COUNT(*) FROM site_settings WHERE setting_key = :key");
            $stmt->bindParam(':key', $key);
            $stmt->execute();

            if ($stmt->fetchColumn() > 0) {
                return true;
            }
        }

        // Check database type
        $dbType = $_ENV['DB_TYPE'] ?? 'sqlite';

        if ($dbType === 'mysql') {
            // MySQL syntax - uses INSERT ... ON DUPLICATE KEY UPDATE
            $stmt = $this->db->prepare("INSERT INTO site_settings (setting_key, setting_value, updated_at)
                                   VALUES (:key, :value, CURRENT_TIMESTAMP)
                                   ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_at = CURRENT_TIMESTAMP");
        } else {
            // SQLite syntax - uses INSERT OR REPLACE
            $stmt = $this->db->prepare("INSERT OR REPLACE INTO site_settings (setting_key, setting_value, updated_at)
                                   VALUES (:key, :value, CURRENT_TIMESTAMP)");
        }

        $stmt->bindParam(':key', $key);
        $stmt->bindParam(':value', $value);

        return $stmt->execute();
    }

    public function getAllSettings() {
        $stmt = $this->db->query("SELECT setting_key, setting_value FROM site_settings");
        $settings = [];

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $settings[$row['setting_key']] = $row['setting_value'];
        }

        return $settings;
    }

    /**
     * Process a title template by replacing tags with actual values
     *
     * @param string $template The title template with tags
     * @param array $replacements An associative array of tag => value pairs
     * @return string The processed title
     */
    public function processTitleTemplate($template, $replacements = []) {
        // Always have site_title available
        if (!isset($replacements['site_title'])) {
            $replacements['site_title'] = $this->getSetting('site_title', 'Moowin Casino');
        }

        // Replace all tags
        foreach ($replacements as $tag => $value) {
            $template = str_replace('{{' . $tag . '}}', $value, $template);
        }

        return $template;
    }
}