<?php
/**
 * EPD - get-withdrawal-history.php
 * Fetch all withdrawals for a specific user
 */
error_reporting(0);
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");

require_once '../config/db.php';

$wallet = $_GET['wallet'] ?? '';

if (empty($wallet)) {
    echo json_encode(["status" => "error", "message" => "Wallet required"]);
    exit;
}

$safeWallet = mysqli_real_escape_string($conn, $wallet);

// Query to get history
$query = "SELECT amount, fee, net_amount, dest_address, status, created_at 
          FROM withdrawals 
          WHERE wallet = '$safeWallet' 
          ORDER BY id DESC";

$result = mysqli_query($conn, $query);
$history = [];

while ($row = mysqli_fetch_assoc($result)) {
    $history[] = [
        "amount" => number_format($row['amount'], 2),
        "fee" => number_format($row['fee'], 2),
        "net" => number_format($row['net_amount'], 2),
        "address" => $row['dest_address'],
        "status" => ucfirst($row['status']),
        "date" => date('d M Y, h:i A', strtotime($row['created_at']))
    ];
}

echo json_encode(["status" => "success", "history" => $history]);
?>