<?php
// Dynamic API handler — supports any REST API for recharge

function customApiCall($apiId, $action, $params = []) {
    $db  = getDB();
    // Support both slug and numeric id
    if(is_numeric($apiId)) {
        $api = $db->prepare("SELECT * FROM custom_apis WHERE id=? AND is_active=1");
    } else {
        $api = $db->prepare("SELECT * FROM custom_apis WHERE slug=? AND is_active=1");
    }
    $api->execute([$apiId]); $api = $api->fetch();
    if (!$api) return ['ok'=>false,'message'=>'API not found or inactive: '.$apiId];

    // Pick endpoint
    $url = match($action) {
        'recharge' => $api['endpoint_recharge'],
        'status'   => $api['endpoint_status'],
        'balance'  => $api['endpoint_balance'],
        'drives'   => $api['endpoint_drives'] ?? '',
        default    => $api['endpoint_recharge'],
    };
    if (!$url) return ['ok'=>false,'message'=>'Endpoint not configured for: '.$action];

    // Build request data — replace {key}, {secret} placeholders
    $baseParams = [
        '{key}'      => $api['api_key'],
        '{secret}'   => $api['api_secret'],
        '{username}' => $api['api_key'],
        '{password}' => $api['api_secret'],
    ];
    // Merge with action params
    $data = [];
    $fieldMap = json_decode($api['field_map'] ?? '{}', true) ?: [];
    foreach ($fieldMap as $ourKey => $apiKey) {
        if (isset($params[$ourKey])) $data[$apiKey] = $params[$ourKey];
    }
    // Always add auth
    $data[$api['auth_key_field']   ?? 'api_key']    = $api['api_key'];
    $data[$api['auth_secret_field'] ?? 'api_secret'] = $api['api_secret'];

    // HTTP call
    $method  = strtoupper($api['http_method'] ?? 'POST');
    $format  = strtolower($api['request_format'] ?? 'json'); // json or form
    $raw     = _customHttpCall($url, $data, $method, $format);

    // Log
    try {
        $logData = $data;
        unset($logData[$api['auth_secret_field'] ?? 'api_secret']);
        $db->prepare("INSERT INTO api_logs (operator,request_data,response_data,status_code) VALUES (?,?,?,?)")
           ->execute([$api['slug'], json_encode($logData), $raw['body'], $raw['code']]);
    } catch(Exception $e) {}

    if (!$raw['ok']) return ['ok'=>false,'message'=>$raw['error']];

    $decoded = json_decode($raw['body'], true);
    if (!$decoded) return ['ok'=>false,'message'=>'Invalid JSON response: '.substr($raw['body'],0,200)];

    // Parse response using response_map
    $rMap = json_decode($api['response_map'] ?? '{}', true) ?: [];
    $successVal = $rMap['success_value'] ?? '1';
    $successKey = $rMap['success_key']   ?? 'result';
    $trxidKey   = $rMap['trxid_key']     ?? 'trxid';
    $balKey     = $rMap['balance_key']   ?? 'balance';
    $msgKey     = $rMap['message_key']   ?? 'message';
    $statusKey  = $rMap['status_key']    ?? 'status';

    // Deep get nested keys like "data.balance"
    function deepGet($arr, $key) {
        $parts = explode('.', $key);
        foreach ($parts as $p) {
            if (!is_array($arr) || !isset($arr[$p])) return null;
            $arr = $arr[$p];
        }
        return $arr;
    }

    $resultVal = deepGet($decoded, $successKey);
    $isSuccess = (string)$resultVal === (string)$successVal || $resultVal === true || $resultVal === 1;

    return [
        'ok'      => $isSuccess,
        'result'  => $resultVal,
        'trxid'   => deepGet($decoded, $trxidKey) ?? '',
        'balance' => deepGet($decoded, $balKey)   ?? '',
        'message' => deepGet($decoded, $msgKey)   ?? '',
        'status'  => deepGet($decoded, $statusKey) ?? '',
        'raw'     => $decoded,
    ];
}

function _customHttpCall($url, $data, $method, $format) {
    if ($method === 'GET') {
        $url .= '?' . http_build_query($data);
        $body = null;
        $headers = [];
    } else {
        if ($format === 'json') {
            $body    = json_encode($data);
            $headers = ['Content-Type: application/json', 'Accept: application/json'];
        } else {
            $body    = http_build_query($data);
            $headers = ['Content-Type: application/x-www-form-urlencoded'];
        }
    }

    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        $opts = [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_CONNECTTIMEOUT => 15,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTPHEADER     => $headers,
        ];
        if ($method === 'POST') { $opts[CURLOPT_POST] = true; $opts[CURLOPT_POSTFIELDS] = $body; }
        curl_setopt_array($ch, $opts);
        $resp = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $err  = curl_error($ch);
        curl_close($ch);
        if ($err || !$resp) return ['ok'=>false,'error'=>'cURL: '.$err,'body'=>'','code'=>0];
        return ['ok'=>true,'body'=>$resp,'code'=>$code,'error'=>''];
    }
    return ['ok'=>false,'error'=>'cURL not available','body'=>'','code'=>0];
}
