<?php
require_once __DIR__ . '/vendor/autoload.php'; // Load Selcom client library
include '../../config.php';

use Selcom\ApigwClient\Client;

// API credentials for Selcom
$vendor = 'TILL61131305';
$apiKey = 'TILL61131305-07df7e8fa1f549d79a3c987842593a2e';
$apiSecret = '8a7679-cf8031-4093a6-98f0dc-6bdf05-15';
$baseUrl = 'https://apigw.selcommobile.com/';
$tid = uniqid('trx_');
$oid = uniqid();

// Initialize Selcom API client
$client = new Client($baseUrl, $apiKey, $apiSecret);

// Ensure required parameters are present
if (!isset($_POST['user_id'], $_POST['loan_id'], $_POST['branch_id'], $_POST['amount'], $_POST['phone_number'], $_POST['network_provider'], $_POST['currency'])) {
    echo json_encode(['status' => 'error', 'message' => 'Missing required parameters.']);
    exit();
}

$userId = $_POST['user_id'];
$branchId = $_POST['branch_id'];
$loanId = $_POST['loan_id'];
$amount = $_POST['amount'];
$phoneNumber = $_POST['phone_number'];
$networkProvider = $_POST['network_provider'];
$currency = $_POST['currency'];

// Create minimal order data payload
$orderMinArray = [
    'vendor' => $vendor,
    'order_id' => $oid,
    'buyer_phone' => $phoneNumber,
    'buyer_email' => "info@bexamicrofinance.com", // Change to the buyer's actual email
    'buyer_name' => "Mteja", // Change to the buyer's actual name
    'amount' => $amount,
    'currency' => $currency,
    'redirect_url' => base64_encode("https://api.bexamicrofinance.com/api_v1/payments/payment_success.php"),
    'cancel_url' => base64_encode("https://api.bexamicrofinance.com/api_v1/payments/cancel_page.php?tid=$tid&oid=$oid"),
    'webhook' => base64_encode("https://api.bexamicrofinance.com/api_v1/payments/marejesho_callback.php?tid=$tid"),
    'buyer_remarks' => "Marejesho ya Bexa Microfinance",
    'merchant_remarks' => "Marejesho ya Bexa Microfinance",
    'no_of_items' => 1
];

// Log order data for debugging
error_log("Order Minimal Array Sent to Selcom: " . print_r($orderMinArray, true));

// Define path for create-order-minimal
$orderMinPath = "/v1/checkout/create-order-minimal";

// Send request to create minimal order
$orderResponse = $client->postFunc($orderMinPath, $orderMinArray);

// Check if the response is valid
if ($orderResponse === false) {
    error_log("Request to Selcom failed. Please check the API client configuration.");
    echo json_encode(['status' => 'error', 'message' => 'Request to Selcom failed.']);
    exit();
}

// Log Selcom API response for debugging
error_log("Response from Selcom create-order-minimal: " . print_r($orderResponse, true));

// Check if order creation was successful
if (isset($orderResponse['result']) && $orderResponse['result'] === 'SUCCESS') {
    // Prepare data for wallet payment
    $walletPaymentArray = [
        'transid' => $tid,
        'order_id' => $oid,
        'msisdn' => $phoneNumber
    ];

    // Log wallet payment data
    error_log("Wallet Payment Array Sent to Selcom: " . print_r($walletPaymentArray, true));

    // Define path for wallet payment
    $walletPaymentPath = "/v1/checkout/wallet-payment";

    // Send request to initiate wallet payment
    $walletResponse = $client->postFunc($walletPaymentPath, $walletPaymentArray);

    // Check if the wallet payment request is valid
    if ($walletResponse === false) {
        error_log("Wallet payment request failed. Please check the API client configuration.");
        echo json_encode(['status' => 'error', 'message' => 'Wallet payment request failed.']);
        exit();
    }

    // Log wallet payment response
    error_log("Response from Selcom wallet-payment: " . print_r($walletResponse, true));

    if (isset($walletResponse['result']) && $walletResponse['result'] === 'SUCCESS') {
        // Insert the pending transaction into `pending_transactions` table
        $insertPending = $conn->prepare("INSERT INTO pending_transactions (loan_id, branch_id, amount, description, user_id, tid) VALUES (?, ?, ?, ?, ?, ?)");
        $description = 'Marejesho';
        $insertPending->bind_param("iissis", $loanId, $branchId,  $amount, $description, $userId, $tid);
        
        if ($insertPending->execute()) {
            echo json_encode(['status' => 'PENDING', 'message' => 'Transaction pending confirmation']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Failed to log pending transaction']);
        }
    } else {
        error_log("Wallet payment failed: " . print_r($walletResponse, true));
        echo json_encode([
            'status' => 'error',
            'message' => isset($walletResponse['message']) ? $walletResponse['message'] : 'Wallet payment failed',
            'details' => $walletResponse
        ]);
    }
} else {
    error_log("Order creation failed: " . (isset($orderResponse['message']) ? $orderResponse['message'] : 'Unknown error'));
    echo json_encode([
        'status' => 'error',
        'message' => isset($orderResponse['message']) ? $orderResponse['message'] : 'Order creation failed',
        'details' => $orderResponse
    ]);
}
?>
