<?php
/**
 * VFM - /vfm-admin/admin-panel/ajax/save-csv.php (Secured)
 */
// Controllo accesso diretto tramite costante
// Se non definita, verifichiamo se è una chiamata AJAX valida
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
    header('HTTP/1.0 403 Forbidden');
    die('Direct access not allowed');
}
require_once dirname(dirname(__DIR__)).'/class/class.setup.php';
require_once dirname(dirname(__DIR__)).'/class/class.utils.php';
require_once dirname(dirname(__DIR__)).'/class/class.gatekeeper.php';

$setUp = new SetUp();
$gateKeeper = new GateKeeper();

// 1. Controllo rigoroso dei permessi (solo SuperAdmin o Admin autorizzati)
if (!$gateKeeper->isSuperAdmin() && !$gateKeeper->isAdmin()) {
    die('Permission Denied');
}

$start = filter_input(INPUT_POST, 'logsince', FILTER_SANITIZE_SPECIAL_CHARS);
$end = filter_input(INPUT_POST, 'loguntil', FILTER_SANITIZE_SPECIAL_CHARS);

if (!$start || !$end) {
    die('Invalid dates');
}

$logspath = dirname(dirname(__DIR__)).'/_content/log/';
$loglist = glob($logspath.'*.json');
$result = array();
$getlogs = false;

foreach ($loglist as $log) {
    $basename = basename($log, ".json");
    if ($basename == $start) { $getlogs = true; }
    if ($getlogs === true) {
        $resultnew = json_decode(file_get_contents($log), true);
        if (is_array($resultnew)) {
            $result = array_merge($result, $resultnew);
        }
    }
    if ($basename == $end) { $getlogs = false; }
} 

$result = array_reverse($result);

// Output headers per il download
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=log-'.$start.'--'.$end.'.csv');

$output = fopen('php://output', 'w');
fputcsv($output, array('Date', 'Time', 'User', 'Action', 'Type', 'File'));

foreach ($result as $day => $actions) {
    foreach ($actions as $action) {
        fputcsv($output, array($day, $action['time'], $action['user'], $action['action'], $action['type'], $action['item']));
    }
}
exit;
