<?php
// Fix SMS API URL Configuration
$host = 'localhost';
$dbname = 'school_management';
$username = 'root';
$password = 'root';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);

    echo "=== Fixing SMS API URL Configuration ===\n";

    // Check current API URL
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'non_musking_url'");
    $stmt->execute();
    $currentUrl = $stmt->fetch();

    if (!$currentUrl || empty($currentUrl['setting_value'])) {
        // Set the correct API URL
        $apiUrl = 'https://rest.mrmessaging.net/messages';
        $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
        $stmt->execute(['non_musking_url', $apiUrl, $apiUrl]);
        echo "✅ Fixed: API URL set to $apiUrl\n";
    } else {
        echo "ℹ️  API URL is already set to: {$currentUrl['setting_value']}\n";
    }

    // Also make sure the method is set correctly
    $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
    $stmt->execute(['non_musking_method', 'POST', 'POST']);
    echo "✅ HTTP Method set to POST\n";

    // Verify the fix
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'non_musking_url'");
    $stmt->execute();
    $updatedUrl = $stmt->fetch();
    
    echo "\n=== Verification ===\n";
    echo "API URL: {$updatedUrl['setting_value']}\n";

    echo "\n=== SMS Configuration Status ===\n";
    
    // Check all critical settings
    $stmt = $pdo->prepare("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('non_musking_enabled', 'non_musking_url', 'non_musking_api_key', 'sms_notification_enabled', 'sms_send_application_confirmation', 'sms_send_fee_notifications', 'sms_send_result_notifications', 'sms_send_fee_due_reminders')");
    $stmt->execute();
    $settings = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($settings as $setting) {
        $status = !empty($setting['setting_value']) ? '✅ SET' : '❌ EMPTY';
        if ($setting['setting_key'] == 'non_musking_enabled') {
            $status = $setting['setting_value'] === '1' ? '✅ ENABLED' : '❌ DISABLED';
        }
        echo "{$setting['setting_key']}: $status\n";
    }

    echo "\n✅ SMS API URL configuration fixed!\n";
    echo "All SMS notifications should now work properly.\n";

} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
}
?>