<?php
/**
 * Admin Panel - Settings Controller
 * Manage platform settings, currencies, and general configuration
 */

namespace App\Controller\Admin;

use App\Classes\Currency\CurrencyManager;

class SettingsController extends AdminController {
    
    /**
     * Get all settings
     */
    public function getAllSettings() {
        $stmt = $this->db->query('SELECT * FROM settings ORDER BY setting_key');
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }
    
    /**
     * Get setting by key
     */
    public function getSetting($key) {
        $stmt = $this->db->prepare('SELECT * FROM settings WHERE setting_key = ?');
        $stmt->execute([$key]);
        return $stmt->fetch(\PDO::FETCH_ASSOC);
    }
    
    /**
     * Update setting
     */
    public function updateSetting($key, $value, $dataType = 'string') {
        try {
            $stmt = $this->db->prepare('
                INSERT INTO settings (setting_key, setting_value, data_type)
                VALUES (?, ?, ?)
                ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)
            ');
            
            $stmt->execute([$key, $value, $dataType]);
            
            $this->logAdminAction('setting_update', "$key = $value");
            
            return ['success' => true];
            
        } catch (\Exception $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
    
    /**
     * Update multiple settings
     */
    public function updateSettings($settings) {
        try {
            $this->db->beginTransaction();
            
            foreach ($settings as $key => $value) {
                $dataType = $this->getDataType($key);
                $this->updateSetting($key, $value, $dataType);
            }
            
            $this->db->commit();
            
            $this->logAdminAction('settings_bulk_update', 'Multiple settings updated');
            
            return ['success' => true];
            
        } catch (\Exception $e) {
            $this->db->rollBack();
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
    
    /**
     * Get settings for currency management
     */
    public function getCurrencySettings() {
        $currencyManager = CurrencyManager::getInstance();
        
        return [
            'primary_currency' => $this->getSetting('primary_currency')['setting_value'],
            'supported_currencies' => explode(',', $this->getSetting('supported_currencies')['setting_value'] ?? 'UGX,USD,KSH'),
            'exchange_rates' => $currencyManager->getAllRates(),
            'currencies_list' => $currencyManager->getCurrencies()
        ];
    }
    
    /**
     * Update exchange rates
     */
    public function updateExchangeRates($rates) {
        try {
            $currencyManager = CurrencyManager::getInstance();
            $currencyManager->updateRates($rates);
            
            // Store in database
            $stmt = $this->db->prepare('
                INSERT INTO settings (setting_key, setting_value, data_type)
                VALUES ("exchange_rates", ?, "json")
                ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)
            ');
            $stmt->execute([json_encode($rates)]);
            
            $this->logAdminAction('exchange_rates_update', json_encode($rates));
            
            return ['success' => true];
            
        } catch (\Exception $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
    
    /**
     * Get settings for payment configuration
     */
    public function getPaymentSettings() {
        return [
            'min_deposit' => $this->getSetting('min_deposit')['setting_value'],
            'max_deposits_per_day' => $this->getSetting('max_deposits_per_day')['setting_value'],
            'payment_gateway' => env('MARZPAY_API_KEY') ? 'Marzpay' : 'Not configured'
        ];
    }
    
    /**
     * Get settings for service configuration
     */
    public function getServiceSettings() {
        return [
            'service_provider' => env('MRGOV_API_KEY') ? 'MrGoViral' : 'Not configured',
            'service_sync_interval' => $this->getSetting('service_sync_interval')['setting_value'],
            'next_sync' => $this->getNextServiceSync()
        ];
    }
    
    /**
     * Get next service sync time
     */
    private function getNextServiceSync() {
        $interval = (int)$this->getSetting('service_sync_interval')['setting_value'];
        $stmt = $this->db->query('SELECT MAX(last_synced) as last_sync FROM services');
        $result = $stmt->fetch(\PDO::FETCH_ASSOC);
        
        if ($result['last_sync']) {
            return date('Y-m-d H:i:s', strtotime($result['last_sync']) + $interval);
        }
        
        return date('Y-m-d H:i:s'); // immediate
    }
    
    /**
     * Get feature flags
     */
    public function getFeatureFlags() {
        return [
            'enable_registration' => (bool)$this->getSetting('enable_registration')['setting_value'],
            'enable_referral_program' => (bool)$this->getSetting('enable_referral_program')['setting_value'],
            'enable_drip_feeds' => env('ENABLE_DRIP_FEEDS', 'true') === 'true',
            'enable_api_access' => env('ENABLE_API_ACCESS', 'true') === 'true'
        ];
    }
    
    /**
     * Update feature flags
     */
    public function updateFeatureFlags($flags) {
        try {
            $this->db->beginTransaction();
            
            foreach ($flags as $key => $value) {
                $this->updateSetting($key, $value ? 'true' : 'false', 'boolean');
            }
            
            $this->db->commit();
            
            $this->logAdminAction('feature_flags_update', json_encode($flags));
            
            return ['success' => true];
            
        } catch (\Exception $e) {
            $this->db->rollBack();
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
    
    /**
     * Get referral settings
     */
    public function getReferralSettings() {
        return [
            'referral_commission' => $this->getSetting('referral_commission')['setting_value'],
            'enable_referral_program' => (bool)$this->getSetting('enable_referral_program')['setting_value']
        ];
    }
    
    /**
     * Update referral settings
     */
    public function updateReferralSettings($commissionRate) {
        if ($commissionRate < 0 || $commissionRate > 100) {
            return ['success' => false, 'error' => 'Commission rate must be between 0 and 100'];
        }
        
        return $this->updateSetting('referral_commission', $commissionRate, 'integer');
    }
    
    /**
     * Helper to determine data type
     */
    private function getDataType($key) {
        $booleanSettings = ['enable_registration', 'enable_referral_program', 'enable_drip_feeds', 'enable_api_access'];
        $integerSettings = ['min_deposit', 'max_deposits_per_day', 'referral_commission', 'service_sync_interval', 'api_rate_limit', 'ticket_auto_close_days'];
        $jsonSettings = ['exchange_rates'];
        
        if (in_array($key, $booleanSettings)) return 'boolean';
        if (in_array($key, $integerSettings)) return 'integer';
        if (in_array($key, $jsonSettings)) return 'json';
        
        return 'string';
    }
}
?>
