<?php
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';

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

$statusFile = '/opt/monitorping/.update_status.json';
$logFile    = '/opt/monitorping/.update.log';

$status = ['status' => 'idle', 'message' => '', 'timestamp' => '', 'current' => ''];
if (file_exists($statusFile)) {
    $raw = @file_get_contents($statusFile);
    $s   = $raw ? @json_decode($raw, true) : null;
    if (is_array($s)) {
        $status = $s;
    } elseif ($raw) {
        // JSON corrompido — marca como falhou para desbloquear o botão
        $status['status']  = 'failed';
        $status['message'] = 'Status corrompido — verifique o log.';
    }
}

// Lê o log e remove códigos ANSI de cor para exibir no browser
$raw = file_exists($logFile) ? @file_get_contents($logFile) : '';
$log = preg_replace('/\x1B\[[0-9;]*[mGKHF]/u', '', $raw ?? '');

echo json_encode([
    'status'    => $status['status']    ?? 'idle',
    'message'   => $status['message']   ?? '',
    'timestamp' => $status['timestamp'] ?? '',
    'current'   => $status['current']   ?? '',
    'log'       => $log,
]);
