<?php
// Connessione al database
include('../include/headscript.php');
$tableName = 'reports'; // Nome tabella per reports.php

// Verifica che i parametri necessari siano stati inviati
if (isset($_POST['user']) && isset($_POST['table']) && isset($_POST['settings'])) {
    $userId = $_POST['user'];
    $page = $tableName;
    $settings = json_decode($_POST['settings'], true);

    $columnVisibility = json_encode(array_column($settings['columns'], 'visible'));
    $columnOrder = json_encode($settings['ColReorder']);

    $conn = new mysqli($servername, $username, $password, $database);

    // Verifica della connessione
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    // Query per verificare se il record esiste già
    $query = "SELECT * FROM user_table_settings WHERE iduser = ? AND page = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("is", $userId, $page);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        // Aggiorna le impostazioni esistenti
        $updateQuery = "UPDATE user_table_settings SET column_visibility = ?, column_order = ?, updated_at = NOW() WHERE iduser = ? AND page = ?";
        $updateStmt = $conn->prepare($updateQuery);
        $updateStmt->bind_param("ssis", $columnVisibility, $columnOrder, $userId, $page);
        $updateStmt->execute();
        $updateStmt->close();
        echo json_encode(['status' => 'Settings updated']);
    } else {
        // Inserisci nuove impostazioni
        $insertQuery = "INSERT INTO user_table_settings (iduser, page, column_visibility, column_order, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW())";
        $insertStmt = $conn->prepare($insertQuery);
        $insertStmt->bind_param("isss", $userId, $page, $columnVisibility, $columnOrder);
        $insertStmt->execute();
        $insertStmt->close();
        echo json_encode(['status' => 'Settings saved']);
    }

    $stmt->close();
    $conn->close();
} else {
    // Se i parametri non sono validi, restituisci errore
    http_response_code(400);
    echo json_encode(['error' => 'Invalid request']);
}
