<?php
declare(strict_types=1);

namespace App\Core;

final class DebugBar
{
    private static float $startTime = 0;
    private static int $queryCount = 0;
    private static float $queryTime = 0.0;

    public static function init(): void
    {
        self::$startTime = $_SERVER['REQUEST_TIME_FLOAT'] ?? microtime(true);
    }

    public static function recordQuery(float $elapsed): void
    {
        self::$queryCount++;
        self::$queryTime += $elapsed;
    }

    public static function render(): string
    {
        $totalTime = self::$startTime > 0 ? round((microtime(true) - self::$startTime) * 1000) : 0;
        $memory = round(memory_get_peak_usage(true) / 1024 / 1024, 1);
        $queryCount = self::$queryCount;
        $queryTime = round(self::$queryTime * 1000);

        $app = App::getInstance();
        $employee = '-';

        try {
            $emp = $app->currentEmployee();
            if ($emp) {
                $employee = $emp->full_name_ar ?? ($emp->id ?? '-');
            }
        } catch (\Throwable $e) {
        }

        return <<<HTML
        <div id="debug-bar" style="position:fixed;bottom:0;left:0;right:0;background:#1a1a2e;color:#e0e0e0;font-family:monospace;font-size:11px;padding:6px 15px;z-index:99999;direction:ltr;text-align:left;display:flex;gap:20px;align-items:center;border-top:2px solid #0D7377;">
            <span style="color:#4ecdc4;font-weight:bold;">DEBUG</span>
            <span>Time: <b>{$totalTime}ms</b></span>
            <span>Queries: <b>{$queryCount}</b> ({$queryTime}ms)</span>
            <span>Memory: <b>{$memory}MB</b></span>
            <span>Employee: <b>{$employee}</b></span>
        </div>
        HTML;
    }
}
