<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

// This file is called after a pending transaction is created.
// It initiates a Korapay charge and redirects the user to the checkout URL.

session_start();
require_once '../include/config.php';

// ── Auth guard ────────────────────────────────────────────────────────────
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    header('Location: ../signin.php');
    exit();
}

// ── We need a pending Korapay transaction in session ──────────────────────
if (empty($_SESSION['pending_transaction']) || empty($_SESSION['pending_amount'])) {
    $_SESSION['error'] = "No pending transaction found. Please try again.";
    header('Location: fund-wallet.php');
    exit();
}

$transaction_ref = $_SESSION['pending_transaction'];
$amount          = floatval($_SESSION['pending_amount']);
$korapay_secret  = $site_data['korapay_secret_key'];
$redirect_url    = rtrim($site_data['web_url'], '/') . '/dashboard/verify-payment.php?gateway=korapay';

// Build payload for Korapay
$payload = json_encode([
    'reference'    => $transaction_ref,
    'amount'       => $amount,           // Naira — Korapay does NOT use kobo
    'currency'     => 'NGN',
    'redirect_url' => $redirect_url,
    'customer'     => [
        'email' => $user['email'],
        'name'  => !empty($user['full_name']) ? $user['full_name'] : $user['username'],
    ],
    'channels'     => ['card', 'bank_transfer', 'pay_with_bank'],
    'metadata'     => [
        'user_id'         => $user['id'],
        'transaction_ref' => $transaction_ref,
    ],
]);

// POST to Korapay
$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL            => "https://api.korapay.com/merchant/api/v1/charges/initialize",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 30,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $payload,
    CURLOPT_HTTPHEADER     => [
        "Authorization: Bearer " . $korapay_secret,
        "Content-Type: application/json",
        "Cache-Control: no-cache",
    ],
]);

$response = curl_exec($curl);
$curl_err  = curl_error($curl);
curl_close($curl);

if ($curl_err) {
    $_SESSION['error'] = "Could not connect to Korapay. Please try again.";
    header('Location: fund-wallet.php');
    exit();
}

$result = json_decode($response, true);

// Korapay returns: { status: true, message: "...", data: { checkout_url: "https://...", reference: "..." } }
if (
    isset($result['status']) && $result['status'] === true &&
    !empty($result['data']['checkout_url'])
) {
    // Clear session — verify-payment.php will handle the rest on return
    unset($_SESSION['pending_transaction']);
    unset($_SESSION['pending_amount']);
    unset($_SESSION['pending_gateway']);

    // Redirect user to Korapay hosted checkout page
    header('Location: ' . $result['data']['checkout_url']);
    exit();

} else {
    $error_detail = isset($result['message']) ? $result['message'] : 'Unknown error from Korapay.';
    $_SESSION['error'] = "Korapay error: " . htmlspecialchars($error_detail);
    header('Location: fund-wallet.php');
    exit();
}
?>