<?php
// Handle Payout (Payment on Behalf)
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");

require_once('../../database/config.php');
require_once('config.php');

// Security check: Ensure only authorized admins/users can call this
// session_start();
// if(!isset($_SESSION['username'])){ die("Unauthorized"); }

$input = json_decode(file_get_contents("php://input"), true);

$amount = isset($input['amount']) ? number_format((float)$input['amount'], 2, '.', '') : '0.00';
$accountName = isset($input['account_name']) ? $input['account_name'] : '';
$accountNumber = isset($input['account_number']) ? $input['account_number'] : '';
$ifscCode = isset($input['ifsc_code']) ? $input['ifsc_code'] : '';
$bankName = isset($input['bank_name']) ? $input['bank_name'] : ''; // Optional

if($amount <= 0 || empty($accountNumber) || empty($ifscCode)) {
    echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
    exit;
}

// Generate Order ID
$merchantOrderId = 'PO' . time() . rand(1000, 9999);

$params = [
    'merchantId' => $rspay_merchant_id,
    'merchantOrderId' => $merchantOrderId,
    'amount' => $amount,
    'type' => 1, // 1: Bank card/IMPS
    'paymentCurrency' => 'INR',
    'notifyUrl' => $payout_callback_url,
    'accountName' => $accountName, // Optional but good to pass
    'accountNumber' => $accountNumber,
    'ifscCode' => $ifscCode,
    'ext' => 'payout',
];

// Optional fields
if(!empty($bankName)) {
    $params['bankName'] = $bankName; // Only needed for some countries like Thailand
}

// Generate Signature
$sign = generateRspaySign($params, $rspay_key);
$params['sign'] = $sign;

// Log Request
// file_put_contents('payout_log.txt', "REQ: " . json_encode($params) . "\n", FILE_APPEND);

// Call API
$response = callRspayApi('/apii/out/createOrder', $params);

// Log Response
// file_put_contents('payout_log.txt', "RES: " . json_encode($response) . "\n", FILE_APPEND);

if(isset($response['status']) && $response['status'] == '200') {
    // Payout Initiated Successfully (It is processing)
    
    // Deduct balance from user wallet (Important: Deduct BEFORE confirming success to avoid double spend)
    // Save to DB as 'pending'
    
    echo json_encode([
        'status' => 'success',
        'message' => 'Payout Initiated',
        'order_id' => $merchantOrderId,
        'platform_order_id' => $response['data']['orderId']
    ]);
} else {
    echo json_encode([
        'status' => 'error',
        'message' => isset($response['message']) ? $response['message'] : 'Payout Failed'
    ]);
}
?>
