<?php
ob_start();
require_once __DIR__ . '/src/auth.php';
require_once __DIR__ . '/src/sync_checker.php';
require_login();

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');

// Forçar atualização se solicitado
$force_refresh = isset($_GET['refresh']) && $_GET['refresh'] == 1;

try {
    $debug = null;
    $orphaned_files = get_orphaned_nextcloud_files($force_refresh, $debug);
    $unexpected_output = trim(ob_get_clean());
    if ($unexpected_output !== '') {
        throw new Exception('Saida inesperada do servidor: ' . strip_tags($unexpected_output));
    }
    echo json_encode([
        'success' => true,
        'count' => count($orphaned_files),
        'debug' => $debug
    ]);
} catch (Exception $e) {
    if (ob_get_level() > 0) {
        ob_end_clean();
    }
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
