<?php

declare(strict_types=1);

final class AppSettings
{
    private const DEFAULTS = [
        'association_name' => 'Association',
        'association_address' => '',
        'association_postal_code' => '',
        'association_city' => '',
        'association_phone' => '',
        'association_email' => '',
        'association_siret' => '',
        'association_rna' => '',
        'association_latitude' => '',
        'association_longitude' => '',
        'adoption_fee_sterilized' => '220',
        'adoption_fee_unsterilized' => '200',
        'quarantine_days' => '15',
        'backup_retention' => '10',
        'app_language' => 'fr',
        'public_site_enabled' => '0',
        'public_site_theme' => 'warm',
        'public_site_routing' => 'integrated',
        'public_site_home_title' => 'Ils attendent une famille',
        'public_site_home_text' => 'Découvrez les animaux actuellement proposés à l’adoption par notre association.',
        'public_site_about_enabled' => '1',
        'public_site_about_title' => 'Notre association',
        'public_site_about_text' => 'Présentez ici votre association, son histoire et ses missions.',
        'public_site_donation_title' => 'Nous soutenir',
        'public_site_donation_text' =>
            'Chaque don contribue directement aux soins, à l’alimentation et à la protection des animaux.',
        'public_site_donation_url' => '',
        'public_site_contact_text' => 'Une question sur une adoption ou sur l’association ? Contactez-nous.',
        'public_site_facebook_url' => '',
        'public_site_instagram_url' => '',
        'notification_email_enabled' => '0',
        'notification_email_frequency' => 'weekly',
        'notification_email_recipient' => '',
        'notification_last_sent_at' => '',
        'privacy_retention_years' => '5',
        'privacy_retention_adopter_years' => '5',
        'privacy_retention_foster_years' => '5',
        'privacy_retention_volunteer_years' => '5',
        'privacy_access_log_months' => '24',
        'backup_schedule_enabled' => '0',
        'backup_schedule_frequency' => 'daily',
        'backup_last_run_at' => '',
        'backup_last_verified_at' => '',
        'public_site_legal_text' => '',
        'public_site_privacy_text' => '',
    ];
    private static ?array $cache = null;
    public static function all(): array
    {
        if (self::$cache !== null) {
            return self::$cache;
        }
        $values = self::DEFAULTS;
        try {
            foreach (
                DB::pdo()->query('SELECT setting_key,setting_value FROM app_settings')->fetchAll(PDO::FETCH_ASSOC)
                as $row
            ) {
                if (array_key_exists($row['setting_key'], $values)) {
                    $values[$row['setting_key']] = (string) $row['setting_value'];
                }
            }
        } catch (Throwable) {
        }
        return self::$cache = $values;
    }
    public static function get(string $key): string
    {
        return (string) (self::all()[$key] ?? '');
    }
    public static function int(string $key, int $min = 0, int $max = PHP_INT_MAX): int
    {
        return max($min, min($max, (int) self::get($key)));
    }
    public static function save(array $values, ?int $userId): void
    {
        $allowed = array_keys(self::DEFAULTS);
        $stmt = DB::pdo()->prepare(
            "INSERT INTO app_settings(setting_key,setting_value,updated_by,updated_at) VALUES(:key,:value,:user,datetime('now')) ON CONFLICT(setting_key) DO UPDATE SET setting_value=excluded.setting_value,updated_by=excluded.updated_by,updated_at=datetime('now')",
        );
        foreach ($allowed as $key) {
            if (array_key_exists($key, $values)) {
                $stmt->execute([':key' => $key, ':value' => (string) $values[$key], ':user' => $userId]);
            }
        }
        self::$cache = null;
    }
}
