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

$conn = new mysqli($servername, $username, $password, $database);
$iduserlogin = $_SESSION['iduserlogin'];
$idhome = isset($_GET['idhome']) ? intval($_GET['idhome']) : 0;
$slug = isset($_GET['slug']) ? $_GET['slug'] : 'legal';

$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', $slug);
$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'];

$querySections = $conn->prepare("
    SELECT DISTINCT s.section_name
    FROM documents d
    LEFT JOIN sections s ON d.idsections = s.idsections
    WHERE d.page_id = ?
    ORDER BY s.section_name
");
$querySections->bind_param('i', $page_id);
$querySections->execute();
$resultSections = $querySections->get_result();

$sections = [];
while ($row = $resultSections->fetch_assoc()) {
    $sections[] = $row;
}

header('Content-Type: application/json');
echo json_encode(['sections' => $sections]);
exit;
