<?php
header('Content-Type: text/html; charset=UTF-8');

require_once 'class/db-functions.php';

// Inizializza la connessione al database
$dbHandler = DBHandlerSelect::getInstance();
$pdo = $dbHandler->getConnection();

// Recupera l'ID dell'immobile
$idhome = isset($_GET['idhome']) ? intval($_GET['idhome']) : 0;

if ($idhome <= 0) {
    echo '<p class="text-muted">Errore: ID immobile non valido.</p>';
    exit();
}

// Recupera i proprietari associati all'immobile
$stmt = $pdo->prepare("
    SELECT 
        po.owner_id, 
        po.first_name, 
        po.last_name, 
        po.company_name, 
        po.tax_code, 
        po.email, 
        ho.ownership_percentage, 
        ho.notes
    FROM 
        home_owners AS ho
    INNER JOIN 
        property_owners AS po ON ho.owner_id = po.owner_id
    WHERE 
        ho.home_id = ?
");
$stmt->execute([$idhome]);
$owners = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (!empty($owners)) {
?>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Nome</th>
                <th>Codice Fiscale</th>
                <th>%</th>
                <th>Note</th>
                <th>Azioni</th>
            </tr>
        </thead>
        <tbody id="ownersTableBody">
            <?php
            $totalPercentage = 0;
            foreach ($owners as $owner) {
                $totalPercentage += $owner['ownership_percentage'];
                echo "<tr>
                    <td>" . htmlspecialchars($owner['first_name'] . ' ' . $owner['last_name']) . "</td>
                    <td>" . htmlspecialchars($owner['tax_code']) . "</td>
                    <td class='ownership-percentage'>" . htmlspecialchars($owner['ownership_percentage']) . "</td>
                    <td>" . htmlspecialchars($owner['notes']) . "</td>
                    <td>
                        <button class='btn btn-danger btn-sm remove-owner-btn' data-id='" . $owner['owner_id'] . "'>
                            <i class='fas fa-trash-alt'></i> Rimuovi
                        </button>
                    </td>
                </tr>";
            }
            ?>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="2"><strong>Totale % Proprietà:</strong></td>
                <td id="totalOwnership" class="font-weight-bold text-center"><?php echo $totalPercentage; ?>%</td>
                <td colspan="2"></td>
            </tr>
        </tfoot>
    </table>
<?php
} else {
    echo '<p class="text-muted">Nessun proprietario associato.</p>';
}
?>