<?php
header('Content-Type: application/json');
include_once __DIR__ . "/../config.php";

// Allow only GET requests
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode([
        'status' => 'error',
        'message' => 'Method not allowed. Please use GET.'
    ]);
    exit();
}

try {
    // Prepare SQL query
    $sql = "SELECT 
                id,
                email,
                mastername,
                mastertrade,
                strategyimage,
                strategyname,
                commission,
                slavename,
                slavetrade,
                copyid,
                volumeselect,
                volume,
                mode,
                status,
                followdate,
                created_at,
                master_ticket,
                slave_ticket,
                executed
            FROM copyaccounts
            ORDER BY id DESC";

    $result = $conn->query($sql);

    // Check for results
    if ($result->num_rows > 0) {
        $data = [];

        while ($row = $result->fetch_assoc()) {
            // Optional: format datetime fields
            $row['followdate'] = $row['followdate'] ? date('Y-m-d H:i:s', strtotime($row['followdate'])) : null;
            $row['created_at'] = date('Y-m-d H:i:s', strtotime($row['created_at']));

            // Optional: convert numeric fields properly
            $row['commission'] = (float)$row['commission'];
            $row['volume'] = (float)$row['volume'];
            $row['mode'] = (int)$row['mode'];
            $row['status'] = (int)$row['status'];
            $row['executed'] = (int)$row['executed'];

            $data[] = $row;
        }

        echo json_encode([
            'status' => 'success',
            'count' => count($data),
            'data' => $data
        ], JSON_PRETTY_PRINT);

    } else {
        echo json_encode([
            'status' => 'success',
            'count' => 0,
            'data' => []
        ]);
    }

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'status' => 'error',
        'message' => 'Server error: ' . $e->getMessage()
    ]);
}

$conn->close();
?>
