<?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'];
$emailuser = $_SESSION['emailuser'];
$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 = ? OR shared_email = ?) AND status = 'accepted'
");
$querySharing->bind_param('iis', $idhome, $iduserlogin, $emailuser);
$querySharing->execute();
$sharingData = $querySharing->get_result()->fetch_assoc();

$queryOwner = $conn->prepare("SELECT iduser FROM home WHERE idhome = ?");
$queryOwner->bind_param("i", $idhome);
$queryOwner->execute();
$ownerData = $queryOwner->get_result()->fetch_assoc();

if (!$sharingData && $ownerData['iduser'] != $iduserlogin) {
    die("Accesso negato.");
}

// Recupera i dati della casa
$queryHome = $conn->prepare("SELECT * FROM home WHERE idhome = ?");
$queryHome->bind_param('i', $idhome);
$queryHome->execute();
$homeData = $queryHome->get_result()->fetch_assoc();

// Classe personalizzata per il PDF
class MYPDF extends TCPDF
{
    protected $homeName; // Proprietà per il nome dell'immobile

    public function __construct($homeName, $orientation, $unit, $format)
    {
        parent::__construct($orientation, $unit, $format);
        $this->homeName = $homeName; // Imposta il nome dell'immobile
    }

    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');
    }
}

// Crea il PDF passando il nome dell'immobile
$pdf = new MYPDF($homeData['name'], PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('CasaDoc');
$pdf->SetTitle($homeData['name']);
$pdf->SetMargins(15, 35, 15);
$pdf->SetHeaderMargin(10);
$pdf->SetFooterMargin(10);
$pdf->SetAutoPageBreak(true, 25);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->AddPage();

// Stile generale
$pdf->SetFont('helvetica', '', 11);
$pdf->SetTextColor(0, 0, 0);

// Sezione Informazioni Generali
$pdf->SetFillColor(240, 248, 255);
$pdf->SetDrawColor(0, 63, 127);
$pdf->SetLineWidth(0.2);
$pdf->Cell(0, 8, 'Informazioni Generali', 'B', 1, 'L', 1);
$pdf->Ln(2);

$html = '
<table cellpadding="4">
    <tr>
        <td width="30%"><strong>Indirizzo:</strong></td>
        <td width="70%">' . htmlspecialchars($homeData['fulladdress']) . '</td>
    </tr>
    <tr>
        <td><strong>Città:</strong></td>
        <td>' . htmlspecialchars($homeData['city']) . ', ' . htmlspecialchars($homeData['country']) . ' ' . htmlspecialchars($homeData['zip']) . '</td>
    </tr>
    <tr>
        <td><strong>Note:</strong></td>
        <td>' . (empty($homeData['comment']) ? 'Nessuna nota' : htmlspecialchars($homeData['comment'])) . '</td>
    </tr>
</table>';
$pdf->writeHTML($html, true, false, true, false, '');

// Immagine
$imageFile = !empty($homeData['mainphoto']) ? 'mainphoto/' . $homeData['mainphoto'] : 'assets/images/no-image.jpg';
if (file_exists($imageFile)) {
    $pdf->Ln(5);
    list($width, $height) = getimagesize($imageFile);
    $maxWidth = $pdf->getPageWidth() - 100;
    $scale = $maxWidth / $width;
    $newHeight = $height * $scale;
    $pdf->Image($imageFile, 15, $pdf->GetY(), $maxWidth, $newHeight, '', '', 'T', false, 300, '', false, false, 1);
    $pdf->Ln($newHeight + 5);
}

// Mappa Google Static Maps
$latitude = $homeData['latitude'] ?: 41.9028;
$longitude = $homeData['longitude'] ?: 12.4964;
$googleMapsApiKey = 'AIzaSyADtQRKgCpJNnQCP8QvBeKDcm0TrTPpsGY'; // Sostituisci con la tua chiave API
$mapUrl = "https://maps.googleapis.com/maps/api/staticmap?center={$latitude},{$longitude}&zoom=14&size=800x500&markers=color:red|{$latitude},{$longitude}&key={$googleMapsApiKey}";
$mapFile = sys_get_temp_dir() . '/map_' . $idhome . '.png';

file_put_contents($mapFile, file_get_contents($mapUrl));
if (file_exists($mapFile)) {
    $pdf->SetFillColor(240, 248, 255);
    $pdf->Cell(0, 8, 'Posizione Geografica', 'B', 1, 'L', 1);
    $pdf->Ln(2);
    $pdf->Image($mapFile, 15, $pdf->GetY(), 100, 50, '', '', 'T', false, 300, '', false, false, 1);
    $pdf->Ln(55);
    unlink($mapFile);
}

// Sezione Dati Catastali
$pdf->SetFillColor(240, 248, 255);
$pdf->Cell(0, 8, 'Dati Catastali', 'B', 1, 'L', 1);
$pdf->Ln(2);

$html = '
<table border="1" cellpadding="5" style="border-color: #003f7f;">
    <tr style="background-color: #e6f0fa;">
        <th width="40%"><strong>Campo</strong></th>
        <th width="60%"><strong>Valore</strong></th>
    </tr>
    <tr>
        <td>Comune Catastale</td>
        <td>' . (empty($homeData['cadastral_municipality']) ? '-' : htmlspecialchars($homeData['cadastral_municipality'])) . '</td>
    </tr>
    <tr>
        <td>Sezione</td>
        <td>' . (empty($homeData['cadastral_section']) ? '-' : htmlspecialchars($homeData['cadastral_section'])) . '</td>
    </tr>
    <tr>
        <td>Foglio</td>
        <td>' . (empty($homeData['cadastral_sheet']) ? '-' : htmlspecialchars($homeData['cadastral_sheet'])) . '</td>
    </tr>
    <tr>
        <td>Particella</td>
        <td>' . (empty($homeData['cadastral_particle']) ? '-' : htmlspecialchars($homeData['cadastral_particle'])) . '</td>
    </tr>
    <tr>
        <td>Subalterno</td>
        <td>' . (empty($homeData['cadastral_sub']) ? '-' : htmlspecialchars($homeData['cadastral_sub'])) . '</td>
    </tr>
    <tr>
        <td>Categoria</td>
        <td>' . (empty($homeData['cadastral_category']) ? '-' : htmlspecialchars($homeData['cadastral_category'])) . '</td>
    </tr>
    <tr>
        <td>Classe</td>
        <td>' . (empty($homeData['cadastral_class']) ? '-' : htmlspecialchars($homeData['cadastral_class'])) . '</td>
    </tr>
    <tr>
        <td>Superficie</td>
        <td>' . (empty($homeData['cadastral_surface']) ? '-' : htmlspecialchars($homeData['cadastral_surface']) . ' mq') . '</td>
    </tr>
    <tr>
        <td>Rendita</td>
        <td>' . (empty($homeData['cadastral_rendita']) ? '-' : '€' . htmlspecialchars($homeData['cadastral_rendita'])) . '</td>
    </tr>
</table>';
$pdf->writeHTML($html, true, false, true, false, '');

// Nome del file e output
$homeNameSafe = preg_replace('/[^A-Za-z0-9\-]/', '_', $homeData['name']);
$pdfFileName = "Report_Immobile_{$homeNameSafe}_" . date('Ymd_His') . ".pdf";
$pdf->Output($pdfFileName, 'D');
exit;
