<?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 withdrawal from settings
$min_withdrawal = $functions->getSetting('min_withdrawal', 5.00);
if ($amount < $min_withdrawal) {
    echo json_encode(['success' => false, 'message' => 'Minimum withdrawal amount is $' . number_format($min_withdrawal, 2)]);
    exit();
}

// Check if user has sufficient balance
if ($user_data['balance'] < $amount) {
    echo json_encode(['success' => false, 'message' => 'Insufficient balance']);
    exit();
}

// Calculate withdrawal fee
$withdrawal_fee_rate = $functions->getSetting('withdrawal_fee', 0.05); // 5%
$fee = $amount * $withdrawal_fee_rate;
$net_amount = $amount - $fee;

try {
    $functions->db->beginTransaction();

    // Create withdrawal transaction
    $transaction_id = $functions->createTransaction([
        'user_id' => $user_id,
        'type' => 'withdrawal',
        'amount' => $amount,
        'fee' => $fee,
        'net_amount' => $net_amount,
        'method' => $method,
        'description' => 'Withdrawal via ' . $method,
        'status' => 'pending',
        'details' => [
            'wallet_address' => $wallet_address,
            'fee' => $fee,
            'net_amount' => $net_amount,
            'withdrawal_date' => date('Y-m-d H:i:s')
        ]
    ]);

    // Log activity
    $functions->logActivity($user_id, 'withdrawal_requested', 'Requested withdrawal of $' . number_format($amount) . ' via ' . $method);

    $functions->db->commit();

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

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