<?php
// includes/successtopup.php
// Success TopUp API Integration

// ST Operator codes (from official docs: GP, RB, AT, BL, TT, SK, BT)
define('ST_OPERATORS', [
    'GP'   => 'GP',    // Grameenphone
    'BL'   => 'BL',    // Banglalink
    'RB'   => 'RB',    // Robi
    'ROBI' => 'RB',    // Robi (alt)
    'AL'   => 'AT',    // Airtel → AT in ST
    'AR'   => 'AT',    // Airtel alt
    'AT'   => 'AT',    // Airtel (direct)
    'TT'   => 'TT',    // Teletalk
    'SK'   => 'SK',    // Skitto
    'BT'   => 'BT',    // Brilliant
]);

function successTopupRecharge($phone, $amount, $operator_code, $trxid, $type = 'prepaid') {
    $api_key    = getSetting('successtopup_key');
    $api_secret = getSetting('successtopup_secret');

    if (!$api_key || !$api_secret) {
        return ['result' => false, 'message' => 'API credentials not configured'];
    }

    // Map operator code to ST format
    $stCode = ST_OPERATORS[strtoupper($operator_code)] ?? null;
    if (!$stCode) {
        return ['result' => false, 'message' => 'Operator not supported by SuccessTopUp: '.$operator_code];
    }

    $data = [
        'number'               => $phone,
        'type'                 => $type,
        'operator'             => $stCode,
        'amount'               => $amount,
        'trxid'                => $trxid,
        'successtopup_key'    => $api_key,
        'successtopup_secret' => $api_secret,
    ];

    return _stApiCall('https://api.successtopup.com/api/recharge', $data);
}

function successTopupDrive($phone, $package_id, $operator_code, $trxid) {
    $api_key    = getSetting('successtopup_key');
    $api_secret = getSetting('successtopup_secret');

    if (!$api_key || !$api_secret) {
        return ['result' => false, 'message' => 'API credentials not configured'];
    }

    // Map operator code to ST format
    $stCode = ST_OPERATORS[strtoupper($operator_code)] ?? strtoupper($operator_code);

    $data = [
        'number'               => $phone,
        'type'                 => 'prepaid',
        'operator'             => $stCode,
        'package_id'           => $package_id,
        'trxid'                => $trxid,
        'successtopup_key'    => $api_key,
        'successtopup_secret' => $api_secret,
    ];

    return _stApiCall('https://api.successtopup.com/api/recharge', $data);
}

function successTopupStatus($trxid) {
    $api_key    = getSetting('successtopup_key');
    $api_secret = getSetting('successtopup_secret');

    $data = [
        'trxid'                => $trxid,
        'successtopup_key'    => $api_key,
        'successtopup_secret' => $api_secret,
    ];

    return _stApiCall('https://api.successtopup.com/api/status', $data);
}

function successTopupBalance() {
    $api_key    = getSetting('successtopup_key');
    $api_secret = getSetting('successtopup_secret');

    $data = [
        'successtopup_key'    => $api_key,
        'successtopup_secret' => $api_secret,
    ];

    return _stApiCall('https://api.successtopup.com/api/balance', $data);
}

function successTopupDriveList($operator = '', $type = '') {
    $api_key    = getSetting('successtopup_key');
    $api_secret = getSetting('successtopup_secret');

    $data = [
        'successtopup_key'    => $api_key,
        'successtopup_secret' => $api_secret,
    ];
    if ($operator) $data['operator'] = strtoupper($operator);
    if ($type)     $data['type']     = $type;

    return _stApiCall('https://api.successtopup.com/api/drives', $data);
}

function _stApiCall($url, $data) {
    // cURL দিয়ে চেষ্টা করো
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => json_encode($data),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_CONNECTTIMEOUT => 15,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTPHEADER     => [
                'Content-Type: application/json',
                'Accept: application/json',
            ],
        ]);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlErr  = curl_error($ch);
        $curlErrNo = curl_errno($ch);
        curl_close($ch);

        if ($curlErr || !$response) {
            return ['result' => false, 'message' => 'cURL Error #'.$curlErrNo.': '.$curlErr];
        }

        $decoded = json_decode($response, true);
        if (!$decoded) {
            return ['result' => false, 'message' => 'Invalid response (HTTP '.$httpCode.'): '.substr($response, 0, 200)];
        }

        // Log
        try {
            $db = getDB();
            $logData = $data;
            unset($logData['successtopup_secret']); // secret log করো না
            $db->prepare("INSERT INTO api_logs (operator, request_data, response_data, status_code) VALUES (?,?,?,?)")
               ->execute(['successtopup', json_encode($logData), $response, $httpCode]);
        } catch (Exception $e) {}

        return $decoded;
    }

    // cURL নেই — file_get_contents দিয়ে চেষ্টা
    $context = stream_context_create([
        'http' => [
            'method'  => 'POST',
            'header'  => "Content-Type: application/json\r\nAccept: application/json\r\n",
            'content' => json_encode($data),
            'timeout' => 30,
            'ignore_errors' => true,
        ],
        'ssl' => [
            'verify_peer'      => false,
            'verify_peer_name' => false,
        ],
    ]);

    $response = @file_get_contents($url, false, $context);
    if (!$response) {
        return ['result' => false, 'message' => 'Connection failed. cURL ও file_get_contents দুটোই কাজ করছে না। Hosting থেকে outbound connection allow করুন।'];
    }

    $decoded = json_decode($response, true);
    return $decoded ?: ['result' => false, 'message' => 'Invalid response: '.substr($response, 0, 200)];
}
