<?php
require_once 'config/database.php';

try {
    // First, let's check if the api subdomain resolves
    $apiUrl = 'https://api.uddoktapay.com';
    $ch = curl_init($apiUrl);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode >= 200 && $httpCode < 400) {
        // API endpoint is accessible, update the configuration
        $stmt = $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = 'uddoktapay_base_url'");
        $stmt->execute([$apiUrl]);
        echo "UddoktaPay base URL updated to correct API endpoint: " . $apiUrl . "\n";
    } else {
        // API endpoint is not accessible, use the main domain with API path
        $mainUrl = 'https://uddoktapay.com';
        $stmt = $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = 'uddoktapay_base_url'");
        $stmt->execute([$mainUrl]);
        echo "UddoktaPay base URL updated to main domain: " . $mainUrl . "\n";
        echo "Note: API endpoint appears to be inaccessible. You may need to contact your hosting provider about DNS resolution issues.\n";
    }
} catch (Exception $e) {
    echo "Error updating UddoktaPay base URL: " . $e->getMessage() . "\n";
}
?>