<?php
// lg_pay_process.php — Initiate LG Pay deposit, redirect to payment page
if (session_status() === PHP_SESSION_NONE) session_start();

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

$order_id = $_SESSION['tmp_deposit_order'];
$amount   = $_SESSION['tmp_deposit_amount'];
$method   = $_SESSION['tmp_deposit_method']; // PKRPH or PKRPH-EASY

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

// Fetch LG Pay Settings
require_once __DIR__ . '/config.php';
$stmt = $pdo->query("SELECT setting_key, setting_value FROM admin_settings WHERE setting_key IN ('lg_app_id', 'lg_key')");
$settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
$app_id     = $settings['lg_app_id'] ?? 'PKR3245';
$key        = $settings['lg_key'] ?? 'LqpUftaBfNNyOh7YrMSXVlro7zIOj5um';

$proto      = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
$host       = $_SERVER['HTTP_HOST'];
$notify_url = "$proto://$host/lg_callback.php";
$return_url = "$proto://$host/wallet/deposit.php?status=return";
$user_ip    = ($_SERVER['REMOTE_ADDR'] === '::1') ? '127.0.0.1' : ($_SERVER['REMOTE_ADDR'] ?: '0.0.0.0');

// trade_type is sent directly as PKRPH (JazzCash) or PKRPH-EASY (EasyPaisa)
$params = [
    'app_id'     => $app_id,
    'trade_type' => $method,
    'order_sn'   => $order_id,
    'money'      => (int)($amount * 100),
    'notify_url' => $notify_url,
    'return_url' => $return_url,
    'ip'         => $user_ip,
    'remark'     => 'Deposit',
];

function md5_sign($data, $auth_key) {
    ksort($data);
    $string = urldecode(http_build_query($data));
    return strtoupper(md5(trim($string) . "&key=$auth_key"));
}
$params['sign'] = md5_sign($params, $key);

$ch = curl_init('https://www.lg-pay.com/api/order/create');
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => http_build_query($params),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_TIMEOUT        => 15,
]);
$response = curl_exec($ch); $err = curl_error($ch); curl_close($ch);

if ($err) {
    $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;
}

$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 {
    $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;
}
