<?php
/**
 * EPD - get-withdrawals.php
 * Returns full withdrawal history (profit + principal) for a user
 */
error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
require_once '../config/db.php';

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

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

// Ensure type column exists (safe migration)
mysqli_query($conn, "ALTER TABLE withdrawals ADD COLUMN IF NOT EXISTS type ENUM('profit','principal') NOT NULL DEFAULT 'profit' AFTER net_amount");
mysqli_query($conn, "ALTER TABLE withdrawals ADD COLUMN IF NOT EXISTS fee DECIMAL(10,4) NOT NULL DEFAULT 0 AFTER amount");
mysqli_query($conn, "ALTER TABLE withdrawals ADD COLUMN IF NOT EXISTS net_amount DECIMAL(10,4) NOT NULL DEFAULT 0 AFTER fee");

$result = mysqli_query($conn,
    "SELECT id, wallet, dest_address, amount, fee, net_amount, type, status, created_at
     FROM withdrawals
     WHERE wallet = '$safeWallet'
     ORDER BY id DESC"
);

$withdrawals = [];
while ($row = mysqli_fetch_assoc($result)) {
    // Fallback: if fee is 0 (old records), calculate it
    $amt = floatval($row['amount']);
    $fee = floatval($row['fee']);
    $net = floatval($row['net_amount']);

    if ($fee == 0 && $amt > 0) {
        $fee = round($amt * 0.05, 4);
        $net = round($amt - $fee, 4);
    }

    $withdrawals[] = [
        "id"           => $row['id'],
        "dest_address" => $row['dest_address'],
        "amount"       => $amt,
        "fee"          => $fee,
        "net_amount"   => $net,
        "type"         => $row['type'] ?: 'profit',   // fallback for old records
        "status"       => $row['status'],
        "created_at"   => date('d M Y, h:i A', strtotime($row['created_at']))
    ];
}

// Summary
$profitTotal    = array_sum(array_map(fn($r) => $r['type'] === 'profit'    ? $r['amount'] : 0, $withdrawals));
$principalTotal = array_sum(array_map(fn($r) => $r['type'] === 'principal' ? $r['amount'] : 0, $withdrawals));

echo json_encode([
    "status"           => "success",
    "withdrawals"      => $withdrawals,
    "profit_total"     => round($profitTotal, 2),
    "principal_total"  => round($principalTotal, 2),
    "grand_total"      => round($profitTotal + $principalTotal, 2),
    "count"            => count($withdrawals)
]);
?>