<?php
session_start();
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';

// Recupera i dati di condivisione
$querySharing = $conn->prepare("SELECT sharing_type, shared_sections, iduser FROM home_sharing WHERE idhome = ? AND idshareduser = ? AND status = 'accepted'");
$querySharing->bind_param('ii', $idhome, $iduserlogin);
$querySharing->execute();
$sharingData = $querySharing->get_result()->fetch_assoc();

if (!$sharingData) {
    echo json_encode(['error' => 'Accesso negato o condivisione non trovata']);
    exit;
}

$sharedSections = json_decode($sharingData['shared_sections'], true);
$sharingIdUser = $sharingData['iduser'];

// Recupera i dettagli della casa
$queryHome = $conn->prepare("SELECT name, address, city, zip FROM home WHERE idhome = ? AND iduser = ?");
$queryHome->bind_param('ii', $idhome, $sharingIdUser);
$queryHome->execute();
$homeData = $queryHome->get_result()->fetch_assoc();

// Recupera page_id
$queryPageId = $conn->prepare("SELECT idpages FROM pages WHERE slug = ?");
$queryPageId->bind_param('s', $slug);
$queryPageId->execute();
$pageData = $queryPageId->get_result()->fetch_assoc();
$page_id = $pageData['idpages'];

// Recupera documenti
$queryDocuments = $conn->prepare("
    SELECT d.*, s.section_name
    FROM documents d
    LEFT JOIN sections s ON d.idsections = s.idsections
    WHERE d.page_id = ? AND d.idsections IN (" . implode(',', array_map('intval', $sharedSections)) . ")
    ORDER BY s.section_name, d.document_name
");
$queryDocuments->bind_param('i', $page_id);
$queryDocuments->execute();
$resultDocuments = $queryDocuments->get_result();

$documents = [];
while ($row = $resultDocuments->fetch_assoc()) {
    $documents[$row['section_name']][] = $row;
}

// Recupera documenti caricati
$queryLoaded = $conn->prepare("
    SELECT ds.* FROM doc_storage ds
    LEFT JOIN home_sharing hs ON hs.idhome = ds.idhome
    WHERE ds.idhome = ? AND hs.idshareduser = ? AND hs.status = 'accepted'
");
$queryLoaded->bind_param('ii', $idhome, $iduserlogin);
$queryLoaded->execute();
$resultLoaded = $queryLoaded->get_result();

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

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