<?php

declare(strict_types=1);

/**
 * PlatformSettings
 * 
 * Manages platform-wide settings including payment gateways, currencies, trials, etc.
 */
class PlatformSettings
{
    private static array $cache = [];

    /**
     * Get a setting value
     */
    public static function get(string $key, $default = null)
    {
        if (isset(self::$cache[$key])) {
            return self::$cache[$key];
        }

        $pdo = getPDO();
        $stmt = $pdo->prepare('SELECT setting_value, setting_type FROM platform_settings WHERE setting_key = ?');
        $stmt->execute([$key]);
        $row = $stmt->fetch();

        if (!$row) {
            return $default;
        }

        $value = self::castValue($row['setting_value'], $row['setting_type']);
        self::$cache[$key] = $value;
        
        return $value;
    }

    /**
     * Set a setting value
     */
    public static function set(string $key, $value, ?int $updatedBy = null): bool
    {
        $pdo = getPDO();
        
        // Determine type
        $type = 'string';
        if (is_bool($value)) {
            $type = 'boolean';
            $value = $value ? 'true' : 'false';
        } elseif (is_numeric($value) && !is_string($value)) {
            $type = 'number';
            $value = (string)$value;
        } elseif (is_array($value)) {
            $type = 'json';
            $value = json_encode($value);
        }

        $stmt = $pdo->prepare('
            INSERT INTO platform_settings (setting_key, setting_value, setting_type, updated_by)
            VALUES (?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), setting_type = VALUES(setting_type), updated_by = VALUES(updated_by)
        ');
        $result = $stmt->execute([$key, $value, $type, $updatedBy]);

        if ($result) {
            unset(self::$cache[$key]);
        }

        return $result;
    }

    /**
     * Get all settings by category
     */
    public static function getByCategory(string $category): array
    {
        $pdo = getPDO();
        $stmt = $pdo->prepare('SELECT * FROM platform_settings WHERE category = ? ORDER BY setting_key');
        $stmt->execute([$category]);
        
        $settings = [];
        foreach ($stmt->fetchAll() as $row) {
            $settings[$row['setting_key']] = [
                'value' => self::castValue($row['setting_value'], $row['setting_type']),
                'type' => $row['setting_type'],
                'description' => $row['description'],
            ];
        }
        
        return $settings;
    }

    /**
     * Get all settings
     */
    public static function getAll(): array
    {
        $pdo = getPDO();
        $stmt = $pdo->query('SELECT * FROM platform_settings ORDER BY category, setting_key');
        
        $settings = [];
        foreach ($stmt->fetchAll() as $row) {
            $settings[$row['setting_key']] = [
                'value' => self::castValue($row['setting_value'], $row['setting_type']),
                'type' => $row['setting_type'],
                'category' => $row['category'],
                'description' => $row['description'],
            ];
        }
        
        return $settings;
    }

    /**
     * Cast value to appropriate type
     */
    private static function castValue(?string $value, string $type)
    {
        if ($value === null) {
            return null;
        }

        switch ($type) {
            case 'boolean':
                return $value === 'true' || $value === '1';
            case 'number':
                return strpos($value, '.') !== false ? (float)$value : (int)$value;
            case 'json':
                return json_decode($value, true);
            default:
                return $value;
        }
    }

    /**
     * Check if Stripe is enabled
     */
    public static function isStripeEnabled(): bool
    {
        return self::get('stripe_enabled', false) && !empty(self::get('stripe_secret_key'));
    }

    /**
     * Check if Razorpay is enabled
     */
    public static function isRazorpayEnabled(): bool
    {
        return self::get('razorpay_enabled', false) && !empty(self::get('razorpay_key_secret'));
    }

    /**
     * Get Stripe keys
     */
    public static function getStripeKeys(): array
    {
        return [
            'public_key' => self::get('stripe_public_key', ''),
            'secret_key' => self::get('stripe_secret_key', ''),
            'webhook_secret' => self::get('stripe_webhook_secret', ''),
        ];
    }

    /**
     * Get Razorpay keys
     */
    public static function getRazorpayKeys(): array
    {
        return [
            'key_id' => self::get('razorpay_key_id', ''),
            'key_secret' => self::get('razorpay_key_secret', ''),
            'webhook_secret' => self::get('razorpay_webhook_secret', ''),
        ];
    }

    /**
     * Get trial settings
     */
    public static function getTrialSettings(): array
    {
        return [
            'enabled' => self::get('trial_enabled', true),
            'days' => self::get('trial_days', 14),
            'plan_id' => self::get('trial_plan_id', 1),
        ];
    }

    /**
     * Get currency settings
     */
    public static function getCurrencySettings(): array
    {
        return [
            'default' => self::get('default_currency', 'USD'),
            'supported' => self::get('supported_currencies', ['USD', 'INR']),
            'usd_to_inr_rate' => self::get('usd_to_inr_rate', 83),
        ];
    }

    /**
     * Get discount settings
     */
    public static function getDiscountSettings(): array
    {
        return [
            'enabled' => self::get('discount_enabled', false),
            'yearly_discount_percent' => self::get('yearly_discount_percent', 20),
        ];
    }

    /**
     * Clear cache
     */
    public static function clearCache(): void
    {
        self::$cache = [];
    }
}
