<?php
// This file acts as the starting point for the automatic payment process.
require_once 'includes/db_connect.php';
require_once 'includes/gateway_handler.php'; // This includes the function to call the API

// Security checks: Ensure user is logged in and a valid amount was submitted
if (!isset($_SESSION["user_id"]) || !isset($_POST['amount']) || (float)$_POST['amount'] <= 0) {
    header("location: add_balance.php");
    exit;
}

$amount = (float)$_POST['amount'];
$user_id = $_SESSION['user_id'];

// Call the function from the gateway handler to start the payment process
$response = initiateBkashPayment($conn, $amount, $user_id);

// Check the response from the handler
if ($response['status'] === 'success' && !empty($response['bkashURL'])) {
    // If successful, redirect the user to the bKash payment page URL returned by the gateway
    header("Location: " . $response['bkashURL']);
    exit;
} else {
    // If it fails for any reason, show a clear error message
    die("পেমেন্ট শুরু করতে সমস্যা হয়েছে: " . ($response['message'] ?? 'Unknown error from gateway handler. Please check API settings in the admin panel.'));
}
?>