<?php

require_once BASE_PATH . '/config/database.php';

class SystemSetting
{
    private PDO $db;

    private const DEFAULTS = [
        'registration_enabled' => [
            'value' => '1',
            'type' => 'boolean'
        ],
        'maintenance_mode' => [
            'value' => '0',
            'type' => 'boolean'
        ],
        'activity_logging_enabled' => [
            'value' => '1',
            'type' => 'boolean'
        ],
        'max_upload_mb' => [
            'value' => '5',
            'type' => 'integer'
        ]
    ];

    public function __construct()
    {
        $this->db = (new Database())->connect();
    }

    public function getAll(): array
    {
        $settings = self::DEFAULTS;

        try {
            $rows = $this->db->query(
                'SELECT setting_key, setting_value, setting_type
                 FROM system_settings'
            )->fetchAll();

            foreach ($rows as $row) {
                if (array_key_exists($row['setting_key'], $settings)) {
                    $settings[$row['setting_key']] = [
                        'value' => (string) $row['setting_value'],
                        'type' => (string) $row['setting_type']
                    ];
                }
            }
        } catch (PDOException) {
            // The application remains compatible until the additive migration runs.
        }

        return $settings;
    }

    public function getBoolean(string $key, bool $default): bool
    {
        $settings = $this->getAll();

        if (!isset($settings[$key])) {
            return $default;
        }

        return $settings[$key]['value'] === '1';
    }

    public function update(array $values, int $updatedBy): void
    {
        $allowed = [
            'registration_enabled' => 'boolean',
            'maintenance_mode' => 'boolean',
            'activity_logging_enabled' => 'boolean',
            'max_upload_mb' => 'integer'
        ];

        foreach ($allowed as $key => $type) {
            if (!array_key_exists($key, $values)) {
                continue;
            }

            $stmt = $this->db->prepare(
                'INSERT INTO system_settings (
                    setting_key, setting_value, setting_type, updated_by
                 ) VALUES (
                    :setting_key, :setting_value, :setting_type, :updated_by
                 ) ON DUPLICATE KEY UPDATE
                    setting_value = VALUES(setting_value),
                    setting_type = VALUES(setting_type),
                    updated_by = VALUES(updated_by),
                    updated_at = NOW()'
            );

            $stmt->execute([
                'setting_key' => $key,
                'setting_value' => (string) $values[$key],
                'setting_type' => $type,
                'updated_by' => $updatedBy
            ]);
        }
    }
}
