<?php
// Dynamic Paystack configuration - loads keys from database
// This ensures keys are always up-to-date without file modifications

// Function to get Paystack configuration from database
// If $storeId is provided, returns store-specific credentials if available
function getPaystackConfig($force_reload = false, $storeId = null) {
    global $conn;
    
    static $configCache = [];
    $cacheKey = $storeId ? "store_$storeId" : "default";
    
    // Cache the config to avoid multiple database queries
    if (!isset($configCache[$cacheKey]) || $force_reload) {
        $config = [
            'public_key' => getenv('PAYSTACK_PUBLIC_KEY') ?: '',
            'secret_key' => getenv('PAYSTACK_SECRET_KEY') ?: '',
            'base_url' => 'https://api.paystack.co',
            'is_store_specific' => false
        ];
        
        // If store ID is provided, try to load store-specific credentials first
        if ($storeId) {
            try {
                $storeStmt = $conn->prepare("
                    SELECT public_key, secret_key, is_active 
                    FROM store_paystack_credentials 
                    WHERE store_id = ? AND is_active = 1
                ");
                $storeStmt->bind_param("i", $storeId);
                $storeStmt->execute();
                $storeResult = $storeStmt->get_result();
                $storeCreds = $storeResult->fetch_assoc();
                $storeStmt->close();
                
                if ($storeCreds && !empty($storeCreds['public_key']) && !empty($storeCreds['secret_key'])) {
                    $config['public_key'] = $storeCreds['public_key'];
                    $config['secret_key'] = $storeCreds['secret_key'];
                    $config['is_store_specific'] = true;
                }
            } catch (Exception $e) {
                error_log('Error loading store Paystack config: ' . $e->getMessage());
            }
        }
        
        // Load from database if not in environment variables and not store-specific
        if (empty($config['public_key']) || empty($config['secret_key'])) {
            try {
                $stmt = $conn->prepare("SELECT config_key, config_value FROM payment_config WHERE config_key IN ('paystack_public_key', 'paystack_secret_key', 'paystack_base_url')");
                $stmt->execute();
                $result = $stmt->get_result();
                
                while ($row = $result->fetch_assoc()) {
                    switch ($row['config_key']) {
                        case 'paystack_public_key':
                            if (empty($config['public_key'])) {
                            $config['public_key'] = $row['config_value'];
                            }
                            break;
                        case 'paystack_secret_key':
                            if (empty($config['secret_key'])) {
                            $config['secret_key'] = $row['config_value'];
                            }
                            break;
                        case 'paystack_base_url':
                            $config['base_url'] = $row['config_value'];
                            break;
                    }
                }
                $stmt->close();
            } catch (Exception $e) {
                error_log('Error loading Paystack config from database: ' . $e->getMessage());
            }
        }
        
        $configCache[$cacheKey] = $config;
    }
    
    return $configCache[$cacheKey];
}

// Function to clear Paystack configuration cache
function clearPaystackConfigCache() {
    // This will force the next call to getPaystackConfig() to reload from database
    getPaystackConfig(true);
}

// Get current configuration
$paystackConfig = getPaystackConfig();

// Set global variables for backward compatibility
$PAYSTACK_PUBLIC_KEY = $paystackConfig['public_key'];
$PAYSTACK_SECRET_KEY = $paystackConfig['secret_key'];
$PAYSTACK_BASE_URL = $paystackConfig['base_url'];

function paystackVerifyTransaction(string $reference, $storeId = null): array {
    // Get fresh configuration from database (force reload for each transaction)
    // If storeId is provided, use store-specific credentials
    $config = getPaystackConfig(true, $storeId);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $config['base_url'] . '/transaction/verify/' . urlencode($reference));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $config['secret_key'],
        'Content-Type: application/json'
    ]);
    
    // Try with SSL verification first
    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    // If SSL fails, retry without SSL verification (for local development)
    if ($result === false) {
        $error = curl_error($ch);
        error_log('Paystack verify SSL error: ' . $error);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    }
    
    if ($result === false) {
        $error = curl_error($ch);
        curl_close($ch);
        error_log('Paystack verify final error: ' . $error);
        return ['success' => false, 'status' => $httpCode, 'error' => $error];
    }
    curl_close($ch);
    
    $data = json_decode($result, true);
    if (!is_array($data)) {
        error_log('Paystack verify invalid response: ' . $result);
        return ['success' => false, 'status' => $httpCode, 'error' => 'Invalid response from Paystack'];
    }
    
    $success = ($httpCode === 200 && ($data['status'] ?? false) === true);
    error_log('Paystack verify success: ' . ($success ? 'true' : 'false') . ', httpCode: ' . $httpCode . ', data status: ' . ($data['status'] ?? 'null'));
    
    return ['success' => $success, 'status' => $httpCode, 'data' => $data];
}
