<?php

namespace App\Controllers;

use PDO;
use Exception;
use Core\Redirect;

class CurrencySettings
{
    private $conn;
    
    public function __construct()
    {
        try {
            // Create PDO connection using config constants
            if (file_exists('config.php')) {
                include_once 'config.php';
            } else {
                throw new Exception('Config file not found');
            }
            
            if (!defined('MYSQL_HOST') || !defined('MYSQL_USER') || !defined('MYSQL_DATABASE')) {
                throw new Exception('Database configuration constants not defined');
            }
            
            $dsn = "mysql:host=" . MYSQL_HOST . ";dbname=" . MYSQL_DATABASE . ";charset=utf8mb4";
            $this->conn = new PDO($dsn, MYSQL_USER, MYSQL_PASSWORD, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false
            ]);
        } catch (Exception $e) {
            error_log("Database connection error in CurrencySettings: " . $e->getMessage());
            $this->conn = null;
        }
    }
    
    /**
     * Get current currency settings
     */
    public function getCurrentSettings()
    {
        try {
            if (!$this->conn) {
                return [];
            }
            
            $stmt = $this->conn->prepare("
                SELECT setting_name, setting_value 
                FROM settings 
                WHERE setting_name IN ('currency_code', 'currency_symbol', 'currency_position')
            ");
            $stmt->execute();
            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $settings = [];
            foreach ($results as $row) {
                $settings[$row['setting_name']] = $row['setting_value'];
            }
            
            // Set defaults if not found
            if (!isset($settings['currency_code'])) $settings['currency_code'] = 'USD';
            if (!isset($settings['currency_symbol'])) $settings['currency_symbol'] = '$';
            if (!isset($settings['currency_position'])) $settings['currency_position'] = 'before';
            
            return $settings;
        } catch (Exception $e) {
            error_log("Error fetching currency settings: " . $e->getMessage());
            return [
                'currency_code' => 'USD',
                'currency_symbol' => '$',
                'currency_position' => 'before'
            ];
        }
    }
    
    /**
     * Save currency settings
     */
    public function saveSettings()
    {
        try {
            if (!$this->conn) {
                $_SESSION['error'] = 'Database connection failed';
                header('Location: ?app_route=currency_settings');
                exit;
            }
            
            $currency_code = $_POST['currency_code'] ?? 'USD';
            $currency_symbol = $_POST['currency_symbol'] ?? '$';
            $currency_position = $_POST['currency_position'] ?? 'before';
            
            // Validate inputs
            if (empty($currency_code) || empty($currency_symbol)) {
                $_SESSION['error'] = 'Currency code and symbol are required';
                header('Location: ?app_route=currency_settings');
                exit;
            }
            
            // Update or insert currency settings
            $settings = [
                'currency_code' => $currency_code,
                'currency_symbol' => $currency_symbol,
                'currency_position' => $currency_position
            ];
            
            $stmt = $this->conn->prepare("
                INSERT INTO settings (setting_name, setting_value, setting_description) 
                VALUES (?, ?, ?) 
                ON DUPLICATE KEY UPDATE 
                setting_value = VALUES(setting_value), 
                updated_at = CURRENT_TIMESTAMP
            ");
            
            foreach ($settings as $name => $value) {
                $description = $this->getSettingDescription($name);
                $stmt->execute([$name, $value, $description]);
            }
            
            $_SESSION['success'] = 'Currency settings updated successfully!';
            header('Location: ?app_route=currency_settings');
            exit;
            
        } catch (Exception $e) {
            $_SESSION['error'] = 'Failed to save currency settings: ' . $e->getMessage();
            header('Location: ?app_route=currency_settings');
            exit;
        }
    }
    
    /**
     * Get setting description
     */
    private function getSettingDescription($setting_name)
    {
        $descriptions = [
            'currency_code' => 'Default currency code for the system',
            'currency_symbol' => 'Currency symbol to display',
            'currency_position' => 'Position of currency symbol (before/after)'
        ];
        
        return $descriptions[$setting_name] ?? '';
    }
    
    /**
     * Get available currencies
     */
    public function getAvailableCurrencies()
    {
        return [
            'USD' => ['name' => 'US Dollar', 'symbol' => '$'],
            'EUR' => ['name' => 'Euro', 'symbol' => '€'],
            'GBP' => ['name' => 'British Pound', 'symbol' => '£'],
            'JPY' => ['name' => 'Japanese Yen', 'symbol' => '¥'],
            'AUD' => ['name' => 'Australian Dollar', 'symbol' => 'A$'],
            'CAD' => ['name' => 'Canadian Dollar', 'symbol' => 'C$'],
            'CHF' => ['name' => 'Swiss Franc', 'symbol' => 'CHF'],
            'CNY' => ['name' => 'Chinese Yuan', 'symbol' => '¥'],
            'INR' => ['name' => 'Indian Rupee', 'symbol' => '₹'],
            'BRL' => ['name' => 'Brazilian Real', 'symbol' => 'R$'],
            'RUB' => ['name' => 'Russian Ruble', 'symbol' => '₽'],
            'KRW' => ['name' => 'South Korean Won', 'symbol' => '₩'],
            'SGD' => ['name' => 'Singapore Dollar', 'symbol' => 'S$'],
            'HKD' => ['name' => 'Hong Kong Dollar', 'symbol' => 'HK$'],
            'NZD' => ['name' => 'New Zealand Dollar', 'symbol' => 'NZ$'],
            'SEK' => ['name' => 'Swedish Krona', 'symbol' => 'kr'],
            'NOK' => ['name' => 'Norwegian Krone', 'symbol' => 'kr'],
            'MXN' => ['name' => 'Mexican Peso', 'symbol' => '$'],
            'ZAR' => ['name' => 'South African Rand', 'symbol' => 'R'],
            'TRY' => ['name' => 'Turkish Lira', 'symbol' => '₺'],
            'KES' => ['name' => 'Kenyan Shilling', 'symbol' => 'KSh'],
            'NGN' => ['name' => 'Nigerian Naira', 'symbol' => '₦'],
            'EGP' => ['name' => 'Egyptian Pound', 'symbol' => '£'],
            'GHS' => ['name' => 'Ghanaian Cedi', 'symbol' => '₵'],
            'UGX' => ['name' => 'Ugandan Shilling', 'symbol' => 'USh'],
            'TZS' => ['name' => 'Tanzanian Shilling', 'symbol' => 'TSh'],
            'ETB' => ['name' => 'Ethiopian Birr', 'symbol' => 'Br'],
            'MAD' => ['name' => 'Moroccan Dirham', 'symbol' => 'MAD'],
        ];
    }
}
