<?php
session_start();
require __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/cowpay_gateway_helper.php';

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

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

$uid      = intval($_SESSION['user_id']);
$amount   = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;
$method   = isset($_POST['method']) ? trim($_POST['method']) : '';
$promo_id = isset($_POST['promo_id']) ? intval($_POST['promo_id']) : 0;

// Basic validation
if ($amount <= 0 || $method === '') {
    $_SESSION['deposit_error'] = 'Invalid amount or payment method.';
    header("Location: deposit.php");
    exit();
}

// Call Cowpay create order
$result = cowpay_create_deposit_order($conn, $uid, $amount, $method, $promo_id);

if (!empty($result['success']) && !empty($result['redirect_url'])) {
    // Success → redirect to Cowpay payment page
    header("Location: " . $result['redirect_url']);
    exit();
}

// Failed
$errorMsg = !empty($result['message']) ? $result['message'] : 'Unable to start payment. Please try again.';
$_SESSION['deposit_error'] = $errorMsg;
header("Location: deposit.php");

// Temporary debug - later remove
if (empty($result['success'])) {
    echo "<pre>";
    print_r($result);
    echo "</pre>";
    exit;
}