<?php
/**
 * withdrawal.php: Handles user withdrawal requests
 * Part of Ton Sui Mining investment workflow
 */

// Define TONSUI_LOADED constant to prevent direct access to session_init.php
define('TONSUI_LOADED', true);

// Include centralized session initialization
require_once __DIR__ . '/session_init.php';

header('Content-Type: application/json');
// Critical: Add cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// CRITICAL: Allow origin with credentials
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

require_once 'config.php';
require_once 'db.php';
require_once 'auth.php';
require_once 'csrf.php';

function respond($success, $message, $data = null) {
    $response = ['success' => $success, 'message' => $message];
    if ($data !== null) {
        $response['data'] = $data;
    }
    echo json_encode($response);
    exit;
}

// Ensure user is authenticated
if (empty($_SESSION['user_id'])) {
    respond(false, 'You must be logged in to request a withdrawal.');
}

// Get POST data
$data = json_decode(file_get_contents('php://input'), true);
$amount = isset($data['amount']) ? floatval($data['amount']) : 0;
$wallet_address = $data['wallet_address'] ?? '';
$withdrawal_method = $data['withdrawal_method'] ?? '';
$description = $data['description'] ?? 'Withdrawal request';

// Validate input
if ($amount <= 0) {
    respond(false, 'Invalid withdrawal amount. Amount must be greater than zero.');
}

if (empty($wallet_address)) {
    respond(false, 'Wallet address is required.');
}

if (empty($withdrawal_method)) {
    respond(false, 'Withdrawal method is required.');
}

// Check if user has sufficient balance
try {
    $stmt = $pdo->prepare('SELECT balance FROM users WHERE id = ?');
    $stmt->execute([$_SESSION['user_id']]);
    $user = $stmt->fetch();
    
    if (!$user) {
        respond(false, 'User not found.');
    }
    
    $balance = floatval($user['balance']);
    
    if ($balance < $amount) {
        respond(false, 'Insufficient balance. Your available balance is ' . number_format($balance, 8) . '.');
    }
    
    // Start a transaction
    $pdo->beginTransaction();
    
    // Deduct the amount from the user's balance
    // Note: We don't actually deduct until admin approves, just mark as pending
    $withdrawalStmt = $pdo->prepare('
        INSERT INTO transactions 
        (user_id, type, amount, status, details, reference, created_at) 
        VALUES (?, ?, ?, ?, ?, ?, NOW())
    ');
    
    $reference = 'WD-' . time() . '-' . rand(1000, 9999);
    $details = json_encode([
        'withdrawal_method' => $withdrawal_method,
        'wallet_address' => $wallet_address,
        'description' => $description
    ]);
    
    $withdrawalStmt->execute([
        $_SESSION['user_id'],
        'withdrawal',
        $amount,
        'pending', // Initial status is pending until approved by admin
        $details,
        $reference
    ]);
    
    $withdrawal_id = $pdo->lastInsertId();
    
    // Log the withdrawal request
    $logStmt = $pdo->prepare('
        INSERT INTO security_logs 
        (event_type, user_id, ip_address, user_agent, details, created_at) 
        VALUES (?, ?, ?, ?, ?, NOW())
    ');
    
    $logStmt->execute([
        'withdrawal_request',
        $_SESSION['user_id'],
        $_SERVER['REMOTE_ADDR'] ?? 'unknown',
        $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
        json_encode([
            'amount' => $amount,
            'wallet_address' => $wallet_address,
            'withdrawal_method' => $withdrawal_method,
            'reference' => $reference
        ])
    ]);
    
    // Commit transaction
    $pdo->commit();
    
    respond(true, 'Withdrawal request submitted successfully. It will be processed after approval.', [
        'transaction_id' => $withdrawal_id,
        'reference' => $reference
    ]);
    
} catch (Exception $e) {
    // Something went wrong, rollback
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    error_log('Withdrawal error: ' . $e->getMessage());
    respond(false, 'An error occurred while processing your withdrawal request. Please try again or contact support.');
}
