<?php
// ✅ CORS Headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

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

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

// ❗ FIXED include path
include __DIR__ . "/../config.php";

// Filters
$search    = $_GET['search'] ?? '';
$status    = $_GET['status'] ?? 'all';
$startDate = $_GET['start_date'] ?? '';
$endDate   = $_GET['end_date'] ?? '';

$query = "
    SELECT t.id, t.created_at, t.from_trade, t.to_trade, t.amount, 
           t.ticket_from, t.ticket_to, t.status, t.notes,
           la.account_name, la.email
    FROM internal_transfers t
    LEFT JOIN liveaccounts la ON t.from_trade = la.trade_id
    WHERE 1
";

$params = [];
$types = "";

// Search filter
if (!empty($search)) {
    $query .= " AND (la.account_name LIKE ? OR t.from_trade LIKE ? OR t.to_trade LIKE ?)";
    $searchTerm = "%$search%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $types .= "sss";
}

// Status filter
if ($status !== 'all') {
    $query .= " AND t.status = ?";
    $params[] = $status;
    $types .= "s";
}

// Date range filter
if (!empty($startDate) && !empty($endDate)) {
    $query .= " AND DATE(t.created_at) BETWEEN ? AND ?";
    $params[] = $startDate;
    $params[] = $endDate;
    $types .= "ss";
}

$query .= " ORDER BY t.created_at DESC";

$stmt = $conn->prepare($query);

// ❗ FIXED – check prepare() error
if (!$stmt) {
    echo json_encode([
        "status" => "error",
        "message" => "SQL Prepare Failed",
        "error" => $conn->error
    ]);
    exit;
}

if ($params) {
    $stmt->bind_param($types, ...$params);
}

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

$data = [];
while ($row = $result->fetch_assoc()) {
    $data[] = [
        "id"          => $row['id'],
        "datetime"    => $row['created_at'],
        "client"      => $row['account_name'],
        "trade_from"  => $row['from_trade'],
        "trade_to"    => $row['to_trade'],
        "amount"      => (float)$row['amount'],
        "ticket_from" => $row['ticket_from'],
        "ticket_to"   => $row['ticket_to'],
        "status"      => $row['status'],
        "notes"       => $row['notes'],
        "email"       => $row['email']
    ];
}

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

$stmt->close();
$conn->close();
