<?php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

include_once __DIR__ . "/config.php"; // Database connection ($conn)

// Enable error reporting for debugging (remove in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Read JSON input
$input = json_decode(file_get_contents("php://input"), true);
$email = isset($input['email']) ? trim($input['email']) : '';

if (empty($email)) {
    echo json_encode([
        "success" => false,
        "message" => "Email is required"
    ]);
    exit;
}

// ================================
// Fetch Withdrawals
// ================================
$withdrawals = [];
$total_withdraw = 0.00;

$sql_withdraw = "SELECT id, trade_id, withdraw_amount, withdraw_type, company_bank, client_bank, account_holder_name, withdraw_date, Status, transaction_id 
                 FROM ib_withdraw 
                 WHERE email = ? 
                 ORDER BY withdraw_date DESC";

if ($stmt = $conn->prepare($sql_withdraw)) {
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $row['withdraw_amount'] = (float)$row['withdraw_amount'];
        $withdrawals[] = $row;
        $total_withdraw += $row['withdraw_amount'];
    }
    $stmt->close();
}

// ================================
// Fetch Internal Transfers
// ================================
$internal_transfers = [];
$total_internal_transfer = 0.00;

$sql_transfer = "SELECT id, trade_id, amount, comment, created_at 
                 FROM ib_commission_transfer_log 
                 WHERE ib_email = ? 
                 ORDER BY created_at DESC";

if ($stmt = $conn->prepare($sql_transfer)) {
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $row['amount'] = (float)$row['amount'];
        $internal_transfers[] = $row;
        $total_internal_transfer += $row['amount'];
    }
    $stmt->close();
}

// ================================
// Final Response
// ================================
$response = [
    "success" => true,
    "email" => $email,
    "total_withdraw" => round($total_withdraw, 2),
    "total_internal_transfer" => round($total_internal_transfer, 2),
    "withdrawals" => $withdrawals,
    "internal_transfers" => $internal_transfers
];

echo json_encode($response, JSON_PRETTY_PRINT);
?>
