<?php
/**
 * Multi-Site Configuration Helper
 * 
 * This class handles site detection, configuration, and theming
 * Include this file in your main config to enable multi-site functionality
 */

// Include Database class if not already loaded
if (!class_exists('Database')) {
    require_once __DIR__ . '/database.php';
}

class SiteManager 
{
    private $db;
    private $currentSite;
    private static $instance = null;
    
    public function __construct($database = null) 
    {
        $this->db = $database ?: new Database();
        $this->detectCurrentSite();
    }
    
    public static function getInstance($database = null) 
    {
        // Deprecated: Use direct instantiation instead
        return new self($database);
    }
    
    /**
     * Detect current site based on domain
     */
    private function detectCurrentSite() 
    {
        $domain = $_SERVER['HTTP_HOST'] ?? 'localhost';
        
        // Remove www. prefix if present
        $domain = preg_replace('/^www\./', '', $domain);
        
        try {
            $connection = $this->db->getConnection();
            if (!$connection) {
                throw new Exception("Database connection not available");
            }
            
            $stmt = $connection->prepare("
                SELECT * FROM sites 
                WHERE domain = ? OR domain = ? 
                AND is_active = 1 
                ORDER BY domain = ? DESC 
                LIMIT 1
            ");
            $stmt->execute([$domain, "www.{$domain}", $domain]);
            
            $this->currentSite = $stmt->fetch(PDO::FETCH_ASSOC);
            
            // Only fallback to MAIN if accessing localhost directly
            if (!$this->currentSite && ($domain === 'localhost' || $domain === '127.0.0.1')) {
                $stmt = $this->db->getConnection()->prepare("
                    SELECT * FROM sites 
                    WHERE site_code = 'MAIN' 
                    AND is_active = 1 
                    LIMIT 1
                ");
                $stmt->execute();
                $this->currentSite = $stmt->fetch(PDO::FETCH_ASSOC);
            }
            
            // If still no site found (unknown domain), set as unknown site
            if (!$this->currentSite) {
                $this->currentSite = [
                    'id' => null,
                    'site_code' => 'UNKNOWN',
                    'site_name' => 'Unknown Site',
                    'domain' => $domain,
                    'primary_color' => '#25d366',
                    'secondary_color' => '#128c7e',
                    'accent_color' => '#075e54',
                    'background_color' => '#000000',
                    'text_color' => '#ffffff',
                    'logo_path' => 'assets/logos/site_logo_default.png',
                    'site_title' => 'Site Not Configured',
                    'site_description' => 'This domain is not configured in the system',
                    'is_active' => 0,
                    'maintenance_mode' => 1
                ];
            }
            
        } catch (Exception $e) {
            // For unknown sites, don't fallback to default site
            // This ensures proper site isolation - unknown sites get no markets
            $this->currentSite = [
                'id' => null,
                'site_code' => 'UNKNOWN',
                'site_name' => 'Unknown Site',
                'domain' => $domain,
                'primary_color' => '#25d366',
                'secondary_color' => '#128c7e',
                'accent_color' => '#075e54',
                'background_color' => '#000000',
                'text_color' => '#ffffff',
                'logo_path' => 'assets/logos/site_logo_default.png',
                'site_title' => 'Site Not Configured',
                'site_description' => 'This domain is not configured in the system',
                'is_active' => 0,
                'maintenance_mode' => 1
            ];
        }
    }
    
    /**
     * Get current site configuration
     */
    public function getCurrentSite() 
    {
        return $this->currentSite;
    }
    
    /**
     * Get site ID
     */
    public function getSiteId() 
    {
        return $this->currentSite['id'] ?? null;
    }
    
    /**
     * Get site code
     */
    public function getSiteCode() 
    {
        return $this->currentSite['site_code'] ?? 'MAIN';
    }
    
    /**
     * Check if site is in maintenance mode
     */
    public function isMaintenanceMode() 
    {
        return (bool) ($this->currentSite['maintenance_mode'] ?? false);
    }
    
    /**
     * Get maintenance message
     */
    public function getMaintenanceMessage() 
    {
        return $this->currentSite['maintenance_message'] ?? 'Site is currently under maintenance. Please try again later.';
    }
    
    /**
     * Get available markets for current site
     */
    public function getAvailableMarkets() 
    {
        // If no site detected (unknown domain), return empty array
        $siteId = $this->getSiteId();
        if ($siteId === null) {
            return [];
        }
        
        try {
            $stmt = $this->db->getConnection()->prepare("
                SELECT 
                    sm.market_code,
                    COALESCE(sm.market_name, ms.market_name) as market_name,
                    ms.close_time as open_time,
                    ms.schedule_time as close_time,
                    ms.official_site,
                    ms.logo_path,
                    sm.is_featured,
                    sm.display_order
                FROM site_markets sm
                LEFT JOIN market_schedules ms ON BINARY sm.market_code = BINARY ms.market_code
                WHERE sm.site_id = ? AND sm.is_active = 1
                ORDER BY sm.display_order ASC, sm.market_code ASC
            ");
            $stmt->execute([$siteId]);
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
            
        } catch (Exception $e) {
            // Log error but return empty array to maintain site isolation
            error_log("SiteManager getAvailableMarkets error for site_id {$siteId}: " . $e->getMessage());
            return [];
        }
    }
    
    /**
     * Get results for current site
     */
    public function getSiteResults($limit = 10) 
    {
        try {
            $stmt = $this->db->getConnection()->prepare("
                SELECT 
                    ldr.*,
                    sr.is_featured,
                    sr.display_order
                FROM site_results sr
                JOIN live_draw_results ldr ON sr.result_id = ldr.id
                WHERE sr.site_id = ? AND sr.is_active = 1
                ORDER BY sr.is_featured DESC, ldr.draw_date DESC, sr.display_order ASC
                LIMIT " . (int)$limit . "
            ");
            $stmt->execute([$this->getSiteId()]);
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
            
        } catch (Exception $e) {
            // Fallback to regular results if error
            return $this->db->getLiveDrawResults($limit);
        }
    }

    /**
     * Get today's results for current site only
     */
    public function getTodayResults() 
    {
        try {
            $today = date('Y-m-d');
            $stmt = $this->db->getConnection()->prepare("
                SELECT 
                    ldr.*,
                    sr.is_featured,
                    sr.display_order
                FROM site_results sr
                JOIN live_draw_results ldr ON sr.result_id = ldr.id
                WHERE sr.site_id = ? AND sr.is_active = 1 AND DATE(ldr.draw_date) = ?
                ORDER BY sr.is_featured DESC, 
                    CASE 
                        WHEN ldr.updated_at IS NOT NULL THEN ldr.updated_at 
                        ELSE ldr.created_at 
                    END DESC, 
                    ldr.draw_date DESC, 
                    sr.display_order ASC
            ");
            $stmt->execute([$this->getSiteId(), $today]);
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
            
        } catch (Exception $e) {
            // Log error but return empty array to maintain site isolation
            error_log("SiteManager getTodayResults error for site_id " . $this->getSiteId() . ": " . $e->getMessage());
            return [];
        }
    }

    /**
     * Get latest results for current site only
     */
    public function getLatestResults($limit = 10) 
    {
        try {
            $stmt = $this->db->getConnection()->prepare("
                SELECT 
                    ldr.*,
                    sr.is_featured,
                    sr.display_order
                FROM site_results sr
                JOIN live_draw_results ldr ON sr.result_id = ldr.id
                WHERE sr.site_id = ? AND sr.is_active = 1
                ORDER BY 
                    sr.is_featured DESC,
                    CASE 
                        WHEN ldr.updated_at IS NOT NULL THEN ldr.updated_at 
                        ELSE ldr.created_at 
                    END DESC,
                    ldr.draw_date DESC,
                    sr.display_order ASC
                LIMIT " . (int)$limit . "
            ");
            $stmt->execute([$this->getSiteId()]);
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
            
        } catch (Exception $e) {
            // Fallback to regular results if error (site_results table doesn't exist)
            error_log("SiteManager getLatestResults error for site_id " . $this->getSiteId() . ": " . $e->getMessage());
            return $this->db->getLiveDrawResults($limit);
        }
    }
    
    /**
     * Generate CSS variables for current site theme
     */
    public function generateThemeCSS() 
    {
        $site = $this->currentSite;
        
        // Use manual color selection from database
        // Fallback to default colors if not set
        $primaryColor = $site['primary_color'] ?? '#25d366';
        $secondaryColor = $site['secondary_color'] ?? '#1ba94c';
        $accentColor = $site['accent_color'] ?? '#40e788';
        $backgroundColor = $site['background_color'] ?? '#0a1a0f';
        $textColor = $site['text_color'] ?? '#ffffff';
        
        return "
        :root {
            /* Base theme colors */
            --primary-color: {$primaryColor};
            --secondary-color: {$secondaryColor};
            --accent-color: {$accentColor};
            --background-color: {$backgroundColor};
            --text-color: {$textColor};
            
            /* Legacy support */
            --site-primary: {$primaryColor};
            --site-secondary: {$secondaryColor};
            
            /* Extended color palette with opacity variations */
            --primary-light: {$primaryColor}20;
            --primary-medium: {$primaryColor}80;
            --primary-dark: {$primaryColor}CC;
            
            --secondary-light: {$secondaryColor}20;
            --secondary-medium: {$secondaryColor}80;
            
            --accent-light: {$accentColor}20;
            --accent-medium: {$accentColor}80;
            
            --background-light: {$backgroundColor}20;
            --background-medium: {$backgroundColor}80;
            --background-dark: {$backgroundColor}F0;
            
            --text-light: {$site['text_color']}99;
            --text-medium: {$site['text_color']}CC;
            
            /* Common UI colors */
            --success-color: #28a745;
            --warning-color: #ffc107;
            --danger-color: #dc3545;
            --info-color: #17a2b8;
            
            /* Border and shadow colors */
            --border-light: rgba(255, 255, 255, 0.1);
            --border-medium: rgba(255, 255, 255, 0.2);
            --border-dark: rgba(255, 255, 255, 0.3);
            
            --shadow-light: rgba(0, 0, 0, 0.1);
            --shadow-medium: rgba(0, 0, 0, 0.3);
            --shadow-dark: rgba(0, 0, 0, 0.5);
            
            /* Gradients */
            --gradient-primary: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            --gradient-background: linear-gradient(135deg, var(--background-color), var(--secondary-color));
        }
        ";
    }
    
    /**
     * Get site setting
     */
    public function getSetting($key, $default = null) 
    {
        try {
            $stmt = $this->db->getConnection()->prepare("
                SELECT setting_value, setting_type 
                FROM site_settings 
                WHERE site_id = ? AND setting_key = ?
            ");
            $stmt->execute([$this->getSiteId(), $key]);
            $setting = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$setting) {
                return $default;
            }
            
            // Convert based on type
            switch ($setting['setting_type']) {
                case 'boolean':
                    return (bool) $setting['setting_value'];
                case 'number':
                    return (float) $setting['setting_value'];
                case 'json':
                    return json_decode($setting['setting_value'], true);
                default:
                    return $setting['setting_value'];
            }
            
        } catch (Exception $e) {
            return $default;
        }
    }
    
    /**
     * Get all sites (for admin)
     */
    public function getAllSites() 
    {
        try {
            $stmt = $this->db->getConnection()->prepare("
                SELECT * FROM sites 
                ORDER BY is_active DESC, site_code ASC
            ");
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
            
        } catch (Exception $e) {
            return [];
        }
    }
    
    /**
     * Get all available markets from market_schedules table
     */
    public function getAllMarkets() 
    {
        try {
            $stmt = $this->db->getConnection()->prepare("
                SELECT DISTINCT market_code, market_name, id
                FROM market_schedules 
                WHERE is_active = 1
                ORDER BY market_name ASC
            ");
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
            
        } catch (Exception $e) {
            return [];
        }
    }
    
    /**
     * Get markets assigned to a specific site
     */
    public function getSiteMarkets($siteId) 
    {
        try {
            $stmt = $this->db->getConnection()->prepare("
                SELECT sm.*, sm.market_name, ms.id as market_id
                FROM site_markets sm
                LEFT JOIN market_schedules ms ON BINARY sm.market_code = BINARY ms.market_code
                WHERE sm.site_id = ?
                ORDER BY sm.display_order ASC, sm.market_code ASC
            ");
            $stmt->execute([$siteId]);
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
            
        } catch (Exception $e) {
            return [];
        }
    }
    
    /**
     * Get default site configuration (fallback)
     */
    private function getDefaultSiteConfig() 
    {
        return [
            'id' => 1,
            'site_code' => 'MAIN',
            'site_name' => 'AutoPrediksi Togel',
            'domain' => 'localhost',
            'primary_color' => '#25d366',
            'secondary_color' => '#128c7e',
            'accent_color' => '#075e54',
            'background_color' => '#000000',
            'text_color' => '#ffffff',
            'logo_path' => 'assets/logos/site_logo_default.png',
            'site_title' => 'AutoPrediksi - Prediksi Togel Akurat',
            'site_description' => 'Situs prediksi togel terpercaya dengan data result terlengkap',
            'is_active' => 1,
            'maintenance_mode' => 0
        ];
    }
    
    /**
     * Add result to multiple sites (for admin)
     */
    public function addResultToSites($marketCode, $drawDate, $result4d, $result3d, $result2d, $siteIds = []) 
    {
        try {
            $pdo = $this->db->getConnection();
            $pdo->beginTransaction();
            
            // Insert result first
            $stmt = $pdo->prepare("
                INSERT INTO live_draw_results (market, draw_date, result_4d, result_3d, result_2d)
                VALUES (?, ?, ?, ?, ?)
            ");
            $stmt->execute([$marketCode, $drawDate, $result4d, $result3d, $result2d]);
            $resultId = $pdo->lastInsertId();
            
            // If no site IDs specified, add to current site only
            if (empty($siteIds)) {
                $siteIds = [$this->getSiteId()];
            }
            
            // Add to specified sites
            $stmt = $pdo->prepare("
                INSERT INTO site_results (site_id, result_id) 
                VALUES (?, ?)
            ");
            
            foreach ($siteIds as $siteId) {
                $stmt->execute([$siteId, $resultId]);
            }
            
            $pdo->commit();
            return $resultId;
            
        } catch (Exception $e) {
            $pdo->rollback();
            throw $e;
        }
    }
    
    /**
     * Get HTML meta tags for current site
     */
    public function getMetaTags() 
    {
        $site = $this->currentSite;
        
        // Get website settings for SEO data
        try {
            $websiteSettings = $this->db->getWebsiteSettings();
            
            return [
                'title' => $websiteSettings['site_name'] ?? $site['site_title'] ?? 'Togel Prediction Site',
                'description' => $websiteSettings['meta_description'] ?? $site['site_description'] ?? 'Accurate togel predictions and results',
                'keywords' => $websiteSettings['meta_keywords'] ?? $site['site_keywords'] ?? 'togel, prediction, result, singapore, hongkong',
                'favicon' => $site['favicon_path'] ?? 'assets/images/favicon.ico'
            ];
        } catch (Exception $e) {
            // Fallback to site data if database fails
            return [
                'title' => $site['site_title'] ?? 'Togel Prediction Site',
                'description' => $site['site_description'] ?? 'Accurate togel predictions and results', 
                'keywords' => $site['site_keywords'] ?? 'togel, prediction, result, singapore, hongkong',
                'favicon' => $site['favicon_path'] ?? 'assets/images/favicon.ico'
            ];
        }
    }
}

// Global helper functions
function getCurrentSite() {
    return SiteManager::getInstance()->getCurrentSite();
}

function getSiteId() {
    $db = new Database();
    $siteManager = new SiteManager($db);
    return $siteManager->getSiteId();
}

function getSiteCode() {
    $db = new Database();
    $siteManager = new SiteManager($db);
    return $siteManager->getSiteCode();
}

function getAvailableMarkets() {
    // Create fresh instance for each call to ensure proper site detection
    $db = new Database();
    $siteManager = new SiteManager($db);
    return $siteManager->getAvailableMarkets();
}

function getAllMarkets() {
    $db = new Database();
    $siteManager = new SiteManager($db);
    return $siteManager->getAllMarkets();
}

function getSiteMarkets($siteId) {
    return SiteManager::getInstance()->getSiteMarkets($siteId);
}

function getSiteResults($limit = 10) {
    return SiteManager::getInstance()->getSiteResults($limit);
}

function generateThemeCSS() {
    return SiteManager::getInstance()->generateThemeCSS();
}

function getSiteSetting($key, $default = null) {
    return SiteManager::getInstance()->getSetting($key, $default);
}

function isMaintenanceMode() {
    return SiteManager::getInstance()->isMaintenanceMode();
}

// Site-Isolated Website Settings Methods
function getSiteWebsiteSettings($siteId = null) {
    $db = new Database();
    return $db->getWebsiteSettings($siteId);
}

function updateSiteWebsiteSetting($key, $value, $siteId = null) {
    $db = new Database();
    return $db->updateWebsiteSetting($key, $value, $siteId);
}

function getSiteWebsiteSetting($key, $siteId = null) {
    $db = new Database();
    return $db->getWebsiteSetting($key, $siteId);
}
?>