<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header('Content-Type: application/json');
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");
header("Expires: 0");

$documentRoot = realpath(__DIR__ . '/../..');
$logFile = $documentRoot . "/php/api/log_rhb.json";

//$logFile = '/var/www/vhosts/cst.cat/subdomains/pefir/httpdocs/php/api/log_rhb.json';

if (file_exists($logFile)) {
    $jsonContent = file_get_contents($logFile);
    $logs = json_decode($jsonContent, true);

    // Verificar si se han proporcionado los parámetros startDate y endDate
    $startDate = isset($_GET['startDate']) ? $_GET['startDate'] : null;
    $endDate = isset($_GET['endDate']) ? $_GET['endDate'] : null;

    // Si se proporcionan startDate y endDate, filtrar por rango de fechas
    if ($startDate && $endDate) {
        $startTimestamp = strtotime(str_replace('/', '-', $startDate));
        $endTimestamp = strtotime(str_replace('/', '-', $endDate));

        $filteredLogs = array_filter($logs, function($log) use ($startTimestamp, $endTimestamp) {
            $logDate = isset($log["timestamp"]) ? explode(',', $log["timestamp"])[0] : null;
            $logTimestamp = $logDate ? strtotime(str_replace('/', '-', $logDate)) : null;

            return $logTimestamp && $logTimestamp >= $startTimestamp && $logTimestamp <= $endTimestamp;
        });

        echo json_encode(array_values($filteredLogs)); // Devuelve los logs filtrados por fecha
    } else {
        echo json_encode($logs); // Devuelve todos los logs si no se proporcionan fechas
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'File not found']);
}

?>
