<?php
/**
 * Simple live-reload endpoint for development.
 * Polls file mtimes across all source directories and returns
 * whether anything changed since last check.
 *
 * Only active when served by PHP's built-in CLI server.
 */

if (php_sapi_name() !== 'cli-server') {
    http_response_code(403);
    exit;
}

header('Content-Type: application/json');

$root = dirname(__DIR__);

$watchDirs = [
    $root . '/public',
    $root . '/src',
    $root . '/config',
];

$watchExts = ['php', 'css', 'js', 'html'];

$hash = '';
foreach ($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(), $watchExts)) {
            $hash .= $file->getMTime() . '|' . $file->getPathname() . "\n";
        }
    }
}

$fingerprint = md5($hash);
$stateFile = sys_get_temp_dir() . '/xamxam-live-reload.txt';

$prev = file_exists($stateFile) ? file_get_contents($stateFile) : null;
// First visit: write baseline, don't fire a reload
if ($prev === null) {
    file_put_contents($stateFile, $fingerprint);
    $changed = false;
} else {
    $changed = $fingerprint !== $prev;
    if ($changed) {
        file_put_contents($stateFile, $fingerprint);
    }
}

echo json_encode(['changed' => $changed]);
