<?php
include('include/headscript.php');

$conn = new mysqli($servername, $username, $password, $database);
$iduserlogin = $_SESSION['iduserlogin'];
$idhome = isset($_GET['idhome']) ? intval($_GET['idhome']) : 0;
$docpage = isset($_GET['slug']) ? $_GET['slug'] : 'legal'; // Slug principale per la pagina
$subSlug = isset($_GET['subSlug']) ? $_GET['subSlug'] : null; // Slug aggiuntivo opzionale
$showOnlyRequired = isset($_GET['showOnlyRequired']) && $_GET['showOnlyRequired'] === 'true';
$sectionId = isset($_GET['sectionId']) ? $_GET['sectionId'] : null;

$queryHome = $conn->prepare("SELECT * FROM home WHERE idhome = ? AND iduser = ?");
$queryHome->bind_param('ii', $idhome, $iduserlogin);
$queryHome->execute();
$resultHome = $queryHome->get_result();
$homeData = $resultHome->fetch_assoc();

if (!$homeData) {
    header('HTTP/1.1 400 Bad Request');
    die(json_encode(['error' => 'Casa non trovata o accesso non autorizzato']));
}

$queryPageId = $conn->prepare("SELECT idpages FROM pages WHERE slug = ?");
$queryPageId->bind_param('s', $docpage);
$queryPageId->execute();
$resultPageId = $queryPageId->get_result();
$pageData = $resultPageId->fetch_assoc();

if (!$pageData) {
    header('HTTP/1.1 400 Bad Request');
    die(json_encode(['error' => 'Pagina non valida']));
}

$page_id = $pageData['idpages'];

// Costruisci la query per i documenti
$sql = "
    SELECT d.*, s.section_name AS section_name
    FROM documents d
    LEFT JOIN sections s ON d.idsections = s.idsections
    WHERE d.page_id = ?
";
$params = [$page_id];

if ($showOnlyRequired) {
    $sql .= " AND d.is_required = 1";
}

if ($sectionId) {
    $sql .= " AND md5(s.section_name) = ?";
    $params[] = $sectionId;
}

// Aggiungi filtro per subSlug (assumendo che i documenti abbiano un campo slug o un riferimento)
if ($subSlug) {
    $sql .= " AND d.slug = ?"; // Assumo che 'documents' abbia un campo 'slug' per il filtraggio
    $params[] = $subSlug;
}

$sql .= " ORDER BY s.section_name, d.document_name";

$queryDocuments = $conn->prepare($sql);
$types = str_repeat('s', count($params) - 1) . 'i'; // 's' per stringhe, 'i' per page_id
$queryDocuments->bind_param($types, ...$params);
$queryDocuments->execute();
$resultDocuments = $queryDocuments->get_result();

$documents = [];
while ($row = $resultDocuments->fetch_assoc()) {
    $sectionName = $row['section_name'] ?: 'Senza sezione';
    $documents[$sectionName][] = $row;
}

$queryLoadedDocuments = $conn->prepare("SELECT * FROM doc_storage WHERE idhome = ?");
$queryLoadedDocuments->bind_param('i', $idhome);
$queryLoadedDocuments->execute();
$resultLoadedDocuments = $queryLoadedDocuments->get_result();

$loadedDocuments = [];
while ($row = $resultLoadedDocuments->fetch_assoc()) {
    $loadedDocuments[$row['document_id']][] = $row;
}

$response = [
    'homeName' => $homeData['name'] ?? '',
    'homeAddress' => ($homeData['address'] ?? '') . ', ' . ($homeData['city'] ?? '') . ' ' . ($homeData['zip'] ?? ''),
    'documents' => $documents,
    'loadedDocuments' => $loadedDocuments
];

header('Content-Type: application/json');
echo json_encode($response, JSON_PRETTY_PRINT);
exit;
