<?php
include('../include/headscript.php');
include("../class/company.php");
$conn = new mysqli($servername, $username, $password, $database);
// Ottieni i parametri per la paginazione da DataTables
$start = $_POST['start'];
$length = $_POST['length'];
$search = $_POST['search']['value'];

// Costruisci la query base
$query = "SELECT * FROM compundsvocabulary WHERE preferred = 'Y'";

// Aggiungi la logica di ricerca se necessario
if (!empty($search)) {
    $query .= " AND (namecompoundsvocabulary LIKE ? OR cascompoundvocabulary LIKE ?)";
    $searchParam = '%' . $search . '%';
    $stmt = $conn->prepare($query . " LIMIT ?, ?");
    $stmt->bind_param('ssii', $searchParam, $searchParam, $start, $length);
} else {
    $stmt = $conn->prepare($query . " LIMIT ?, ?");
    $stmt->bind_param('ii', $start, $length);
}

$stmt->execute();
$result = $stmt->get_result();

// Recupera i dati e formattali per DataTables
$data = [];
while ($row = $result->fetch_assoc()) {
    $data[] = $row;
}

// Ottieni il numero totale di record per il paginatore di DataTables
$totalQuery = "SELECT COUNT(*) as total FROM compundsvocabulary WHERE preferred = 'Y'";
$totalResult = $conn->query($totalQuery);
$totalData = $totalResult->fetch_assoc();

$response = [
    "draw" => intval($_POST['draw']),
    "recordsTotal" => intval($totalData['total']),
    "recordsFiltered" => intval($totalData['total']),
    "data" => $data
];

echo json_encode($response);
