<?php

namespace App\Core;

/**
 * Config Manager - إدارة الإعدادات
 * يوحد الوصول إلى الإعدادات من config.php و settings table
 */
class ConfigManager
{
    private array $config;
    private \PDO $db;
    private ?int $tenantId;
    private array $settingsCache = [];
    private bool $settingsLoaded = false;

    public function __construct(array $config, \PDO $db, ?int $tenantId = null)
    {
        $this->config = $config;
        $this->db = $db;
        $this->tenantId = $tenantId;
    }

    /**
     * جلب إعداد من config.php
     */
    public function get(string $key, $default = null)
    {
        $keys = explode('.', $key);
        $value = $this->config;

        foreach ($keys as $k) {
            if (!isset($value[$k])) {
                return $default;
            }
            $value = $value[$k];
        }

        return $value;
    }

    /**
     * جلب إعداد من settings table
     */
    public function getSetting(string $key, $default = null)
    {
        $this->loadSettings();

        return $this->settingsCache[$key] ?? $default;
    }

    /**
     * حفظ إعداد في settings table
     */
    public function setSetting(string $key, $value): bool
    {
        try {
            $tenantClause = '';
            $params = [$key, $value];
            
            if ($this->tenantId !== null) {
                try {
                    $this->db->query('SELECT tenant_id FROM settings LIMIT 1');
                    $tenantClause = ' AND tenant_id = ?';
                    $params[] = $this->tenantId;
                } catch (\Throwable $e) {}
            }

            $stmt = $this->db->prepare("
                INSERT INTO settings (setting_key, setting_value" . 
                ($this->tenantId !== null && $tenantClause ? ', tenant_id' : '') . 
                ")
                VALUES (?, ?" . ($this->tenantId !== null && $tenantClause ? ', ?' : '') . ")
                ON DUPLICATE KEY UPDATE setting_value = ?, updated_at = NOW()
            ");

            if ($this->tenantId !== null && $tenantClause) {
                $stmt->execute([$key, $value, $this->tenantId, $value]);
            } else {
                $stmt->execute([$key, $value, $value]);
            }

            // تحديث cache
            $this->settingsCache[$key] = $value;
            
            return true;
        } catch (\Throwable $e) {
            error_log("Config setSetting error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * تحميل جميع الإعدادات من settings table
     */
    private function loadSettings(): void
    {
        if ($this->settingsLoaded) {
            return;
        }

        try {
            $tenantClause = '';
            $params = [];
            
            if ($this->tenantId !== null) {
                try {
                    $this->db->query('SELECT tenant_id FROM settings LIMIT 1');
                    $tenantClause = ' WHERE tenant_id = ?';
                    $params[] = $this->tenantId;
                } catch (\Throwable $e) {
                    $tenantClause = '';
                }
            }

            $stmt = $this->db->prepare("SELECT setting_key, setting_value FROM settings" . $tenantClause);
            $stmt->execute($params);
            $settings = $stmt->fetchAll();

            foreach ($settings as $setting) {
                $this->settingsCache[$setting['setting_key']] = $setting['setting_value'];
            }

            $this->settingsLoaded = true;
        } catch (\Throwable $e) {
            error_log("Config loadSettings error: " . $e->getMessage());
        }
    }

    /**
     * جلب إعداد (config أولاً، ثم settings)
     */
    public function getConfig(string $key, $default = null)
    {
        $value = $this->get($key);
        if ($value !== null) {
            return $value;
        }

        return $this->getSetting($key, $default);
    }

    /**
     * مسح cache الإعدادات
     */
    public function clearCache(): void
    {
        $this->settingsCache = [];
        $this->settingsLoaded = false;
    }
}
