<?php
require_once 'includes/db.php';

if (!isset($_SESSION['user_id'])) { 
    header("Location: login.php"); 
    exit(); 
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { 
    exit('Invalid request method.'); 
}

// --- THIS IS THE FIX: Load all site settings from the database first ---
$settings_result = $conn->query("SELECT * FROM site_settings");
$site_settings = [];
if ($settings_result) {
    while ($row = $settings_result->fetch_assoc()) {
        $site_settings[$row['setting_name']] = $row['setting_value'];
    }
}

$amount = floatval($_POST['amount']) * 100; // PayMongo requires amount in centavos
$method = $_POST['method']; // e.g., 'gcash', 'paymaya'
$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['user_name'];

// Now we can safely access the API key
$secret_key = $site_settings['paymongo_secret_key'] ?? '';

if (empty($secret_key)) {
    die('Could not create payment session. The PayMongo Secret Key is not set in the admin Site Settings.');
}

$payload = [
    'data' => [
        'attributes' => [
            'line_items' => [
                [
                    'currency' => 'PHP',
                    'amount' => $amount,
                    'name' => 'Wallet Top-Up for ' . $user_name,
                    'quantity' => 1,
                ]
            ],
            'payment_method_types' => [$method],
            'success_url' => "http://" . $_SERVER['HTTP_HOST'] . "/dashboard/transactions.php?payment=success",
            'cancel_url' => "http://" . $_SERVER['HTTP_HOST'] . "/dashboard/top-up.php?payment=cancelled",
            'description' => 'Wallet Top-Up for user #' . $user_id,
            'metadata' => [
                'user_id' => $user_id // IMPORTANT for the webhook to identify the user
            ]
        ]
    ]
];

$ch = curl_init('https://api.paymongo.com/v1/checkout_sessions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Basic ' . base64_encode($secret_key)
]);

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$result = json_decode($response, true);

if (isset($result['data']['attributes']['checkout_url'])) {
    // Success: Redirect the user to the PayMongo payment page
    header('Location: ' . $result['data']['attributes']['checkout_url']);
    exit();
} else {
    // Failure: Show an error
    echo "Could not create payment session. Please check your API keys in the admin panel.";
    echo "<br><br>PayMongo Response: <pre>";
    print_r($result);
    echo "</pre>";
    die();
}
?>
