<?php

/**
 * Live-reload endpoint for PHP built-in development server.
 * Polls file mtimes across source directories and returns
 * whether anything changed since last check.
 *
 * Usage (from browser): /live-reload
 */
class LiveReloadController
{
    private array $watchDirs;
    private array $watchExts = ['php', 'css', 'js', 'html'];
    private string $stateFile;

    public function __construct(string $appRoot)
    {
        $this->watchDirs = [
            $appRoot . '/public',
            $appRoot . '/src',
            $appRoot . '/config',
            $appRoot . '/templates',
        ];
        $this->stateFile = sys_get_temp_dir() . '/xamxam-live-reload.txt';
    }

    public function handle(): array
    {
        return ['json' => true, 'body' => $this->poll()];
    }

    private function poll(): array
    {
        $hash = '';
        foreach ($this->watchDirs as $dir) {
            if (!is_dir($dir)) {
                continue;
            }
            $it = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS)
            );
            foreach ($it as $file) {
                if (in_array($file->getExtension(), $this->watchExts, true)) {
                    $hash .= $file->getMTime() . '|' . $file->getPathname() . "\n";
                }
            }
        }

        $fingerprint = md5($hash);
        $prev = file_exists($this->stateFile) ? file_get_contents($this->stateFile) : null;

        if ($prev === null) {
            file_put_contents($this->stateFile, $fingerprint);
            $changed = false;
        } else {
            $changed = $fingerprint !== $prev;
            if ($changed) {
                file_put_contents($this->stateFile, $fingerprint);
            }
        }

        return ['changed' => $changed];
    }
}
