<?php
class SAPaystackController {
    public function index(): void {
        SuperAuth::requireLogin();
        
        // Get current Paystack settings from database or use defaults
        $paystackSettings = $this->getPaystackSettings();
        
        $pageTitle = 'Paystack Settings';
        ob_start();
        include APP_ROOT . '/views/superadmin/paystack.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/superadmin/layout.php';
    }
    
    public function update(): void {
        SuperAuth::requireLogin();
        Security::checkCsrf();
        
        $environment = $_POST['environment'] ?? 'test';
        
        // Validate inputs
        $publicKey = trim($_POST["{$environment}_public_key"] ?? '');
        $secretKey = trim($_POST["{$environment}_secret_key"] ?? '');
        
        if (empty($publicKey) || empty($secretKey)) {
            flash('error', 'Both public and secret keys are required');
            redirect('superadmin/paystack');
            return;
        }
        
        // Validate key formats
        if ($environment === 'test') {
            if (!str_starts_with($publicKey, 'pk_test_') || !str_starts_with($secretKey, 'sk_test_')) {
                flash('error', 'Invalid test key format. Keys must start with pk_test_ and sk_test_');
                redirect('superadmin/paystack');
                return;
            }
        } else {
            if (!str_starts_with($publicKey, 'pk_live_') || !str_starts_with($secretKey, 'sk_live_')) {
                flash('error', 'Invalid live key format. Keys must start with pk_live_ and sk_live_');
                redirect('superadmin/paystack');
                return;
            }
        }
        
        try {
            // Save settings to database
            $this->savePaystackSettings($environment, [
                'public_key' => $publicKey,
                'secret_key' => $secretKey,
                'callback_url' => APP_URL . '/billing/callback',
                'webhook_url' => APP_URL . '/billing/webhook'
            ]);
            
            flash('success', ucfirst($environment) . ' Paystack settings updated successfully');
        } catch (Exception $e) {
            flash('error', 'Failed to update Paystack settings: ' . $e->getMessage());
        }
        
        redirect('superadmin/paystack');
    }
    
    public function updateGlobal(): void {
        SuperAuth::requireLogin();
        Security::checkCsrf();
        
        $environment = $_POST['environment'] ?? 'test';
        $currency = $_POST['currency'] ?? 'NGN';
        
        // Validate inputs
        if (!in_array($environment, ['test', 'live'])) {
            flash('error', 'Invalid environment');
            redirect('superadmin/paystack');
            return;
        }
        
        if (!in_array($currency, ['NGN', 'USD', 'GHS'])) {
            flash('error', 'Invalid currency');
            redirect('superadmin/paystack');
            return;
        }
        
        try {
            // Save global settings
            $this->saveGlobalSettings([
                'environment' => $environment,
                'currency' => $currency
            ]);
            
            flash('success', 'Global Paystack settings updated successfully');
        } catch (Exception $e) {
            flash('error', 'Failed to update global settings: ' . $e->getMessage());
        }
        
        redirect('superadmin/paystack');
    }
    
    private function getPaystackSettings(): array {
        // Check if settings table exists and create if needed
        try {
            $stmt = db()->prepare("SELECT 1 FROM system_settings LIMIT 1");
            $stmt->execute();
        } catch (Exception $e) {
            // Table doesn't exist, create it
            $this->createSettingsTable();
        }
        
        // Get settings from database
        try {
            $stmt = db()->prepare("SELECT setting_key, setting_value FROM system_settings WHERE setting_key LIKE 'paystack_%'");
            $stmt->execute();
            $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
        } catch (Exception $e) {
            // If query fails, return empty settings
            $settings = [];
        }
        
        // Parse settings into nested array
        $paystackSettings = [
            'test' => [
                'public_key' => $settings['paystack_test_public_key'] ?? '',
                'secret_key' => $settings['paystack_test_secret_key'] ?? '',
                'callback_url' => $settings['paystack_test_callback_url'] ?? APP_URL . '/billing/callback',
                'webhook_url' => $settings['paystack_test_webhook_url'] ?? APP_URL . '/billing/webhook'
            ],
            'live' => [
                'public_key' => $settings['paystack_live_public_key'] ?? '',
                'secret_key' => $settings['paystack_live_secret_key'] ?? '',
                'callback_url' => $settings['paystack_live_callback_url'] ?? APP_URL . '/billing/callback',
                'webhook_url' => $settings['paystack_live_webhook_url'] ?? APP_URL . '/billing/webhook'
            ],
            'environment' => $settings['paystack_environment'] ?? 'test',
            'currency' => $settings['paystack_currency'] ?? 'NGN'
        ];
        
        return $paystackSettings;
    }
    
    private function savePaystackSettings(string $environment, array $settings): void {
        db()->beginTransaction();
        try {
            foreach ($settings as $key => $value) {
                $settingKey = "paystack_{$environment}_{$key}";
                $stmt = db()->prepare("
                    INSERT INTO system_settings (setting_key, setting_value) 
                    VALUES (?, ?) 
                    ON DUPLICATE KEY UPDATE setting_value = ?
                ");
                $stmt->execute([$settingKey, $value, $value]);
            }
            db()->commit();
        } catch (Exception $e) {
            db()->rollBack();
            throw $e;
        }
    }
    
    private function saveGlobalSettings(array $settings): void {
        db()->beginTransaction();
        try {
            foreach ($settings as $key => $value) {
                $settingKey = "paystack_{$key}";
                $stmt = db()->prepare("
                    INSERT INTO system_settings (setting_key, setting_value) 
                    VALUES (?, ?) 
                    ON DUPLICATE KEY UPDATE setting_value = ?
                ");
                $stmt->execute([$settingKey, $value, $value]);
            }
            db()->commit();
        } catch (Exception $e) {
            db()->rollBack();
            throw $e;
        }
    }
    
    private function createSettingsTable(): void {
        $sql = "
            CREATE TABLE IF NOT EXISTS `system_settings` (
              `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
              `setting_key` VARCHAR(100) NOT NULL UNIQUE,
              `setting_value` TEXT,
              `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
              `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
              PRIMARY KEY (`id`),
              KEY `idx_setting_key` (`setting_key`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
        ";
        db()->exec($sql);
    }
    
    public function testConnection(): void {
        SuperAuth::requireLogin();
        Security::checkCsrf();
        
        $environment = $_POST['environment'] ?? 'test';
        $settings = $this->getPaystackSettings();
        
        $publicKey = $settings[$environment]['public_key'] ?? '';
        $secretKey = $settings[$environment]['secret_key'] ?? '';
        
        if (empty($publicKey) || empty($secretKey)) {
            echo json_encode(['success' => false, 'message' => 'API keys not configured']);
            exit;
        }
        
        // Test connection to Paystack API
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://api.paystack.co/transaction/verify');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $secretKey,
            'Content-Type: application/json'
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode === 200) {
            echo json_encode(['success' => true, 'message' => 'Connection successful']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Connection failed: Invalid API keys']);
        }
        exit;
    }
}
