<?php
namespace App\Controllers;

use App\Core\Auth;

class AppController
{
    public function spa(array $params): void
    {
        $basePath = CONFIG['BASE_PATH'];
        $appName = CONFIG['APP_NAME'];

        // Cek apakah assets sudah di-build
        $jsFile = ROOT_PATH . '/public/assets/app.js';
        $cssFile = ROOT_PATH . '/public/assets/app.css';

        $jsPath = $basePath . '/assets/app.js';
        $cssPath = $basePath . '/assets/app.css';

        // Cache busting via file modification time
        if (file_exists($jsFile)) {
            $jsPath .= '?v=' . filemtime($jsFile);
        }
        if (file_exists($cssFile)) {
            $cssPath .= '?v=' . filemtime($cssFile);
        }

        $faviconPath = $basePath . '/favicon.svg';

        header('Content-Type: text/html; charset=UTF-8');
        echo <<<HTML
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{$appName}</title>
    <link rel="icon" type="image/svg+xml" href="{$faviconPath}">
    <link rel="stylesheet" href="{$cssPath}">
    <script>window.__BASE_PATH__ = '{$basePath}';</script>
</head>
<body>
    <div id="root"></div>
    <script src="{$jsPath}"></script>
</body>
</html>
HTML;
    }

    public function root(array $params): void
    {
        $basePath = CONFIG['BASE_PATH'];
        if (Auth::isLoggedIn()) {
            header('Location: ' . $basePath . '/app', true, 302);
        } else {
            header('Location: ' . $basePath . '/login', true, 302);
        }
        exit;
    }
}
