<?php
namespace App\Repositories;

use App\Database\Connection;
use App\Models\Config;
use App\Utils\Logger;
use PDO;
use PDOException;

class ConfigRepository
{
    private $db;
    private static $cache = [];

    public function __construct(Connection $db)
    {
        $this->db = $db;
    }

    public function getValue($key, $default = null)
    {
        if ($key === null || $key === '') {
            return $default;
        }
        
        if (array_key_exists($key, self::$cache)) {
            return self::$cache[$key];
        }
        
        try {
            $pdo = $this->db->getPdo();
            $stmt = $pdo->prepare("SELECT value FROM config WHERE `key` = ?");
            $stmt->execute([$key]);
            $value = $stmt->fetchColumn();
            
            if ($value === false) {
                return $default;
            }
            
            self::$cache[$key] = $value;
            return $value;
        } catch (PDOException $e) {
            $message = $e->getMessage();
            if ($e->getCode() === '42S02' || strpos($message, 'Base table or view not found') !== false) {
                return $default;
            }
            Logger::logError("Failed to read config value", $e, ['key' => $key]);
            return $default;
        }
    }

    public function setValue($key, $value)
    {
        if ($key === null || $key === '') {
            return false;
        }
        
        try {
            $pdo = $this->db->getPdo();
            // MySQL: INSERT ... ON DUPLICATE KEY UPDATE
            $stmt = $pdo->prepare("INSERT INTO config (`key`, value, updated_at) VALUES (?, ?, NOW()) 
                                   ON DUPLICATE KEY UPDATE value = VALUES(value), updated_at = NOW()");
            $stmt->execute([$key, $value]);
            self::$cache[$key] = $value;
            return true;
        } catch (PDOException $e) {
            Logger::logError("Failed to write config value", $e, ['key' => $key]);
            return false;
        }
    }

    public function clearCache()
    {
        self::$cache = [];
    }
}
