<?php
/**
 * Site Settings Helper
 * Frontend ve Backend arasında ayarları senkronize eder
 * 
 * Bu dosya config.php'den sonra dahil edilir ve
 * veritabanından gelen ayarları sabit tanımlarla birleştirir
 */

declare(strict_types=1);

class SiteSettings
{
    private static ?self $instance = null;
    private array $settings = [];
    private bool $loaded = false;
    
    private function __construct()
    {
        $this->loadSettings();
    }
    
    public static function getInstance(): self
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Tüm ayarları veritabanından yükle
     */
    private function loadSettings(): void
    {
        if ($this->loaded) return;
        
        try {
            $db = Database::getInstance();
            
            // Önce settings tablosunun var olup olmadığını kontrol et
            $tableExists = $db->fetchColumn(
                "SELECT COUNT(*) FROM information_schema.tables 
                 WHERE table_schema = DATABASE() AND table_name = 'settings'"
            );
            
            if (!$tableExists) {
                $this->loaded = true;
                return;
            }
            
            $rows = $db->fetchAll(
                "SELECT setting_key, setting_value, category FROM settings WHERE is_active = 1"
            );
            
            foreach ($rows as $row) {
                $this->settings[$row['setting_key']] = $row['setting_value'];
            }
            
            $this->loaded = true;
            
        } catch (Exception $e) {
            error_log("SiteSettings::loadSettings error: " . $e->getMessage());
            $this->loaded = true;
        }
    }
    
    /**
     * Ayar değeri al (veritabanı öncelikli, sonra config sabitleri)
     */
    public function get(string $key, string $default = ''): string
    {
        // Veritabanından
        if (isset($this->settings[$key]) && $this->settings[$key] !== '') {
            return $this->settings[$key];
        }
        
        // Config sabitlerinden
        $constantMap = [
            'site_name' => 'SITE_NAME',
            'site_slogan' => 'SITE_SLOGAN',
            'contact_phone' => 'SITE_PHONE',
            'contact_whatsapp' => 'SITE_WHATSAPP',
            'contact_email' => 'SITE_EMAIL',
            'contact_address' => 'SITE_ADDRESS',
            'seo_title' => 'SEO_TITLE',
            'seo_description' => 'SEO_DESCRIPTION',
            'seo_keywords' => 'SEO_KEYWORDS',
        ];
        
        if (isset($constantMap[$key]) && defined($constantMap[$key])) {
            return constant($constantMap[$key]);
        }
        
        return $default;
    }
    
    /**
     * Tüm ayarları al
     */
    public function all(): array
    {
        return $this->settings;
    }
    
    /**
     * Kategoriye göre ayarları al
     */
    public function getByCategory(string $category): array
    {
        try {
            $db = Database::getInstance();
            return $db->fetchAll(
                "SELECT setting_key, setting_value FROM settings WHERE category = ? AND is_active = 1",
                [$category]
            );
        } catch (Exception $e) {
            return [];
        }
    }
    
    /**
     * Network linklerini al
     */
    public function getNetworkLinks(): array
    {
        try {
            $db = Database::getInstance();
            
            // network_links tablosu var mı?
            $tableExists = $db->fetchColumn(
                "SELECT COUNT(*) FROM information_schema.tables 
                 WHERE table_schema = DATABASE() AND table_name = 'network_links'"
            );
            
            if ($tableExists) {
                return $db->fetchAll(
                    "SELECT domain, title, anchor_text, target_url, rel_attribute 
                     FROM network_links WHERE is_active = 1 ORDER BY display_order"
                );
            }
            
            // Fallback to config constant
            if (defined('DOMAIN_NETWORK')) {
                $links = [];
                foreach (DOMAIN_NETWORK as $domain => $title) {
                    $links[] = [
                        'domain' => $domain,
                        'title' => $title,
                        'anchor_text' => $title,
                        'target_url' => 'https://' . $domain,
                        'rel_attribute' => 'dofollow'
                    ];
                }
                return $links;
            }
            
            return [];
            
        } catch (Exception $e) {
            return [];
        }
    }
    
    /**
     * Aktif servisleri al
     */
    public function getActiveServices(int $limit = 20): array
    {
        try {
            $db = Database::getInstance();
            return $db->fetchAll(
                "SELECT id, name, slug, category, short_description, featured_image 
                 FROM services WHERE is_active = 1 
                 ORDER BY display_order ASC, name ASC 
                 LIMIT ?",
                [$limit]
            );
        } catch (Exception $e) {
            return [];
        }
    }
    
    /**
     * Son blog yazılarını al
     */
    public function getRecentPosts(int $limit = 5): array
    {
        try {
            $db = Database::getInstance();
            return $db->fetchAll(
                "SELECT id, title, slug, excerpt, category, published_at 
                 FROM blog_posts WHERE status = 'published' 
                 ORDER BY published_at DESC 
                 LIMIT ?",
                [$limit]
            );
        } catch (Exception $e) {
            return [];
        }
    }
    
    /**
     * Aktif şehirleri al
     */
    public function getActiveCities(): array
    {
        try {
            $db = Database::getInstance();
            return $db->fetchAll(
                "SELECT id, name, slug, region 
                 FROM cities WHERE is_active = 1 
                 ORDER BY display_order ASC, name ASC"
            );
        } catch (Exception $e) {
            return [];
        }
    }
}

/**
 * Global helper function
 */
function siteSettings(): SiteSettings
{
    return SiteSettings::getInstance();
}

/**
 * Quick setting getter (replaces the one in Database.php for frontend)
 */
if (!function_exists('site')) {
    function site(string $key, string $default = ''): string
    {
        return siteSettings()->get($key, $default);
    }
}
