<?php

namespace Shm\ShmAdmin\Utils;

use Shm\Shm;
use Shm\ShmAdmin\AdminPanel;
use Shm\ShmUtils\ShmInit;
use Shm\ShmUtils\ShmTwig;

class AdminHTML
{


    private static function url($path = "")
    {


        $scheme =  (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';

        $host = $_SERVER['HTTP_HOST'] ?? "";

        $currentURL = $scheme . '://' . $host;

        return $currentURL . $path;
    }

    public static function html()
    {


        $title = AdminPanel::$schema->title ?? "Admin";

        $icon = AdminPanel::$schema->assets['icon'] ?? null;
        $color = AdminPanel::$schema->assets['color'] ?? "#000000";
        $apiUrl =  self::url() . $_SERVER['REQUEST_URI'];


        $url = self::url();


        $assetsUrl = ShmInit::$shmDir . '/../admin/dist/assets.json';
        $assets = json_decode(file_get_contents($assetsUrl), true);



        $jsLink = $assets['js'] ?? null;
        $cssLinks = $assets['css'] ?? [];

        if (!$jsLink) {
            Shm::error('Admin assets not found for JS');
        }
        if (!$cssLinks || count($cssLinks) === 0) {
            Shm::error('Admin assets not found for CSS');
        }

        return ShmTwig::render('@shm/admin', [
            'title' => $title,
            'icon' => $icon,
            'color' => $color,
            'shm' => ShmInit::$shmVersionHash,
            'url' => $url,
            'jsLink' => $jsLink,
            'cssLinks' => $cssLinks,
            'apiUrl' => $apiUrl,

        ]);
    }
}