<?php
// ECARE TECHNOLOGY API Integration

define('ECARE_URL', getSetting('ecare_url') ?: 'http://118.179.129.98/myportal/api/rechargeapi/recharge_api_thirdparty.php');

// ECARE Operator codes (numeric)
define('ECARE_OPERATORS', [
    'GP'   => ['code'=>'7', 'name'=>'Grameenphone'],
    'BL'   => ['code'=>'4', 'name'=>'Banglalink'],
    'RB'   => ['code'=>'8', 'name'=>'Robi'],
    'ROBI' => ['code'=>'8', 'name'=>'Robi'],
    'AL'   => ['code'=>'6', 'name'=>'Airtel'],
    'AR'   => ['code'=>'6', 'name'=>'Airtel'],
    'TT'   => ['code'=>'5', 'name'=>'Teletalk'],
]);

// Number types
define('ECARE_NUM_TYPES', [
    'prepaid'   => '1',
    'postpaid'  => '2',
    'skitto'    => '3',
    'powerload' => '4',
]);

function ecareGet($params) {
    $access_id   = getSetting('ecare_username') ?: '';
    $access_pass = getSetting('ecare_password') ?: '';

    if (!$access_id || !$access_pass) {
        return ['STATUS'=>'FAILED','MESSAGE'=>'ECARE credentials not configured'];
    }

    $params = array_merge([
        'access_id'   => $access_id,
        'access_pass' => $access_pass,
    ], $params);

    $url = ECARE_URL . '?' . http_build_query($params);

    $res = null;

    // Try cURL first
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_CONNECTTIMEOUT => 15,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTPHEADER     => ['Accept: application/json', 'User-Agent: Mozilla/5.0'],
        ]);
        $res = curl_exec($ch);
        $err = curl_error($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($err || !$res) {
            // Log error
            try { $db = getDB(); $db->prepare("INSERT INTO api_logs (operator,request_data,response_data,status_code) VALUES (?,?,?,?)")->execute(['ecare_err', json_encode($params), 'cURL Error: '.$err, 0]); } catch(Exception $e) {}
            return ['STATUS'=>'FAILED','MESSAGE'=>'Connection error: '.$err];
        }
    } else {
        // Fallback: file_get_contents
        $context = stream_context_create([
            'http' => ['timeout'=>30, 'ignore_errors'=>true],
            'ssl'  => ['verify_peer'=>false, 'verify_peer_name'=>false],
        ]);
        $res = @file_get_contents($url, false, $context);
        if (!$res) {
            return ['STATUS'=>'FAILED','MESSAGE'=>'Connection failed - cURL not available'];
        }
    }

    // Parse JSON response
    $data = json_decode($res, true);
    if ($data) {
        try { $db = getDB(); $db->prepare("INSERT INTO api_logs (operator,request_data,response_data,status_code) VALUES (?,?,?,?)")->execute(['ecare', json_encode($params), $res, 200]); } catch(Exception $e) {}
        return $data;
    }

    // Parse key=value lines (fallback)
    $data = [];
    foreach (explode("\n", trim($res)) as $line) {
        $line = trim($line);
        if (strpos($line,'=') !== false) {
            [$k,$v] = explode('=', $line, 2);
            $data[trim($k)] = trim($v);
        }
    }

    if (!empty($data)) {
        try { $db = getDB(); $db->prepare("INSERT INTO api_logs (operator,request_data,response_data,status_code) VALUES (?,?,?,?)")->execute(['ecare', json_encode($params), $res, 200]); } catch(Exception $e) {}
        return $data;
    }

    return ['STATUS'=>'FAILED','MESSAGE'=>'Invalid response format','RAW'=>substr($res,0,300)];
}

// Recharge
function ecareRecharge($phone, $amount, $operatorCode, $numType, $refId) {
    $opKey = strtoupper($operatorCode);
    $ops   = ECARE_OPERATORS;
    $opNum = isset($ops[$opKey]) ? $ops[$opKey]['code'] : '7';

    $numTypeCode = ['prepaid'=>'1','postpaid'=>'2','skitto'=>'3','powerload'=>'4'][strtolower($numType)] ?? '1';

    $res = ecareGet([
        'service'     => 'MRC',
        'operator'    => $opNum,
        'number_type' => $numTypeCode,
        'number'      => $phone,
        'amount'      => $amount,
        'refid'       => $refId,
    ]);

    // Normalize to standard format
    $status   = $res['STATUS'] ?? 'FAILED';
    $rcStatus = $res['RECHARGE_STATUS'] ?? '';
    // result = true ONLY on final SUCCESS, not RECEIVED (RECEIVED = sent, pending confirmation)
    $success  = ($status === 'OK' && $rcStatus === 'SUCCESS');
    $received = ($status === 'OK' && $rcStatus === 'RECEIVED');

    return [
        'result'    => $success,
        'received'  => $received,
        'status'    => $status,
        'rc_status' => $rcStatus,
        'trxid'     => $res['TRXID'] ?? $res['RECHARGE_TRXID'] ?? '',
        'message'   => $res['MESSAGE'] ?? '',
        'raw'       => $res,
    ];
}

// Status check
function ecareStatus($refId) {
    $res = ecareGet([
        'service' => 'MRCSTATUS',
        'refid'   => $refId,
    ]);
    return [
        'status'    => $res['STATUS'] ?? 'FAILED',
        'rc_status' => $res['RECHARGE_STATUS'] ?? '',
        'trxid'     => $res['RECHARGE_TRXID'] ?? '',
        'message'   => $res['MESSAGE'] ?? '',
        'raw'       => $res,
    ];
}

// Balance check
function ecareBalance() {
    $res = ecareGet(['service'=>'BLCK']);
    return [
        'status'          => $res['STATUS'] ?? 'FAILED',
        'main_balance'    => $res['MAIN_BALANCE'] ?? '0',
        'stock_balance'   => $res['STOCK_BALANCE'] ?? '0',
        'commission_type' => $res['COMMISSION_TYPE'] ?? '',
        'commission_rate' => $res['COMMISSION_RATE'] ?? '0',
        'message'         => $res['MESSAGE'] ?? '',
        'raw'             => $res,
    ];
}

// Offer pack list
function ecareOfferPacks($operatorCode = '', $phone = '') {
    $params = ['service'=>'OFFERPACK'];
    if ($operatorCode) {
        $opKey = strtoupper($operatorCode);
        $ops   = ECARE_OPERATORS;
        $opNum = isset($ops[$opKey]) ? $ops[$opKey]['code'] : '7';
        $params['operator'] = $opNum;
    }
    if ($phone) $params['number'] = $phone;
    return ecareGet($params);
}
