<?php
header('Content-Type: application/json');
require_once '../includes/auth.php';
require_once '../includes/functions.php';

if (!$auth->isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit();
}

$user_id = $auth->getCurrentUserId();
$user_data = $auth->getCurrentUser();
$functions = new Functions();

// Get POST data
$amount = isset($_POST['amount']) ? (float)$_POST['amount'] : 0;
$method = isset($_POST['method']) ? $functions->sanitize($_POST['method']) : '';
$wallet_address = isset($_POST['wallet_address']) ? $functions->sanitize($_POST['wallet_address']) : '';

// Validate input
if ($amount <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid amount']);
    exit();
}

// Get minimum deposit from settings
$min_deposit = $functions->getSetting('min_deposit', 10.00);
if ($amount < $min_deposit) {
    echo json_encode(['success' => false, 'message' => 'Minimum deposit amount is $' . number_format($min_deposit, 2)]);
    exit();
}

try {
    // Create deposit transaction
    $transaction_id = $functions->createTransaction([
        'user_id' => $user_id,
        'type' => 'deposit',
        'amount' => $amount,
        'method' => $method,
        'description' => 'Deposit via ' . $method,
        'status' => 'pending',
        'details' => [
            'wallet_address' => $wallet_address,
            'deposit_date' => date('Y-m-d H:i:s')
        ]
    ]);

    // Log activity
    $functions->logActivity($user_id, 'deposit_initiated', 'Initiated deposit of $' . number_format($amount) . ' via ' . $method);

    echo json_encode([
        'success' => true,
        'message' => 'Deposit request submitted successfully',
        'data' => [
            'transaction_id' => $transaction_id,
            'amount' => number_format($amount, 2),
            'method' => $method,
            'status' => 'pending'
        ]
    ]);

} catch (Exception $e) {
    error_log("Deposit creation error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Failed to process deposit. Please try again.']);
}
?>
