<?php
include('../include/headscript.php');
include("../class/company.php");

// Abilita il reporting degli errori per il debug
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

$columns = ['idanalysisvocabulary', 'nameanalysisvoc', 'kindanalysisvoc', 'analysiscode'];

// Recupera i parametri di DataTables
$draw = isset($_POST['draw']) ? intval($_POST['draw']) : 0;
$start = isset($_POST['start']) ? intval($_POST['start']) : 0;
$length = isset($_POST['length']) ? intval($_POST['length']) : 10;
$searchValue = isset($_POST['search']['value']) ? $_POST['search']['value'] : '';

// Costruisci la query di base per recuperare tutti i dati
$sql = "SELECT * FROM analysisvocabulary WHERE preferred = 'Y'";

// Applica il filtro di ricerca, se presente
if (!empty($searchValue)) {
    $searchValueEscaped = $conn->real_escape_string($searchValue);
    $sql .= " AND (nameanalysisvoc LIKE '%$searchValueEscaped%' 
              OR kindanalysisvoc LIKE '%$searchValueEscaped%'
              OR analysiscode LIKE '%$searchValueEscaped%')";
}

// Esegui la query per ottenere il conteggio dei record filtrati
$filteredRecordsQuery = "SELECT COUNT(*) as total FROM analysisvocabulary WHERE preferred = 'Y'";
if (!empty($searchValue)) {
    $filteredRecordsQuery .= " AND (nameanalysisvoc LIKE '%$searchValueEscaped%' 
                                  OR kindanalysisvoc LIKE '%$searchValueEscaped%'
                                  OR analysiscode LIKE '%$searchValueEscaped%')";
}
$filteredRecordsResult = $conn->query($filteredRecordsQuery);
$totalFilteredRecords = $filteredRecordsResult->fetch_assoc()['total'];

// Esegui la query per ottenere il conteggio totale dei record senza filtro
$totalRecordsQuery = "SELECT COUNT(*) as total FROM analysisvocabulary WHERE preferred = 'Y'";
$totalRecordsResult = $conn->query($totalRecordsQuery);
$totalRecords = $totalRecordsResult->fetch_assoc()['total'];

// Aggiungi la limitazione per la paginazione
$sql .= " LIMIT $start, $length";

// Esegui la query principale per recuperare i dati
$result = $conn->query($sql);
$data = [];

while ($row = $result->fetch_assoc()) {
    $data[] = [
        'idanalysisvocabulary' => $row['idanalysisvocabulary'],
        'nameanalysisvoc' => $row['nameanalysisvoc'],
        'kindanalysisvoc' => $row['kindanalysisvoc'],
        'analysiscode' => $row['analysiscode']
    ];
}

// Prepara la risposta per DataTables
$response = [
    "draw" => $draw,
    "recordsTotal" => $totalRecords,
    "recordsFiltered" => $totalFilteredRecords,
    "data" => $data
];

// Imposta il tipo di contenuto e restituisci la risposta JSON
header('Content-Type: application/json');
echo json_encode($response);

$conn->close();
