<?php
require_once __DIR__ . '/db.php';

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
    http_response_code(500);
    echo "DB connection failed: " . $e->getMessage();
    exit;
}

// Helper function to log reporter activity
function logReporterAction($pdo, $action, $uniqueKey = null, $details = null) {
    try {
        $stmt = $pdo->prepare("
            INSERT INTO reporter_log (action, unique_key, details)
            VALUES (:action, :unique_key, :details)
        ");
        $stmt->execute([
            'action' => $action,
            'unique_key' => $uniqueKey,
            'details' => $details
        ]);
    } catch (Exception $e) {
        // Silently fail - logging should not break reporter
    }
}

$type = $_POST['type'] ?? '';
$type = strtolower(trim($type));

if ($type === 'wallet') {
    if (
        isset($_POST['balance']) && $_POST['balance'] !== '' &&
        isset($_POST['equity']) && $_POST['equity'] !== '' &&
        isset($_POST['account_number']) && $_POST['account_number'] !== ''
    ) {
        $data = [
            'time' => date('Y-m-d H:i:s'), // Vždy použij serverový čas (timezone synchronizace)
            'balance' => $_POST['balance'],
            'equity' => $_POST['equity'],
            'free_margin' => $_POST['free_margin'] ?? 0,
            'used_margin' => $_POST['used_margin'] ?? 0,
            'account_number' => $_POST['account_number']
        ];

        $stmt = $pdo->prepare("
            INSERT INTO wallet_history (time, balance, equity, free_margin, used_margin, account_number)
            VALUES (:time, :balance, :equity, :free_margin, :used_margin, :account_number)
        ");
        $stmt->execute($data);

        // Log wallet action
        logReporterAction($pdo, 'wallet', $_POST['account_number'],
            "balance={$_POST['balance']}, equity={$_POST['equity']}");

        // Update CPU and RAM usage in accounts table if provided
        if (isset($_POST['cpu_usage']) || isset($_POST['ram_usage'])) {
            $updateData = ['account_number' => $_POST['account_number']];
            $updateFields = [];

            if (isset($_POST['cpu_usage']) && $_POST['cpu_usage'] !== '') {
                $updateData['cpu_usage'] = $_POST['cpu_usage'];
                $updateFields[] = 'cpu_usage = :cpu_usage';
            }

            if (isset($_POST['ram_usage']) && $_POST['ram_usage'] !== '') {
                $updateData['ram_usage'] = $_POST['ram_usage'];
                $updateFields[] = 'ram_usage = :ram_usage';
            }

            if (!empty($updateFields)) {
                $updateStmt = $pdo->prepare("
                    UPDATE accounts
                    SET " . implode(', ', $updateFields) . "
                    WHERE account_number = :account_number
                ");
                $updateStmt->execute($updateData);
            }
        }

        echo "Wallet OK";
    } else {
        echo "Wallet payload missing fields";
    }

} elseif ($type === 'position') {
    // position_id je UNIQUE klíč upsertu - bez něj by se prázdná hodnota ''
    // sdílela napříč všemi účty a přepisovala jeden společný řádek (ztráta dat).
    $positionId = $_POST['position_id'] ?? '';
    $positionIdValid = ($positionId !== '' && strtolower($positionId) !== 'null');
    if (
        $positionIdValid &&
        (!isset($_POST['balance']) || $_POST['balance'] === '') &&
        (!isset($_POST['equity']) || $_POST['equity'] === '') &&
        isset($_POST['symbol']) && $_POST['symbol'] !== '' &&
        isset($_POST['entry_price']) && $_POST['entry_price'] !== '' &&
        isset($_POST['account_number']) && $_POST['account_number'] !== ''
    ) {
        // Handle stoploss_price - convert "null" string or empty to actual NULL
        $stoploss_price = $_POST['stoploss_price'] ?? null;
        if ($stoploss_price === '' || $stoploss_price === 'null' || $stoploss_price === 'NULL') {
            $stoploss_price = null;
        }

        // Handle comment - convert "null" string or empty to actual NULL (optional field)
        $comment = $_POST['comment'] ?? null;
        if ($comment === '' || $comment === 'null' || $comment === 'NULL') {
            $comment = null;
        }

        $data = [
            'position_id' => $positionId,
            'symbol' => $_POST['symbol'],
            'volume' => $_POST['volume'] ?? '',
            'side' => $_POST['side'] ?? '',
            'label' => $_POST['label'] ?? '',
            'comment' => $comment,
            'entry_price' => $_POST['entry_price'],
            'current_price' => $_POST['current_price'] ?? '',
            'stoploss_price' => $stoploss_price,
            'pnl' => $_POST['pnl'] ?? '',
            'account_number' => $_POST['account_number']
        ];

        $stmt = $pdo->prepare("
            INSERT INTO positions (position_id, symbol, volume, side, label, `comment`, entry_price, current_price, stoploss_price, pnl, account_number)
            VALUES (:position_id, :symbol, :volume, :side, :label, :comment, :entry_price, :current_price, :stoploss_price, :pnl, :account_number)
            ON DUPLICATE KEY UPDATE
                symbol = VALUES(symbol),
                volume = VALUES(volume),
                side = VALUES(side),
                label = VALUES(label),
                `comment` = VALUES(`comment`),
                entry_price = VALUES(entry_price),
                current_price = VALUES(current_price),
                stoploss_price = VALUES(stoploss_price),
                pnl = VALUES(pnl),
                account_number = VALUES(account_number),
                time_ping = CURRENT_TIMESTAMP
        ");
        $stmt->execute($data);

        // Log position action
        logReporterAction($pdo, 'position', $positionId,
            "symbol={$_POST['symbol']}, side=" . ($_POST['side'] ?? '') . ", pnl=" . ($_POST['pnl'] ?? ''));

        echo "Position OK";
    } else {
        echo "Position payload missing fields (position_id, symbol, entry_price, account_number) or contains wallet fields";
    }

} elseif ($type === 'watchdog') {
    if (
        isset($_POST['time']) && $_POST['time'] !== '' &&
        isset($_POST['account_number']) && $_POST['account_number'] !== ''
    ) {
        // Použij aktuální serverový čas místo času od bota (timezone synchronizace)
        $data = [
            'time_ping' => date('Y-m-d H:i:s'),
            'account_number' => $_POST['account_number']
        ];
        $stmt = $pdo->prepare("
            INSERT INTO watchdog_heartbeat (account_number, time_ping)
            VALUES (:account_number, :time_ping)
            ON DUPLICATE KEY UPDATE time_ping = VALUES(time_ping)
        ");
        $stmt->execute($data);

        // IP address handling
        function getClientIP(): string {
            if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
                return $_SERVER['HTTP_CF_CONNECTING_IP'];
            } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                return explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
            } else {
                return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
            }
        }
        $ip = getClientIP();
        $account_number = $_POST['account_number'];
        $last_time = date('Y-m-d H:i:s'); // Použij serverový čas

        // Umožni více IP adres pro jeden account_number (PRIMARY KEY = account_number + ip_address)
        $insert = $pdo->prepare("
            INSERT INTO ip_address (account_number, ip_address, last_time)
            VALUES (:account_number, :ip, :last_time)
            ON DUPLICATE KEY UPDATE last_time = VALUES(last_time)
        ");
        $insert->execute([
            'account_number' => $account_number,
            'ip' => $ip,
            'last_time' => $last_time
        ]);

        // Log watchdog action
        logReporterAction($pdo, 'watchdog', $account_number, "ip=$ip");

        echo "Watchdog OK, ip: $ip";
    } else {
        echo "Watchdog payload missing fields";
    }

} elseif ($type === 'account') {
    if (
        isset($_POST['account_number']) && $_POST['account_number'] !== '' &&
        isset($_POST['account_type']) && $_POST['account_type'] !== '' &&
        isset($_POST['user']) && $_POST['user'] !== '' &&
        isset($_POST['broker']) && $_POST['broker'] !== ''
    ) {
        $account_number = $_POST['account_number'];
        $account_type = $_POST['account_type'];
        $user = $_POST['user'];
        $broker = $_POST['broker'];

        $stmt = $pdo->prepare("SELECT account_type, user, broker FROM accounts WHERE account_number = :account_number");
        $stmt->execute(['account_number' => $account_number]);
        $row = $stmt->fetch();

        if ($row) {
            if ($row['account_type'] !== $account_type || $row['user'] !== $user || $row['broker'] !== $broker) {
                $update = $pdo->prepare("UPDATE accounts SET account_type = :account_type, user = :user, broker = :broker WHERE account_number = :account_number");
                $update->execute([
                    'account_type' => $account_type,
                    'user' => $user,
                    'broker' => $broker,
                    'account_number' => $account_number
                ]);
                logReporterAction($pdo, 'account_update', $account_number, "broker=$broker, type=$account_type");
                echo "Account updated";
            } else {
                echo "Account up-to-date";
            }
        } else {
            $insert = $pdo->prepare("INSERT INTO accounts (account_number, account_type, user, broker) VALUES (:account_number, :account_type, :user, :broker)");
            $insert->execute([
                'account_number' => $account_number,
                'account_type' => $account_type,
                'user' => $user,
                'broker' => $broker
            ]);
            logReporterAction($pdo, 'account_insert', $account_number, "broker=$broker, type=$account_type, user=$user");
            echo "Account inserted";
        }
    } else {
        echo "Account payload missing fields";
    }

} else {
    echo "Invalid payload";
}
?>