<?php
if (session_status() === PHP_SESSION_NONE) session_start();

if (!isset($_SESSION['user_id']) || !isset($_SESSION['tmp_deposit_order']) || !isset($_SESSION['tmp_deposit_method'])) {
    header('Location: /wallet/deposit.php'); exit;
}

$order_id = $_SESSION['tmp_deposit_order'];
$amount   = $_SESSION['tmp_deposit_amount'];
$method   = $_SESSION['tmp_deposit_method']; // e.g., easypaisa, jazz, usdt

if ($_SESSION['tmp_deposit_gateway'] !== 'boom_pay') {
    die("Invalid gateway routing.");
}

unset($_SESSION['tmp_deposit_order'], $_SESSION['tmp_deposit_amount'], $_SESSION['tmp_deposit_method'], $_SESSION['tmp_deposit_gateway']);

require_once __DIR__ . '/config.php';
$stmt = $pdo->query("SELECT setting_key, setting_value FROM admin_settings WHERE setting_key IN ('boompay_mchid', 'boompay_deposit_key', 'base_domain')");
$settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
$mchid       = $settings['boompay_mchid'] ?? '112549';
$api_key     = $settings['boompay_deposit_key'] ?? 'DTYFUYGIUHOIUGIYFUCT';
$base_domain = rtrim($settings['base_domain'] ?? (isset($_SERVER['HTTPS']) ? "https://" : "http://") . $_SERVER['HTTP_HOST'], '/');

$notify_url = "$base_domain/boompay_callback.php";
$return_url = "$base_domain/wallet/deposit.php?status=return";

$method_lower = strtolower($method);
if (strpos($method_lower, 'easy') !== false || $method_lower === 'pkrph-easy' || $method_lower === '102') {
    $channel_code = '102'; // easypaisa
} else {
    $channel_code = '101'; // jazzcash
}

$params = [
    'mchID'        => $mchid,
    'mchorderid'   => $order_id,
    'channel_code' => $channel_code,
    'api_key'      => $api_key,
    'amount'       => number_format((float)$amount, 2, '.', ''),
    'return_url'   => $return_url,
    'notify_url'   => $notify_url
];

$options = [
    "http" => [
        "header"  => "Content-Type: application/x-www-form-urlencoded\r\n",
        "method"  => "POST",
        "content" => http_build_query($params),
        "ignore_errors" => true,
        "timeout" => 30
    ]
];

$context  = stream_context_create($options);
$response = @file_get_contents('https://pkapi.boompays.online/v1/paynew', false, $context);

if (isset($http_response_header) && count($http_response_header) > 0) {
    preg_match('#HTTP/[0-9\.]+\s+([0-9]+)#', $http_response_header[0], $matches);
    $httpcode = intval($matches[1]);
} else {
    $httpcode = 0;
}

if ($response === FALSE && $httpcode === 0) {
    die("Boompay API Connection Error");
}

$res = json_decode($response, true);
if (!empty($res['payurl'])) {
    header("Location: " . $res['payurl']);
    exit;
} elseif (isset($res['data']['payurl']) && !empty($res['data']['payurl'])) {
    header("Location: " . $res['data']['payurl']);
    exit;
} else {
    file_put_contents(__DIR__ . '/boompay_error_log.txt', date('Y-m-d H:i:s') . " | Req: " . json_encode($params) . " | Res: " . $response . "\n", FILE_APPEND);
    
    // If it fails, delete the pending deposit order
    $pdo->prepare("DELETE FROM deposits WHERE order_id = ? AND status = 'pending'")->execute([$order_id]);
    
    $display_error = $response === '' ? 'Empty Response' : $response;
    $_SESSION['deposit_error'] = "Boompay Error (HTTP $httpcode): " . htmlspecialchars($display_error);
    header("Location: /wallet/deposit.php");
    exit;
}
