<?php
session_start();
include('include/headscript.php');
require_once 'vendor/autoload.php';

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

// Verifica accesso
$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) {
    die("Accesso negato o condivisione non trovata.");
}

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

// Recupera i dettagli della casa
$queryHome = $conn->prepare("SELECT * FROM home WHERE idhome = ?");
$queryHome->bind_param('i', $idhome);
$queryHome->execute();
$homeData = $queryHome->get_result()->fetch_assoc();
$homeName = preg_replace('/[^A-Za-z0-9\-]/', '_', $homeData['name']);

// Recupera i documenti caricati
$queryLoaded = $conn->prepare("
    SELECT ds.filename, ds.document_id, d.document_name, s.section_name
    FROM doc_storage ds
    LEFT JOIN documents d ON ds.document_id = d.document_id
    LEFT JOIN sections s ON d.idsections = s.idsections
    LEFT JOIN home_sharing hs ON hs.idhome = ds.idhome
    WHERE ds.idhome = ? AND hs.idshareduser = ? AND hs.status = 'accepted'
    AND d.idsections IN (" . implode(',', array_map('intval', $sharedSections)) . ")
");
$queryLoaded->bind_param('ii', $idhome, $iduserlogin);
$queryLoaded->execute();
$resultLoaded = $queryLoaded->get_result();

$files = [];
while ($row = $resultLoaded->fetch_assoc()) {
    $files[] = [
        'filename' => $row['filename'],
        'document_name' => $row['document_name'],
        'section_name' => $row['section_name']
    ];
}

// Crea il PDF del report
// ... (codice precedente fino alla creazione del PDF) ...

class MYPDF extends TCPDF
{
    protected $homeName;

    public function __construct($homeName, $orientation, $unit, $format)
    {
        parent::__construct($orientation, $unit, $format);
        $this->homeName = $homeName;
    }

    public function Header()
    {
        $this->SetFont('helvetica', 'B', 16);
        $this->SetTextColor(0, 63, 127);
        $this->Cell(80, 10, 'Report Immobile', 0, 0, 'L');
        $this->SetFont('helvetica', 'B', 14);
        $this->Cell(0, 10, htmlspecialchars($this->homeName), 0, 1, 'R');
        $this->SetFont('helvetica', '', 10);
        $this->SetTextColor(100, 100, 100);
        $this->Cell(0, 5, 'Generato il ' . date('d/m/Y H:i'), 0, 1, 'C');
        $this->Ln(5);
        $this->SetLineStyle(array('width' => 0.5, 'color' => array(0, 63, 127)));
        $this->Line(15, $this->GetY(), $this->getPageWidth() - 15, $this->GetY());
    }

    public function Footer()
    {
        $this->SetY(-15);
        $this->SetFont('helvetica', 'I', 8);
        $this->SetTextColor(100, 100, 100);
        $this->Cell(0, 10, 'CasaDoc - Pagina ' . $this->getAliasNumPage() . '/' . $this->getAliasNbPages(), 0, 0, 'C');
    }
}

$pdf = new MYPDF($homeData['name'], PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetMargins(15, 35, 15);
$pdf->SetHeaderMargin(10);
$pdf->SetFooterMargin(10);
$pdf->SetAutoPageBreak(true, 25);
$pdf->AddPage();

// ... (resto del codice per il PDF e lo ZIP invariato) ...

$html = '<h2>' . htmlspecialchars($homeData['name']) . '</h2>';
$html .= '<p><strong>Indirizzo:</strong> ' . htmlspecialchars($homeData['fulladdress']) . '</p>';
$html .= '<p><strong>Città:</strong> ' . htmlspecialchars($homeData['city']) . ', ' . htmlspecialchars($homeData['country']) . ' ' . htmlspecialchars($homeData['zip']) . '</p>';
$html .= '<p><strong>Note:</strong> ' . htmlspecialchars($homeData['comment']) . '</p>';
$html .= '<h3>Dati Catastali</h3>';
$html .= '<p><strong>Comune Catastale:</strong> ' . htmlspecialchars($homeData['cadastral_municipality']) . '</p>';
$html .= '<p><strong>Sezione:</strong> ' . htmlspecialchars($homeData['cadastral_section']) . '</p>';
$html .= '<p><strong>Foglio:</strong> ' . htmlspecialchars($homeData['cadastral_sheet']) . '</p>';
$html .= '<p><strong>Particella:</strong> ' . htmlspecialchars($homeData['cadastral_particle']) . '</p>';
$html .= '<p><strong>Subalterno:</strong> ' . htmlspecialchars($homeData['cadastral_sub']) . '</p>';
$html .= '<p><strong>Categoria:</strong> ' . htmlspecialchars($homeData['cadastral_category']) . '</p>';
$html .= '<p><strong>Classe:</strong> ' . htmlspecialchars($homeData['cadastral_class']) . '</p>';
$html .= '<p><strong>Superficie:</strong> ' . htmlspecialchars($homeData['cadastral_surface']) . ' mq</p>';
$html .= '<p><strong>Rendita:</strong> €' . htmlspecialchars($homeData['cadastral_rendita']) . '</p>';

$pdf->writeHTML($html, true, false, true, false, '');

$imageFile = !empty($homeData['mainphoto']) ? 'mainphoto/' . $homeData['mainphoto'] : 'assets/images/no-image.jpg';
if (file_exists($imageFile)) {
    $pdf->Image($imageFile, 15, $pdf->GetY() + 10, 100, 0, '', '', '', false, 300, '', false, false, 0);
}

$reportFilePath = sys_get_temp_dir() . "/Report_Immobile_{$homeName}_" . date('Ymd_His') . ".pdf";
$pdf->Output($reportFilePath, 'F'); // Salva il PDF temporaneamente

// Crea lo ZIP
$zip = new ZipArchive();
$zipFileName = "Documenti_Condivisi_{$homeName}_" . date('Ymd_His') . ".zip";
$zipFilePath = sys_get_temp_dir() . '/' . $zipFileName;

if ($zip->open($zipFilePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
    die("Errore nella creazione del file ZIP.");
}

// Aggiungi i documenti allo ZIP
foreach ($files as $file) {
    $filePath = "homedocuments/{$file['filename']}";
    if (file_exists($filePath)) {
        $zip->addFile($filePath, "{$file['section_name']}/{$file['document_name']}_{$file['filename']}");
    }
}

// Aggiungi il PDF del report
if (file_exists($reportFilePath)) {
    $zip->addFile($reportFilePath, "Report_Immobile_{$homeName}.pdf");
}

$zip->close();

// Download dello ZIP
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . $zipFileName . '"');
header('Content-Length: ' . filesize($zipFilePath));
readfile($zipFilePath);

// Pulizia
unlink($zipFilePath);
unlink($reportFilePath);
exit;
