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

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

// Naya Gateway Config (apne merchant code aur secret key yahan daalein)
define('MERCHANT_CODE', '1754978283834');  // aapka merchant_code (string)
define('SECRET_KEY', 'b208669f0d6fc2e262786a8a523a61bc');  // merchant secret key
define('API_URL', 'https://pay365.cowpay.in/pay');  // naya API endpoint
define('CALLBACK_URL', 'https://kilicow.rdnslvhost.in.net/payinr/callbackv1'); // aapka callback URL
define('RETURN_URL', 'https://kilicow.rdnslvhost.in.net/payinr/return'); // agar chahiye frontend redirect ke liye

// POST params
$merchantKey = $_POST['merchant_key'] ?? '';
$amount_float = floatval($_POST['amount'] ?? 0);
$currency = $_POST['currency'] ?? 'inr';  // currency code, mostly INR
$txn_id = $_POST['txn_id'] ?? '';

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

// Fetch user from DB (jaise pehle)
$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 = strtoupper($user['default_currency'] ?? 'INR');  // currency uppercase for consistency

// Fee and conversion rate (same as purana logic)
$fee_percent = isset($user['payin_fee']) ? floatval($user['payin_fee']) : 0;

// Currency rate from user_currencies table
$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;
$converted_amount = $amount_float * $rate;
$fee = ($converted_amount * $fee_percent) / 100;
$final_amount = $converted_amount - $fee;

// IMPORTANT: Naye gateway mein amount integer (paisa) chahiye, toh convert rupees to paise (multiply by 100)
$amount_in_paise = intval(round($amount_float));  // remove *100


// Prepare params for naya gateway
$order_time = date('YmdHis');  // current time in required format

$data = [
    "merchant_code" => MERCHANT_CODE,
    "order_no" => $txn_id,
    "order_amount" => (string)$amount_in_paise,  // integer string paise mein
    "order_time" => $order_time,
    "product_name" => preg_replace('/\s+/', '', $user['name'] ?? 'UserProduct'),  // no spaces allowed
    "notify_url" => CALLBACK_URL,
    "pay_type" => "india-upi",  // ya jo bhi aapka payment type ho, dynamic bhi kar sakte hain
    "return_url" => RETURN_URL,
    "user_no" => "1"  // optional, user id ya 1
];

// Create sign string
ksort($data);
$sign_str = '';
foreach ($data as $k => $v) {
    if ($v !== '') {
        $sign_str .= "$k=$v&";
    }
}
$sign_str .= "key=" . SECRET_KEY;

// Signature (MD5 uppercase)
$sign = strtoupper(md5($sign_str));

// Prepare final request
$request = [
    "signtype" => "MD5",
    "sign" => urlencode($sign),
    "transdata" => urlencode(json_encode($data, JSON_UNESCAPED_UNICODE))
];

// Send POST request with curl
$ch = curl_init(API_URL);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request));
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);

// Yahan debug log add karo
file_put_contents('payin_debug.log', date('Y-m-d H:i:s') . " - Response: " . $response . ", HTTP Status: $http_status\n", FILE_APPEND);

curl_close($ch);


$responseData = json_decode($response, true);

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

// Database inserts - same structure as purana code
$stmt = $pdo->prepare("INSERT INTO payin_requests (user_id, txn_id, amount, currency, converted_amount, rate, status, created_at) VALUES (?, ?, ?, ?, ?, ?, 'pending', NOW())");
$stmt->execute([$user_id, $txn_id, $amount_float, $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,
    $user_id,
    'payin',
    $final_amount,
    'pending',
    'KCPI-V1', // ya koi unique name payment gateway ka
    null,
    null,
    null,
    $default_currency,
    $fee,
    $currency,
    $default_currency,
    $rate,
    0
]);

// Payment URL
$payment_url = $responseData['payUrl'] ?? 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,
]);
