<?php
/**
 * Fix UddoktaPay Settings Script v2
 * 
 * This script will automatically fix common UddoktaPay configuration issues:
 * 1. Fix incorrect base URL (when set to an endpoint instead of base domain)
 * 2. Ensure proper configuration values
 */

require_once 'config/database.php';

echo "Checking and fixing UddoktaPay settings...\n";

try {
    // Get current settings
    $stmt = $pdo->query("SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE 'uddoktapay_%'");
    $results = $stmt->fetchAll();
    
    echo "Current UddoktaPay settings:\n";
    $settings = [];
    foreach ($results as $row) {
        echo "  " . $row['setting_key'] . " = " . $row['setting_value'] . "\n";
        $settings[$row['setting_key']] = $row['setting_value'];
    }
    
    // Check if base URL is incorrectly set to an endpoint
    if (isset($settings['uddoktapay_base_url'])) {
        $currentBaseUrl = $settings['uddoktapay_base_url'];
        
        if (strpos($currentBaseUrl, '/api/') !== false || strpos($currentBaseUrl, '/verify-payment') !== false) {
            echo "\nFixing malformed UddoktaPay base URL...\n";
            echo "Current base URL: " . $currentBaseUrl . "\n";
            
            // Extract just the domain part
            $parsedUrl = parse_url($currentBaseUrl);
            if (isset($parsedUrl['scheme']) && isset($parsedUrl['host'])) {
                $correctBaseUrl = $parsedUrl['scheme'] . '://' . $parsedUrl['host'];
                echo "Corrected base URL: " . $correctBaseUrl . "\n";
                
                // Update in database
                $stmt = $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = 'uddoktapay_base_url'");
                $stmt->execute([$correctBaseUrl]);
                
                echo "UddoktaPay base URL updated successfully!\n";
            } else {
                echo "Could not parse base URL. Please manually update it to https://api.uddoktapay.com\n";
            }
        } else {
            echo "\nUddoktaPay base URL appears to be correctly configured.\n";
        }
    } else {
        echo "\nUddoktaPay base URL not found in settings. Setting to default...\n";
        // Insert default value
        $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES ('uddoktapay_base_url', 'https://api.uddoktapay.com')");
        $stmt->execute();
        echo "Default UddoktaPay base URL set.\n";
    }
    
    echo "\nUddoktaPay settings fix completed.\n";
    echo "Please test a payment to verify the fix.\n";
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
?>