<?php
// includes/dingconnect.php
// DingConnect International Recharge API
// Authentication: api_key as query parameter

function _dingCall($endpoint, $params = [], $method = 'GET') {
    $api_key = getSetting('ding_api_key');
    if (!$api_key) return ['error' => 'API Key সেট নেই!'];

    $base = 'https://api.dingconnect.com/api/V1/';

    $url = $base . $endpoint;

    $ch = curl_init();

    if ($method === 'GET') {
        if ($params) $url .= '?' . http_build_query($params);
        curl_setopt($ch, CURLOPT_HTTPGET, true);
    } else {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
    }

    curl_setopt_array($ch, [
        CURLOPT_URL            => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 90,
        CURLOPT_CONNECTTIMEOUT => 20,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json',
            'Accept: application/json',
            'api_key: ' . $api_key,  // ✅ Header হিসেবে পাঠাও
        ],
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlErr  = curl_error($ch);
    curl_close($ch);

    if ($curlErr) return ['error' => 'cURL Error: ' . $curlErr];
    if (!$response) return ['error' => 'Empty response (HTTP ' . $httpCode . ')'];

    $data = json_decode($response, true);
    if ($data === null) return ['error' => 'Invalid JSON (HTTP '.$httpCode.'): '.substr($response,0,300)];

    // Log
    try {
        $db = getDB();
        $logP = $params; unset($logP['api_key']); // API key লগে রাখব না
        $db->prepare("INSERT INTO api_logs (operator, request_data, response_data, status_code) VALUES (?,?,?,?)")
           ->execute(['ding_'.$endpoint, json_encode($logP), $response, $httpCode]);
    } catch(Exception $e) {}

    return $data;
}

// ✅ Get Balance
function dingGetBalance() {
    return _dingCall('GetBalance');
}

// ✅ Get Products
function dingGetProducts($country_iso = '', $account_number = '') {
    $params = [];
    if ($country_iso)    $params['country_isos']   = $country_iso;
    if ($account_number) $params['account_number'] = $account_number;
    return _dingCall('GetProducts', $params);
}

// ✅ Get Countries
function dingGetCountries() {
    return _dingCall('GetCountries');
}

// ✅ Get Providers
function dingGetProviders($country_iso = '') {
    $params = $country_iso ? ['country_isos' => $country_iso] : [];
    return _dingCall('GetProviders', $params);
}

// ✅ Estimate Prices
function dingEstimatePrice($sku_code, $send_value) {
    return _dingCall('EstimatePrices', [
        'sku_codes'   => $sku_code,
        'send_values' => $send_value,
    ]);
}

// ✅ Send Transfer (Actual Recharge/PIN Purchase)
// PIN products এ AccountNumber = dummy number দিলেই হয়
// RedemptionMechanism = ReadReceipt হলে PIN ReceiptText এ আসে
function dingSendTransfer($account_number, $sku_code, $send_value, $distributor_ref, $validate_only = false) {
    $params = [
        'AccountNumber'  => $account_number,
        'SkuCode'        => $sku_code,
        'SendValue'      => floatval($send_value),
        'DistributorRef' => $distributor_ref,
        'ValidateOnly'   => $validate_only,
    ];
    return _dingCall('SendTransfer', $params, 'POST');
}

// ✅ Buy PIN Card (ReadReceipt products)
// PIN products এ AccountNumber লাগে না — dummy দিলেই হয়
function dingBuyPin($sku_code, $send_value, $distributor_ref) {
    $params = [
        'AccountNumber'  => '0000000000', // PIN products এ dummy number
        'SkuCode'        => $sku_code,
        'SendValue'      => floatval($send_value),
        'DistributorRef' => $distributor_ref,
        'ValidateOnly'   => false,
    ];
    $result = _dingCall('SendTransfer', $params, 'POST');

    // PIN extract from ReceiptText
    if (isset($result['ResultCode']) && $result['ResultCode'] == 1) {
        $transfer = $result['TransferRecord'] ?? [];
        $receiptText = $transfer['ReceiptText'] ?? '';
        $receiptParams = $transfer['ReceiptParams'] ?? [];

        // PIN from ReceiptParams (structured)
        $pin = null;
        foreach ($receiptParams as $rp) {
            if (in_array(strtolower($rp['Name'] ?? ''), ['pin','pin_code','pincode','code'])) {
                $pin = $rp['Value'] ?? null;
                break;
            }
        }

        // Fallback: extract from ReceiptText
        if (!$pin && $receiptText) {
            if (preg_match('/\b([0-9]{8,20})\b/', $receiptText, $m)) {
                $pin = $m[1];
            } else {
                $pin = $receiptText; // full text as PIN
            }
        }

        $result['_pin_code']     = $pin;
        $result['_receipt_text'] = $receiptText;
    }

    return $result;
}

// ✅ Get Transfer Status
function dingGetTransferStatus($distributor_ref) {
    return _dingCall('GetTransferRecords', ['distributor_ref' => $distributor_ref]);
}

// ✅ Check configuration
function dingIsConfigured() {
    return !empty(getSetting('ding_api_key'));
}

// ✅ Format phone for international
function dingFormatPhone($phone, $country_code = '+880') {
    $phone = preg_replace('/[^0-9]/', '', $phone);
    if (substr($phone, 0, 1) === '0') $phone = substr($phone, 1);
    return $country_code . $phone;
}
