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

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

// LG‑Pay config
define('LG_APP_ID', 'PKR3051'); // ← Replace this
define('LG_APP_SECRET', 'DD3UsTt84Wsf6pQAw9SH5dgbzbVd8xYX'); // ← Replace this
define('LG_TRADE_TYPE', 'PKRPH');
define('LG_CALLBACK_URL', 'https://fastpay.rdnslvhost.in.net/api/lg_callback.php');

// Validate inputs
$merchantKey = $_POST['merchant_key'] ?? '';
$amount = floatval($_POST['amount'] ?? 0);
$currency = $_POST['currency'] ?? 'pkr';
$txn_id = $_POST['txn_id'] ?? '';

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

// Get user info
$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'] ?? 'pkr';
$fee_percent = isset($user['payin_fee']) ? floatval($user['payin_fee']) : 0; // ✅ now from users table

// Get conversion rate (payin_rate) from user_currencies
$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'];

// Calculate fee and final amount
$converted = $amount * $rate;
$fee = ($converted * $fee_percent) / 100;
$final_amount = $converted - $fee;


// Prepare LG-Pay request
$money = intval($amount * 100); // money in cents
$params = [
    'app_id' => LG_APP_ID,
    'trade_type' => LG_TRADE_TYPE,
    'order_sn' => $txn_id,
    'money' => $money,
    'notify_url' => LG_CALLBACK_URL,
    'return_url' => 'https://fastpay.rdnslvhost.in.net/api/lg_callback.php'
];

// Build sign
ksort($params);
$sign_string = '';
foreach ($params as $key => $val) {
    $sign_string .= "$key=$val&";
}
$sign_string .= "key=" . LG_APP_SECRET;
$sign = strtoupper(md5($sign_string));
$params['sign'] = $sign;

// Send request to LG‑Pay
$ch = curl_init("https://www.lg-pay.com/api/order/create");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);

$response = curl_exec($ch);
curl_close($ch);
$responseData = json_decode($response, true);

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

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

// Store transaction
$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 (after fee cut)
    'pending',          // status
    'Fast-Pay',         // payment_gateway
    null,               // reference
    null,               // admin_id
    null,               // user_note
    $default_currency,  // currency
    $fee,               // ✅ fee value inserted correctly
    $currency,          // from_currency
    $default_currency,  // to_currency
    $rate,              // conversion_rate
    0                   // webhook_sent
]);


// Return success with redirect URL
echo json_encode([
    "status" => "redirect",
    "message" => "Redirect to payment",
    "payment_url" => $payment_url
]);
?>
