<?php
// ───────────────────────────────
// SAFETY & DEBUG SETTINGS
// ───────────────────────────────
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

// --- Increase execution time & memory ---
ini_set('max_execution_time', 600); // 10 minutes
ini_set('memory_limit', '1G');  

// --- OPTIONS preflight ---
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;

// --- Include configs and MT5 ---
include_once __DIR__ . '/config.php';
include_once __DIR__ . '/connection.php';
include_once __DIR__ . '/mt5_api/mt5_api.php'; // MT5Connection class

// --- MySQL safe timeouts ---
$conn->query("SET SESSION wait_timeout=28800"); 
$conn->query("SET SESSION interactive_timeout=28800");

// ───────────────────────────────
// 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 {
    $mt5 = new MT5Connection();
    $mt5_connected = $mt5->connect();

    // ───────────────────────────────
    // FAST MT5 STATS FOR SLAVE ONLY
    // ───────────────────────────────
    function get_slave_mt5_stats($api, $login) {
        $stats = [
            'balance' => null,
            'equity' => null,
            'floating_pl' => null,
            'closed_pl' => 0.0,
            'open_trades' => 0
        ];

        if (!$login) return $stats;

        $account = null;
        @$ret = $api->UserAccountGet((int)$login, $account); 
        if ($ret !== MTRetCode::MT_RET_OK || !$account) return $stats;

        $stats['balance']      = (float)($account->Balance ?? 0);
        $stats['equity']       = (float)($account->Equity ?? 0);
        $stats['floating_pl']  = (float)($account->Profit ?? 0);

        // Open trades
        $posTotal = 0;
        @$retPos = $api->PositionGetTotal((int)$login, $posTotal);
        if ($retPos === MTRetCode::MT_RET_OK) {
            $stats['open_trades'] = (int)$posTotal;
        }

        // Closed deals
        $totalDeals = 0;
        @$retDeals = $api->DealGetTotal($login, 0, 0, $totalDeals);
        $closedProfit = 0.0;

        if ($retDeals === MTRetCode::MT_RET_OK && $totalDeals > 0) {
            $pageSize = 50;
            $offset = 0;

            while ($offset < $totalDeals) {
                $deals = [];
                @$retPage = $api->DealGetPage($login, 0, 0, $offset, $pageSize, $deals);
                if ($retPage !== MTRetCode::MT_RET_OK) break;

                foreach ($deals as $deal) {
                    if (isset($deal->VolumeClosed) && $deal->VolumeClosed > 0) {
                        $closedProfit += (float)($deal->Profit ?? 0);
                    }
                }
                $offset += $pageSize;
            }
        }

        $stats['closed_pl'] = $closedProfit;

        return $stats;
    }

    // ───────────────────────────────
    // FETCH COPY ACCOUNTS
    // ───────────────────────────────
    $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);

    if ($result && $result->num_rows > 0) {
        $data = [];

        while ($row = $result->fetch_assoc()) {

            $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']));

            $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'];

            if ($mt5_connected) {
                $slave_login  = (int)$row['slavetrade'];
                $slave_stats  = $slave_login ? get_slave_mt5_stats($mt5->api, $slave_login) : ['balance'=>null,'equity'=>null,'floating_pl'=>null,'closed_pl'=>0.0,'open_trades'=>0];

                $row['slave_balance']      = $slave_stats['balance'];
                $row['slave_equity']       = $slave_stats['equity'];
                $row['slave_floating_pl']  = $slave_stats['floating_pl'];
                $row['slave_closed_pl']    = $slave_stats['closed_pl'];
                $row['slave_open_trades']  = $slave_stats['open_trades'];
                $row['opentrades']         = $slave_stats['open_trades'];
            }

            $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();
?>
