<?php
session_start();
require '../includes/db.php';
require '../includes/auth.php';  // Assume this checks session & sets $_SESSION['user_id']

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

function nf($v, $d = 2) {
    return number_format((float)($v ?? 0), $d);
}

$user_id = $_SESSION['user_id'];

// Fetch user info
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$user) {
    http_response_code(404);
    echo json_encode(['error' => 'User not found']);
    exit;
}

// Fetch withdrawal details
$stmt = $pdo->prepare("SELECT * FROM user_withdrawal_details WHERE user_id = ?");
$stmt->execute([$user_id]);
$details = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$details) {
    echo json_encode(['error' => 'Withdrawal details not set']);
    exit;
}

// Fetch payout rates
$stmt = $pdo->prepare("SELECT currency_code, payout_rate FROM user_currencies WHERE user_id = ?");
$stmt->execute([$user_id]);
$userPayoutRates = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $userPayoutRates[strtolower($row['currency_code'])] = (float)$row['payout_rate'];
}

$methodToPayoutKey = [
    'bank' => 'inr',
    'usdt' => 'usdt',
    'pkr' => 'pkr',
];

// Available payout methods logic
$availableMethods = [];
if (
    strtolower($user['currency']) === 'inr' &&
    !empty($details['bank_account']) &&
    isset($userPayoutRates[$methodToPayoutKey['bank']])
) {
    $availableMethods['bank'] = 'Bank Transfer';
}
if (!empty($details['usdt_address']) && isset($userPayoutRates[$methodToPayoutKey['usdt']])) {
    $availableMethods['usdt'] = 'USDT';
}
if (!empty($details['jazzcash_account']) && isset($userPayoutRates[$methodToPayoutKey['pkr']])) {
    $availableMethods['pkr'] = 'PKR';
}

// Handle GET: return data for frontend
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Fetch withdrawal history
    $stmt = $pdo->prepare("SELECT * FROM withdrawal_requests WHERE user_id = ? ORDER BY id DESC");
    $stmt->execute([$user_id]);
    $withdrawals = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'user' => [
            'currency' => $user['currency'],
            'balance' => (float)$user['balance'],
            'payout_fee' => (float)$user['payout_fee'],
        ],
        'available_methods' => $availableMethods,
        'withdrawals' => $withdrawals,
    ]);
    exit;
}

// Handle POST: process withdrawal request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);

    $method = strtolower(trim($input['method'] ?? ''));
    $amount = (float)($input['amount'] ?? 0);
    $user_note = trim($input['user_note'] ?? '');

    if (!isset($availableMethods[$method])) {
        http_response_code(400);
        echo json_encode(['error' => "Invalid or unavailable withdrawal method."]);
        exit;
    }

    if ($amount <= 0) {
        http_response_code(400);
        echo json_encode(['error' => "Amount must be greater than zero."]);
        exit;
    }

    $payoutRateKey = $methodToPayoutKey[$method] ?? null;
    $payoutRate = $payoutRateKey ? ($userPayoutRates[$payoutRateKey] ?? 0) : 0;

    if ($payoutRate <= 0) {
        http_response_code(400);
        echo json_encode(['error' => "No payout rate configured for this method."]);
        exit;
    }

    $convertedAmount = round($amount * $payoutRate, 2);
    $feeAmount = round(($convertedAmount * $user['payout_fee']) / 100, 2);
    $totalDeduct = $convertedAmount + $feeAmount;

    if ($totalDeduct > $user['balance']) {
        http_response_code(400);
        echo json_encode(['error' => "Insufficient balance. Need " . nf($totalDeduct) . " including fee " . nf($feeAmount) . "."]);
        exit;
    }

    try {
        $pdo->beginTransaction();

        // snapshot of current withdrawal details
        $stmt = $pdo->prepare("SELECT * FROM user_withdrawal_details WHERE user_id = ?");
        $stmt->execute([$user_id]);
        $detailsSnapshot = json_encode($stmt->fetch(PDO::FETCH_ASSOC));

        // Insert withdrawal request
        $stmt = $pdo->prepare("
            INSERT INTO withdrawal_requests 
            (user_id, method, amount, fee, user_note, currency_code, currency, details_json, total_deducted)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            $user_id,
            $method,
            $amount,
            $feeAmount,
            $user_note,
            $method,
            $user['currency'],
            $detailsSnapshot,
            $totalDeduct
        ]);

        // Deduct balance
        $stmt = $pdo->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
        $stmt->execute([$totalDeduct, $user_id]);

        $pdo->commit();

        // Fetch updated balance
        $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user['balance'] = (float)$stmt->fetchColumn();

        echo json_encode([
            'success' => "Withdrawal of $amount $method requested. " . nf($totalDeduct) . " {$user['currency']} deducted (including " . nf($feeAmount) . " fee).",
            'balance' => $user['balance'],
        ]);
    } catch (Exception $e) {
        $pdo->rollBack();
        http_response_code(500);
        echo json_encode(['error' => "Failed to process withdrawal. Please try again."]);
    }
    exit;
}

// For other methods:
http_response_code(405);
echo json_encode(['error' => 'Method Not Allowed']);
exit;
