<?php
require_once '../core/bootstrap.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: wallet.php');
    exit();
}

$amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_FLOAT);

if (!$amount || $amount <= 0) {
    header('Location: wallet.php?error=Invalid amount');
    exit();
}

$userModel = new User();
$user = $userModel->getFullUserDetailsById($_SESSION['user_id']);

$settingModel = new Setting();
$settings = $settingModel->getAll();
$flutterwave_secret_key = $settings['flutterwave_secret_key'] ?? '';

if (empty($flutterwave_secret_key)) {
    header('Location: wallet.php?error=Payment gateway not configured');
    exit();
}

$tx_ref = 'wallet_' . uniqid();
$redirect_url = URL_ROOT . '/app/flutterwave_verify.php?payment_context=wallet_deposit';

$payload = [
    'tx_ref' => $tx_ref,
    'amount' => $amount,
    'currency' => $settings['system_currency'] ?? 'USD',
    'redirect_url' => $redirect_url,
    'payment_options' => 'card, mobilemoney, ussd',
    'customer' => [
        'email' => $user->email,
        'name' => $user->first_name . ' ' . $user->last_name,
    ],
    'meta' => [
        'user_id' => $_SESSION['user_id'],
        'payment_context' => 'wallet_deposit'
    ],
    'customizations' => [
        'title' => 'Wallet Deposit',
        'description' => 'Add funds to your wallet',
        'logo' => $settings['app_logo'] ?? '',
    ],
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.flutterwave.com/v3/payments');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $flutterwave_secret_key,
]);

$response = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);

if ($err) {
    header('Location: wallet.php?error=Payment initialization failed');
    exit();
}

$result = json_decode($response);

if ($result && $result->status === 'success' && !empty($result->data->link)) {
    header('Location: ' . $result->data->link);
    exit();
} else {
    $msg = $result->message ?? 'Unknown error';
    header('Location: wallet.php?error=' . urlencode($msg));
    exit();
}