<?php
// This file contains functions to process transactions through the active gateway selected in the admin panel.
require_once __DIR__ . '/mock_api.php'; // Needed for the default mock functions.

/**
 * এটি একটি सहायक ফাংশন যা cURL ব্যবহার করে বিকাশের API-তে কল পাঠায়।
 * @param string $url        - বিকাশের API এন্ডপয়েন্ট URL।
 * @param string $post_data  - পাঠানোর জন্য JSON ডেটা।
 * @param array $headers     - HTTP হেডার।
 * @return array             - API থেকে প্রাপ্ত উত্তর।
 */
function make_bkash_api_call($url, $post_data, $headers) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    // SSL ভেরিফিকেশন (লাইভ সার্ভারের জন্য গুরুত্বপূর্ণ)
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // ডেভেলপমেন্টের সময় false রাখুন, লাইভে true করে দিন

    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);

    if ($error) {
        return ['curl_error' => $error];
    }
    $decoded_response = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        // If response is not valid JSON, return the raw response for debugging
        return ['raw_response' => $response];
    }
    return $decoded_response;
}

/**
 * বিকাশের "Add Money" পেমেন্ট প্রক্রিয়া শুরু করে।
 */
function initiateBkashPayment($conn, $amount, $user_id) {
    // 1. ডাটাবেজ থেকে বিকাশের ক্রেডেনশিয়াল (তথ্য) সংগ্রহ করা
    $gateway = $conn->query("SELECT * FROM api_gateways WHERE gateway_name = 'bKash'")->fetch_assoc();
    if (!$gateway || empty($gateway['api_key'])) {
        return ['status' => 'error', 'message' => 'bKash gateway credentials not configured in the admin panel.'];
    }

    // বিকাশ ডকুমেন্টেশন অনুযায়ী URL সেট করা (এটি উদাহরণ, আপনার ডকুমেন্টেশন দেখুন)
    // Sandbox URL: https://tokenized.sandbox.bka.sh/v1.2.0-beta/tokenized
    // Live URL: https://tokenized.pay.bka.sh/v1.2.0-beta/tokenized
    $base_url   = $gateway['api_url'] ?? "https://tokenized.sandbox.bka.sh/v1.2.0-beta/tokenized";
    $app_key    = $gateway['api_key'];
    $app_secret = $gateway['secret_key'];
    $username   = $gateway['api_key']; 
    $password   = $gateway['secret_key'];

    try {
        // === ধাপ ১: টোকেন সংগ্রহ করা ===
        $token_url = rtrim($base_url, '/') . "/checkout/token/grant";
        $token_request_body = json_encode(['app_key' => $app_key, 'app_secret' => $app_secret]);
        $token_headers = [
            'Content-Type: application/json',
            'Accept: application/json',
            'username: ' . $username,
            'password: ' . $password
        ];
        
        $token_response = make_bkash_api_call($token_url, $token_request_body, $token_headers);

        if (!isset($token_response['id_token'])) {
            throw new Exception("Could not get bKash token. Response: " . ($token_response['errorMessage'] ?? 'Invalid credentials or URL.'));
        }
        $id_token = $token_response['id_token'];

        // === ধাপ ২: পেমেন্ট তৈরি করা ===
        $create_payment_url = rtrim($base_url, '/') . "/checkout/create";
        // খুবই গুরুত্বপূর্ণ: এই URLটি আপনাকে বিকাশের মার্চেন্ট পোর্টালে যুক্ত করতে হবে
        $callback_url = "https://webtopup.next-pay.shop/telecom/bkash_callback.php"; 
        $invoice_number = 'INV-' . time() . '-' . $user_id;

        $payment_request_body = json_encode([
            'mode'                  => '0011',
            'payerReference'        => $user_id,
            'callbackURL'           => $callback_url,
            'amount'                => $amount,
            'currency'              => 'BDT',
            'intent'                => 'sale',
            'merchantInvoiceNumber' => $invoice_number
        ]);
        $auth_headers = [
            'Content-Type: application/json',
            'Authorization: ' . $id_token,
            'X-App-Key: ' . $app_key
        ];
        
        $payment_response = make_bkash_api_call($create_payment_url, $payment_request_body, $auth_headers);

        if (!isset($payment_response['bkashURL'])) {
            throw new Exception("Could not create bKash payment URL. Response: " . ($payment_response['errorMessage'] ?? 'Unknown error during payment creation.'));
        }
        $bkash_url = $payment_response['bkashURL'];

        return ['status' => 'success', 'bkashURL' => $bkash_url];

    } catch (Exception $e) {
        return ['status' => 'error', 'message' => $e->getMessage()];
    }
}

/**
 * Processes a mobile recharge request using the currently active API gateway.
 */
function processRecharge($conn, $mobile, $amount) {
    $gateway_res = $conn->query("SELECT * FROM api_gateways WHERE is_active = 1 LIMIT 1");
    if ($gateway_res->num_rows === 0) {
        return ['status' => 'error', 'message' => 'কোনো فعال API গেটওয়ে পাওয়া যায়নি।'];
    }
    $gateway = $gateway_res->fetch_assoc();

    switch ($gateway['gateway_name']) {
        case 'bKash':
            // DEVELOPER NOTE: Place bKash Recharge API call logic here.
            return ['status' => 'success', 'transactionId' => 'BKASH_RC_' . time(), 'message' => 'bKash Recharge Successful (Simulated)'];
        case 'SSLCOMMERZ':
            // DEVELOPER NOTE: Place SSLCOMMERZ Recharge API call logic here.
            return ['status' => 'success', 'transactionId' => 'SSL_RC_' . time(), 'message' => 'SSLCOMMERZ Recharge Successful (Simulated)'];
        case 'Mock API':
        default:
            return ['status' => 'success', 'transactionId' => 'MOCK_RC_' . time(), 'message' => 'Mock Recharge Successful'];
    }
}

/**
 * Processes a bill payment request using the currently active API gateway.
 */
function processBillPayment($conn, $biller, $account_number, $amount) {
    $gateway_res = $conn->query("SELECT * FROM api_gateways WHERE is_active = 1 LIMIT 1");
    if ($gateway_res->num_rows === 0) {
        return ['status' => 'error', 'message' => 'কোনো فعال API গেটওয়ে পাওয়া যায়নি।'];
    }
    $gateway = $gateway_res->fetch_assoc();

    switch ($gateway['gateway_name']) {
        case 'bKash':
            // DEVELOPER NOTE: Place bKash Bill Pay API call logic here.
            return ['status' => 'success', 'transactionId' => 'BKASH_BILL_' . time(), 'message' => 'bKash Bill Payment Successful (Simulated)'];
        case 'SSLCOMMERZ':
            // DEVELOPER NOTE: Place SSLCOMMERZ Bill Pay API call logic here.
            return ['status' => 'success', 'transactionId' => 'SSL_BILL_' . time(), 'message' => 'SSLCOMMERZ Bill Payment Successful (Simulated)'];
        case 'Mock API':
        default:
            return processBillPaymentAPI($biller, $account_number, $amount);
    }
}
?>