<?php
// io_pay_process.php ?" Initiate IO-Pay deposit, redirect to payment page
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

// Ensure this script only runs for io_pay
if ($_SESSION['tmp_deposit_gateway'] !== 'io_pay') {
    die("Invalid gateway routing.");
}

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

// Fetch IO Pay Settings
require_once __DIR__ . '/config.php';
$stmt = $pdo->query("SELECT setting_key, setting_value FROM admin_settings WHERE setting_key IN ('io_app_id', 'io_key', 'base_domain')");
$settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
$app_id      = $settings['io_app_id'] ?? 'APP47be5aa3465a';
$key         = $settings['io_key'] ?? '2D0B68F4496049956B6E259662FE0155';
$base_domain = rtrim($settings['base_domain'] ?? 'https://pakclub24.club', '/');

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

$params = [
    'app_id'     => $app_id,
    'order_sn'   => $order_id,
    'money'      => (int)($amount * 100), // convert to paisa
    'notify_url' => $notify_url,
    'trade_type' => $method,
    'remark'     => 'deposit'
];

function iopay_sign($data, $apiKey) {
    // Remove empty values and 'sign' key
    $filtered = [];
    foreach ($data as $k => $v) {
        if ($k !== 'sign' && $v !== '' && $v !== null) {
            $filtered[$k] = $v;
        }
    }
    ksort($filtered);
    $stringA = urldecode(http_build_query($filtered));
    return strtoupper(md5($stringA . "&key=" . $apiKey));
}

$params['sign'] = iopay_sign($params, $key);

$ch = curl_init('https://iopay.in/api/payin/create');
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => http_build_query($params),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_TIMEOUT        => 30,
    CURLOPT_HTTPHEADER     => ["Content-Type: application/x-www-form-urlencoded"]
]);
$response = curl_exec($ch); 
$err = curl_error($ch); 
curl_close($ch);

if ($err) {
    die("IO-Pay API Connection Error: " . $err);
}

$res = json_decode($response, true);
if (isset($res['status']) && $res['status'] == 1 && !empty($res['data']['pay_url'])) {
    header("Location: " . $res['data']['pay_url']);
    exit;
} else {
    // If it fails, refund/delete the pending deposit order
    $pdo->prepare("DELETE FROM deposits WHERE order_id = ? AND status = 'pending'")->execute([$order_id]);
    $_SESSION['deposit_error'] = 'Method under maintenance';
    header("Location: /wallet/deposit.php");
    exit;
}
