<?php
require_once __DIR__ . '/../core/routing.php';

function madr_terminate($country, $network, $payload)
{
    global $conn;

    // 1️⃣ Check Route Governance
    $route = check_route_enabled(
        $conn,
        $payload['from_country'],
        $country
    );

    if (!$route['allowed']) {
        return [
            'status' => 'FAILED',
            'message' => $route['reason']
        ];
    }

    // 2️⃣ Load Active Network Provider
    $stmt = $conn->prepare("
        SELECT provider, provider_channel 
        FROM madr_networks 
        WHERE country_code = ? 
        AND network_name = ?
        AND status = 'ACTIVE'
    ");

    $stmt->bind_param("ss", $country, $network);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();

    if (!$result) {
        return ['status' => 'FAILED', 'message' => 'Network not supported'];
    }

    $provider = $route['preferred_provider'] ?: $result['provider'];
    $channel  = $result['provider_channel'];

    // 3️⃣ Execute Provider
    $response = madr_execute_provider($provider, $country, $channel, $payload);

if ($response['status'] !== 'SUCCESS') {

    // Try alternative providers
    $failover = madr_try_failover($conn, $country, $network, $provider, $payload);

    if ($failover) {
        return $failover;
    }
}

return $response;

}


function madr_execute_provider($provider, $country, $channel, $payload)
{
    switch ($provider) {

        case 'HUBTEL':
            require_once __DIR__ . '/../providers/hubtel.php';
            return hubtel_payout($channel, $payload);

        case 'SASAPAY':
            require_once __DIR__ . '/../providers/sasapay.php';
            return sasapay_payout($country, $channel, $payload);

        default:
            return [
                'status' => 'FAILED',
                'message' => 'Provider not configured'
            ];
    }
}



function madr_try_failover($conn, $country, $network, $failedProvider, $payload)
{
    $stmt = $conn->prepare("
        SELECT provider, provider_channel
        FROM madr_networks
        WHERE country_code = ?
        AND network_name = ?
        AND status = 'ACTIVE'
        AND provider != ?
    ");

    $stmt->bind_param("sss", $country, $network, $failedProvider);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {

        $response = madr_execute_provider(
            $row['provider'],
            $country,
            $row['provider_channel'],
            $payload
        );

        if ($response['status'] === 'SUCCESS') {
            return $response;
        }
    }

    return null;
}
