<?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');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

include_once __DIR__ . '/config.php';

try {
    $input = json_decode(file_get_contents("php://input"), true);

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

    $email = trim($input['email']);
    $type = isset($input['type']) ? trim($input['type']) : null; // optional (e.g., USDT TRC20)

    // Build query
    $query = "
        SELECT dr.deposit_address, dr.type, dr.created_at
        FROM deposit_requests dr
        JOIN liveaccounts l ON l.trade_id = dr.trade_id
        WHERE l.email = ? 
          AND dr.deposit_address IS NOT NULL
    ";

    // Filter by type if provided
    if (!empty($type)) {
        $query .= " AND dr.type = ?";
    }

    $query .= " ORDER BY dr.created_at DESC LIMIT 1";

    $stmt = $conn->prepare($query);
    if (!empty($type)) {
        $stmt->bind_param("ss", $email, $type);
    } else {
        $stmt->bind_param("s", $email);
    }

    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();

    if ($row) {
        echo json_encode([
            'success' => true,
            'deposit_address' => $row['deposit_address'],
            'type' => $row['type']
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'No previous deposit address found.'
        ]);
    }
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Server error: ' . $e->getMessage()
    ]);
}
?>
