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

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

// === 🔁 KiliPay configuration ===
define('KILIPAY_MERCHANT_NO', '1811526477');       // Your KiliPay merchant number
define('KILIPAY_SECRET', '4b46ecb8294b47f48bc2dc237afe2680'); // Secret key for signing
define('KILIPAY_API_URL', 'https://openapi-prod.kilipayment.com/pak-pay/v1/kilipayPK/payin'); // Sandbox API URL
define('KILIPAY_NOTIFY_URL', 'https://fastpay.rdnslvhost.in.net/api/kilipay_callback.php'); // Your async notification URL

// === 🔎 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 based on merchant key ===
$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;

// === 💱 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;

// === 🧾 Dummy payer info (can update to actual payer info) ===
$payer_name = 'Test User';
$payer_email = 'testuser@gmail.com';
$payer_mobile = '3256987413';
$payer_cnic = '1730123456789';
$customer_id = 'user_' . $user_id;

// ✅ Timestamp in milliseconds (required by KiliPay)
$timestamp = round(microtime(true) * 1000);

// Payment method (hardcoded here; could be dynamic)
$payment_type = 'jazzcash';

// === 📨 Prepare Payload to send to KiliPay ===
$payload = [
    'tradeNo'      => $txn_id,
    'paymentType'  => $payment_type,
    'amount'       => strval(intval($amount)), // **Important:** amount must be integer string
    'name'         => $payer_name,
    'mobile'       => $payer_mobile,
    'email'        => $payer_email,
    'remark'       => "Payment for TXN $txn_id",
    'notifyUrl' => 'https://fastpay.rdnslvhost.in.net/api/kilipay_callback.php',
    'timestamp'    => strval($timestamp),
    'customerCert' => $payer_cnic,
    'custId'       => $customer_id
];

// === 🔐 Generate Signature for payload ===
function kilipay_generate_sign($params, $private_key) {
    ksort($params);
    $sign_string = '';
    foreach ($params as $key => $val) {
        if ($key !== 'sign' && $val !== '') {
            $sign_string .= $key . '=' . $val;
        }
    }
    $sign_string .= $private_key;
    return strtolower(md5($sign_string));
}

$payload['sign'] = kilipay_generate_sign($payload, KILIPAY_SECRET);

// === 🪵 Log full request for debugging ===
file_put_contents('sign_debug.txt', json_encode($payload, JSON_PRETTY_PRINT));
file_put_contents('kilipay_debug.log', date('Y-m-d H:i:s') . " Request: " . json_encode($payload) . "\n", FILE_APPEND);

// === 🚀 Send request to KiliPay API ===
$ch = curl_init(KILIPAY_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',
    'merchantNo: ' . KILIPAY_MERCHANT_NO
]);

$response = curl_exec($ch);
if (curl_errno($ch)) {
    $curl_error = curl_error($ch);
    file_put_contents('kilipay_errors.log', date('Y-m-d H:i:s') . " CURL ERROR: $curl_error\n", FILE_APPEND);
}
curl_close($ch);

// === 📥 Log and decode response ===
file_put_contents('kilipay_debug.log', date('Y-m-d H:i:s') . " Response: $response\n\n", FILE_APPEND);
$responseData = json_decode($response, true);

// === 🧾 Handle empty or invalid response ===
if (!$responseData || !isset($responseData['code'])) {
    echo json_encode([
        "status" => "error",
        "message" => "Invalid or empty response from KiliPay",
        "details" => $response
    ]);
    exit;
}

// === ❌ If error from KiliPay ===
if ($responseData['code'] !== '0000') {
    echo json_encode([
        "status" => "error",
        "message" => "KiliPay error",
        "details" => $responseData['msg'] ?? 'Unknown error'
    ]);
    exit;
}

// === ✅ Success: Extract response data ===
$data = $responseData['data'] ?? [];
$kili_trade_no = $data['kiliTradeNo'] ?? '';
$kili_status = $data['status'] ?? '';
$remark = $data['remark'] ?? '';

// === 💾 Save transaction to database (two inserts) ===
$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',
    'KiliPayV',
    $kili_trade_no,
    null,
    null,
    $default_currency,
    $fee,
    $currency,
    $default_currency,
    $rate,
    0
]);

file_put_contents('final_output_debug.log', json_encode([
    'gateway_status' => $responseData['data']['status'] ?? null,
    'payment_url' => $responseData['data']['paymentLink'] ?? null
], JSON_PRETTY_PRINT), FILE_APPEND);


// === 📤 Final success response ===
echo json_encode([
    'status' => 'success',
    'message' => 'Kili Fast initiated successfully',
    'transaction_id' => $txn_id,
    'remark' => $remark,
    'gateway_status' => $responseData['data']['status'] ?? null,
    'payment_url' => $responseData['data']['paymentLink'] ?? null
]);

