<?php
/**
 * gopay_process.php — Initiate GoPay deposit, redirect to checkout page
 * API: https://api.gopayx.live/api/public/v1/payins
 * Auth: x-api-key + HMAC-SHA256 signature
 */
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']; // GoPay method code from routing config
$uid      = (int)$_SESSION['user_id'];

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

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

// Fetch GoPay Settings from DB
require_once __DIR__ . '/config.php';
$stmt = $pdo->query("SELECT setting_key, setting_value FROM admin_settings WHERE setting_key IN ('gopay_merchant_id','gopay_payin_api_key','gopay_payin_api_secret','payment_routing')");
$settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

$api_key    = $settings['gopay_payin_api_key'] ?? '';
$api_secret = $settings['gopay_payin_api_secret'] ?? '';

// Resolve the GoPay method code from routing config
$routing = json_decode($settings['payment_routing'] ?? '{}', true);
$gp_methods = $routing['gateways']['go_pay']['methods'] ?? [];

// The $method coming from session is the raw gateway code (e.g., "PKRPH-EASY" format stored in deposit)
// We need to find the matching GoPay payin code from the routing config
$gopay_method_code = $method; // fallback to raw
foreach ($gp_methods as $m_key => $m_data) {
    if ($m_data['code'] === $method) {
        $gopay_method_code = $m_data['payin_code'] ?? $m_key; // Use payin_code if set, else method key name
        break;
    }
}

// Get user info for customer fields
$user_st = $pdo->prepare("SELECT number, member_name FROM users WHERE id = ?");
$user_st->execute([$uid]);
$user_info = $user_st->fetch();
$customer_name  = $user_info['member_name'] ?? ('User' . $uid);
$customer_phone = $user_info['number'] ?? '03001234567';

$notify_url = "https://pakclub24.club/webhook/";
$return_url = "https://pakclub24.club/wallet/deposit.php?status=return";

// Build JSON body
$body = [
    'merchant_order_id' => $order_id,
    'amount'            => intval($amount),
    'currency'          => 'PKR',
    'method'            => $gopay_method_code,
    'customer_name'     => $customer_name,
    'customer_phone'    => $customer_phone,
    'notify_url'        => $notify_url,
    'return_url'        => $return_url
];

$body_json = json_encode($body);

// HMAC-SHA256 signature
$signature = hash_hmac('sha256', $body_json, $api_secret);

// cURL Request
$ch = curl_init('https://api.gopayx.live/api/public/v1/payins');
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $body_json,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_TIMEOUT        => 30,
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/json',
        'x-api-key: ' . $api_key,
        'x-signature: ' . $signature
    ]
]);
$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'] = 'GoPay: Connection Error';
    header("Location: /wallet/deposit.php");
    exit;
}

$res = json_decode($response, true);

if (isset($res['code']) && $res['code'] === 0 && !empty($res['data']['checkout_url'])) {
    // Success — redirect user to GoPay checkout page
    header("Location: " . $res['data']['checkout_url']);
    exit;
} else {
    // Failed — cleanup pending deposit and redirect back with error
    $pdo->prepare("DELETE FROM deposits WHERE order_id = ? AND status = 'pending'")->execute([$order_id]);
    $error_msg = $res['msg'] ?? 'Unknown error';
    $_SESSION['deposit_error'] = 'GoPay: ' . $error_msg;
    header("Location: /wallet/deposit.php");
    exit;
}
