<?php
// Connessione al database
include('../include/headscript.php');

// Recupera i dati dalla richiesta POST
$iduser = isset($_POST['iduser']) ? $_POST['iduser'] : 0;
$page = isset($_POST['page']) ? $_POST['page'] : '';
$column_visibility = isset($_POST['column_visibility']) ? $_POST['column_visibility'] : '';
$column_order = isset($_POST['column_order']) ? $_POST['column_order'] : '';

if ($iduser && $page && $column_visibility && $column_order) {
    // Verifica se esistono già impostazioni per l'utente e la pagina
    $stmt = $conn->prepare("SELECT * FROM user_table_settings WHERE iduser = ? AND page_name = ?");
    $stmt->bind_param("is", $iduser, $page);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        // Aggiorna le impostazioni esistenti
        $stmt = $conn->prepare("UPDATE user_table_settings SET column_visibility = ?, column_order = ? WHERE iduser = ? AND page_name = ?");
        $stmt->bind_param("ssis", $column_visibility, $column_order, $iduser, $page);
    } else {
        // Inserisci nuove impostazioni
        $stmt = $conn->prepare("INSERT INTO user_table_settings (iduser, page_name, column_visibility, column_order) VALUES (?, ?, ?, ?)");
        $stmt->bind_param("isss", $iduser, $page, $column_visibility, $column_order);
    }

    if ($stmt->execute()) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['error' => 'Failed to save settings']);
    }
} else {
    // Se non ci sono dati sufficienti, invia un errore
    http_response_code(400);
    echo json_encode(['error' => 'Invalid request']);
}

$conn->close();
?>
