<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
ob_start();

require '../includes/db.php';
header('Content-Type: application/json');

// New Gateway Config
define('API_APP_NO', 'Bfun'); // Merchant unique code (replace as needed)
define('API_SECRET_KEY', 'neOthtXwQzLDDJipwtPg'); // Merchant secret key (replace as needed)
define('API_BASE_URL', 'https://api.mlpayment.cc/open-api/trade/collection'); // New Gateway order create URL
define('CALLBACK_URL', 'https://kilicow.rdnslvhost.in.net/payinr/callback'); // Your callback URL

// Get POST parameters
$merchantKey = $_POST['merchant_key'] ?? '';
$amount = floatval($_POST['amount'] ?? 0);
$currency = $_POST['currency'] ?? 'inr';  // default 'inr', change as needed
$txn_id = $_POST['txn_id'] ?? '';

if (!$merchantKey || !$amount || !$currency || !$txn_id) {
    echo json_encode(["status" => "error", "message" => "Missing parameters"]);
    exit;
}

// Fetch user from DB
$stmt = $pdo->prepare("SELECT * FROM users WHERE merchant_key = ?");
$stmt->execute([$merchantKey]);
$user = $stmt->fetch();

if (!$user) {
    echo json_encode(["status" => "error", "message" => "Invalid merchant key"]);
    exit;
}

$user_id = $user['id'];
$default_currency = $user['default_currency'] ?? 'inr';

// Currency conversion and fee calculation (same as old logic)
$fee_percent = isset($user['payin_fee']) ? floatval($user['payin_fee']) : 0;

// Fetch currency rate for conversion (old logic)
$stmt = $pdo->prepare("SELECT * FROM user_currencies WHERE user_id = ? AND currency_code = ?");
$stmt->execute([$user_id, $currency]);
$rate_data = $stmt->fetch();

if (!$rate_data) {
    echo json_encode(["status" => "error", "message" => "Currency not supported"]);
    exit;
}

$rate = $rate_data['payin_rate'] ?? 1; // fallback 1 if not set
$converted_amount = $amount * $rate;
$fee = ($converted_amount * $fee_percent) / 100;
$final_amount = $converted_amount - $fee;

// Prepare request params according to new gateway API
$params = [
    "appNo" => API_APP_NO,
    "callbackUrl" => CALLBACK_URL,
    "orderCode" => $txn_id,
    "amount" => number_format($amount, 2, '.', ''), // amount in rupees (original currency amount)
    "name" => $user['name'] ?? 'User',
    "remark" => "Payment for txn $txn_id",
];

// Generate sign string and signature using new gateway secret key
ksort($params);
$sign_str = '';
foreach ($params as $k => $v) {
    $sign_str .= "$k=$v&";
}
$sign_str .= "key=" . API_SECRET_KEY;
$params['sign'] = md5($sign_str);

// Send POST request to new gateway
$ch = curl_init(API_BASE_URL);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$response = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$responseData = json_decode($response, true);

if (!$responseData || !isset($responseData['code']) || $responseData['code'] != 200) {
    echo json_encode([
        "status" => "error",
        "message" => "Payment gateway error",
        "details" => $responseData['msg'] ?? "Unknown error",
    ]);
    exit;
}

// Save transaction and payin request - same DB structure as old code
$stmt = $pdo->prepare("INSERT INTO payin_requests (user_id, amount, currency, converted_amount, rate, status, created_at) VALUES (?, ?, ?, ?, ?, 'pending', NOW())");
$stmt->execute([$user_id, $amount, $currency, $final_amount, $rate]);

$stmt = $pdo->prepare("INSERT INTO transactions (
    txn_id, user_id, type, amount, status, payment_gateway,
    reference, created_at, admin_id, user_note,
    currency, fee, from_currency, to_currency,
    conversion_rate, webhook_sent
) VALUES (
    ?, ?, ?, ?, ?, ?, ?, NOW(), ?, ?, ?, ?, ?, ?, ?, ?
)");
$stmt->execute([
    $txn_id,            // txn_id
    $user_id,           // user_id
    'payin',            // type
    $final_amount,      // amount (converted & fee deducted)
    'pending',          // status
    'KCPI',       // payment_gateway
    null,               // reference
    null,               // admin_id
    null,               // user_note
    $default_currency,  // currency (user default)
    $fee,               // fee
    $currency,          // from_currency (input currency)
    $default_currency,  // to_currency (user default)
    $rate,              // conversion_rate
    0                   // webhook_sent
]);

// Return payment redirect URL to frontend
$payment_url = $responseData['data']['tradeUrl'] ?? null;
if (!$payment_url) {
    echo json_encode(["status" => "error", "message" => "No payment URL returned"]);
    exit;
}

echo json_encode([
    "status" => "redirect",
    "message" => "Redirect to payment",
    "payment_url" => $payment_url,
]);
