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

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

// === 🔧 New Gateway Config ===
define('NEW_MERCHANT_CODE', 'M2529159017735294470');
define('NEW_API_URL', 'https://api.cowpay.co/pay'); // Update with real URL
define('NEW_NOTIFY_URL', 'https://kilicow.rdnslvhost.in.net/paypkr/cow1callback');

// === 🔎 Validate Inputs ===
$merchantKey = $_POST['merchant_key'] ?? '';
$amount = floatval($_POST['amount'] ?? 0);
$currency = $_POST['currency'] ?? 'pkr';
$txn_id = $_POST['txn_id'] ?? '';
$pay_type = $_POST['pay_type'] ?? 'jazzcash'; // or easypaisa

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'];
$fee_percent = isset($user['payin_fee']) ? floatval($user['payin_fee']) : 0;

// === 💱 Get conversion rate ===
$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'];
$converted = $amount * $rate;
$fee = ($converted * $fee_percent) / 100;
$final_amount = $converted - $fee;

// === 📨 Prepare New Gateway Payload ===
$payload = [
    "merchant_code" => NEW_MERCHANT_CODE,
    "country_code" => "PK",
    "order_no" => $txn_id,
    "order_amount" => number_format($amount, 2, '.', ''), // string format
    "pay_type" => $pay_type, // jazzcash / easypaisa
    "notify_url" => NEW_NOTIFY_URL,
    "return_url" => "https://kilicow.rdnslvhost.in.net/paypkr/cow1callback", // optional
    'signtype'     => 'md5'
];

function generate_signature(array $params, string $secret_key): string {
    if (isset($params['sign'])) {
        unset($params['sign']);
    }
    ksort($params);
    $sign_string = '';
    foreach ($params as $key => $value) {
        if ($value !== '') {
            $sign_string .= "$key=$value&";
        }
    }
    $sign_string = rtrim($sign_string, '&');
    $sign_string .= $secret_key;
    file_put_contents('signature_debug.log', "String to sign: $sign_string\n", FILE_APPEND);
    return strtolower(md5($sign_string));
}


// Usage
$secret_key = 'M2529159017735294470';  // Replace with your gateway secret key

$payload['sign'] = generate_signature($payload, $secret_key);


// === 🪵 Log payload ===
file_put_contents('newgateway_debug.log', date('Y-m-d H:i:s') . " Request: " . json_encode($payload) . "\n", FILE_APPEND);

// === 🚀 Send request to New Gateway ===
$ch = curl_init(NEW_API_URL);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json'
]);

$response = curl_exec($ch);
curl_close($ch);

// === 📥 Decode Response ===
$responseData = json_decode($response, true);

if (!$responseData || !isset($responseData['code'])) {
    echo json_encode([
        "status" => "error",
        "message" => "Invalid or empty response from new gateway"
    ]);
    exit;
}

if ($responseData['code'] !== '0') {
    echo json_encode([
        "status" => "error",
        "message" => $responseData['message'] ?? 'Payment initiation failed'
    ]);
    exit;
}

$pay_url = $responseData['pay_url'] ?? '';
$plat_order_no = $responseData['plat_order_no'] ?? '';

// === 💾 Save 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,
    $user_id,
    'payin',
    $final_amount,
    'pending',
    'NewGatewayPK',
    $plat_order_no,
    null,
    null,
    $currency,
    $fee,
    $currency,
    $currency,
    $rate,
    0
]);

// === 📤 Final Response ===
echo json_encode([
    'status' => 'success',
    'message' => 'Payment initiated with new gateway',
    'transaction_id' => $txn_id,
    'payment_url' => $pay_url
]);
