<?php
require_once __DIR__ . '/../config/user_functions.php';

if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['user'])) {
    http_response_code(401);
    die('Not authorized');
}
$role = $_SESSION['user']['role'] ?? 'viewer';
if (!in_array($role, ['admin','warehouse'])) {
    http_response_code(403);
    die('Forbidden');
}

require_once __DIR__ . '/../config/db_remote.php';

$table = $_GET['table'] ?? '';
if ($table === '') {
    die('Nessuna tabella selezionata.');
}
$tableSafe = $mysqli->real_escape_string($table);

// carica colonne
$colsRes = $mysqli->query("SHOW COLUMNS FROM `$tableSafe`");
if (!$colsRes) {
    die('Errore nel caricamento colonne: ' . $mysqli->error);
}
$cols = $colsRes->fetch_all(MYSQLI_ASSOC);
$colNames = array_column($cols, 'Field');

// stessi filtri della view
$search = trim($_GET['search'] ?? '');
$colFilters = $_GET['col_filters'] ?? [];
if (!is_array($colFilters)) $colFilters = [];

$whereParts = [];
if ($search !== '') {
    $s = $mysqli->real_escape_string($search);
    $likes = [];
    foreach ($colNames as $c) {
        $likes[] = "`$c` LIKE '%$s%'";
    }
    if ($likes) {
        $whereParts[] = '(' . implode(' OR ', $likes) . ')';
    }
}
foreach ($colFilters as $col => $val) {
    if ($val === '' || !in_array($col, $colNames, true)) continue;
    $v = $mysqli->real_escape_string($val);
    $whereParts[] = "`$col` LIKE '%$v%'";
}
$whereSql = $whereParts ? 'WHERE ' . implode(' AND ', $whereParts) : '';

$sql = "SELECT * FROM `$tableSafe` $whereSql";
$res = $mysqli->query($sql);
if (!$res) {
    die('Errore query: ' . $mysqli->error);
}

header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . $table . '_export.csv"');

$out = fopen('php://output', 'w');
fputcsv($out, $colNames, ';');

while ($row = $res->fetch_assoc()) {
    $line = [];
    foreach ($colNames as $c) {
        $line[] = $row[$c] ?? '';
    }
    fputcsv($out, $line, ';');
}
fclose($out);
exit;
