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

<?php
// Connessione al database
$conn = new mysqli($servername, $username, $password, $database);

// Recupera l'id utente loggato e la sua email
$iduserlogin = $_SESSION['iduserlogin'];
$emailuser = $_SESSION['emailuser'];

// Verifica se si sta aggiungendo una nuova casa o aggiornando una esistente
$idhome = isset($_GET['idhome']) ? intval($_GET['idhome']) : 0;
$isNew = ($idhome == 0);

if ($isNew) {
    // Se non esiste ancora l'idhome, crea un nuovo record e ricarica la pagina con l'ID generato
    $insertQuery = $conn->prepare("INSERT INTO home (iduser) VALUES (?)");
    $insertQuery->bind_param("i", $iduserlogin);
    $insertQuery->execute();
    $idhome = $conn->insert_id; // Ottieni il nuovo idhome generato

    // Ricarica la pagina con il nuovo idhome
    header("Location: manage-home.php?idhome=$idhome");
    exit(); // Assicurati di uscire per evitare che il codice continui
}

// Determina l'iduser corretto per l'immobile, controllando sia il proprietario che le condivisioni
$ownerId = null;
$queryOwner = $conn->prepare("SELECT iduser FROM home WHERE idhome = ?");
$queryOwner->bind_param("i", $idhome);
$queryOwner->execute();
$resultOwner = $queryOwner->get_result();
if ($resultOwner->num_rows > 0) {
    $ownerData = $resultOwner->fetch_assoc();
    $ownerId = $ownerData['iduser'];
}

// Verifica se l'utente ha accesso diretto (è il proprietario) o tramite condivisione
$hasAccess = false;
if ($ownerId == $iduserlogin) {
    $hasAccess = true; // Utente è il proprietario
} else {
    // Controlla se l'utente ha accesso tramite home_sharing
    $querySharing = $conn->prepare("
        SELECT * FROM home_sharing 
        WHERE idhome = ? 
        AND (idshareduser = ? OR shared_email = ?)
        AND status = 'accepted'
    ");
    $querySharing->bind_param("iis", $idhome, $iduserlogin, $emailuser);
    $querySharing->execute();
    $resultSharing = $querySharing->get_result();
    $hasAccess = ($resultSharing->num_rows > 0);
}

// Se l'utente non ha accesso, reindirizza o mostra un errore
if (!$hasAccess) {
    header("Location: access-denied.php"); // O una pagina di errore personalizzata
    exit();
}

// Carica i dati della casa per l'utente con accesso
$query = $conn->prepare("SELECT * FROM home WHERE idhome = ?");
$query->bind_param("i", $idhome);
$query->execute();
$result = $query->get_result();
$homeData = $result->fetch_assoc();

// Assegna i valori esistenti ai campi
$namedb = $homeData['name'];
$addressdb = $homeData['address'];
$countrydb = $homeData['country'];
$citydb = $homeData['city'];
$zipdb = $homeData['zip'];
$commentdb = $homeData['comment'];
$latitudedb = $homeData['latitude'];
$longitudedb = $homeData['longitude'];
$fulladdressdb = $homeData['fulladdress'];
// Campi catastali
$cadastral_municipalitydb = $homeData['cadastral_municipality'];
$cadastral_sectiondb = $homeData['cadastral_section'];
$cadastral_sheetdb = $homeData['cadastral_sheet'];
$cadastral_particledb = $homeData['cadastral_particle'];
$cadastral_subdb = $homeData['cadastral_sub'];
$cadastral_categorydb = $homeData['cadastral_category'];
$cadastral_classdb = $homeData['cadastral_class'];
$cadastral_surfacedb = $homeData['cadastral_surface'];
$cadastral_renditadbs = $homeData['cadastral_rendita'];
$cadastral_notesdb = $homeData['cadastral_notes'];
?>



<!DOCTYPE html>
<html lang="it">

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <?php include('include/seo.php'); ?>

    <link rel="shortcut icon" href="assets/images/favicon.ico">
    <link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link href="assets/css/icons.css" rel="stylesheet" type="text/css">
    <link href="assets/css/style.css" rel="stylesheet" type="text/css">
    <style>
        #map {
            height: 400px;
            width: 100%;
        }

        .success-flash {
            background-color: #d4edda !important;
            transition: background-color 1s ease;
        }
    </style>
</head>

<body class="fixed-left">
    <div id="wrapper">
        <?php include('include/navigationbar.php'); ?>

        <div class="content-page">
            <div class="content">
                <?php include('include/topbar.php'); ?>

                <div class="page-content-wrapper">
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-sm-12">
                                <div class="page-title-box d-flex justify-content-between align-items-center">
                                    <!-- Titolo -->
                                    <h4 class="page-title m-0"><?php echo $isNew ? "Aggiungi Casa" : "Modifica Casa"; ?></h4>

                                    <!-- Tasto Torna indietro -->
                                    <button onclick="history.back()" class="btn btn-dark">
                                        <i class="fas fa-arrow-left"></i> Torna indietro
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Banner Section -->
                        <!-- Banner Section -->
                        <div class="row">
                            <div class="col-lg-12">
                                <div class="banner-section" style="position: relative; border-radius: 10px; overflow: hidden; height: 150px;">
                                    <!-- Background Image -->
                                    <div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-image: url('<?php echo !empty($homeData['mainphoto']) ? 'mainphoto/' . htmlspecialchars($homeData['mainphoto']) : 'assets/images/no-image.jpg'; ?>'); background-size: cover; background-position: center;"></div>
                                    <!-- Gradient Overlay -->
                                    <div class="header-banner-overlay" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: linear-gradient(to right, rgba(30, 58, 138, 0.8), rgba(255, 255, 255, 0.2)); padding: 20px; display: flex; align-items: center;">
                                        <!-- Thumbnail and Address/City -->
                                        <div style="flex: 1; display: flex; align-items: center;">
                                            <!-- Thumbnail -->
                                            <img src="<?php echo !empty($homeData['mainphoto']) ? 'mainphoto/' . htmlspecialchars($homeData['mainphoto']) : 'assets/images/no-image.jpg'; ?>"
                                                alt="Thumbnail"
                                                style="width: 80px; height: 80px; object-fit: cover; border-radius: 5px; margin-right: 20px;">
                                            <!-- Address and City -->
                                            <div>
                                                <h5 style="margin: 0; font-size: 1.2rem; color: white;"><?php echo htmlspecialchars($fulladdressdb); ?></h5>
                                                <p style="margin: 0; font-size: 0.9rem; color: rgba(255, 255, 255, 0.8);"><?php echo htmlspecialchars($citydb); ?></p>
                                            </div>
                                        </div>
                                        <!-- House Name -->
                                        <div style="flex: 1; text-align: right;">
                                            <h2 style="margin: 0; font-size: 2rem; font-weight: bold; color: white;"><?php echo htmlspecialchars($namedb); ?></h2>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <br>
                        <!-- Inizio Sezione Collassabile: Dettagli Immobile -->
                        <div class="row">
                            <div class="col-lg-12">
                                <div class="card">
                                    <div class="card-header bg-primary d-flex justify-content-between align-items-center" id="details-heading">
                                        <!-- Titolo con pulsante per collassare/espandere -->
                                        <h4 class="mb-0 text-white">
                                            <button class="btn btn-link text-white" type="button" data-toggle="collapse" data-target="#details-collapse" aria-expanded="true" aria-controls="details-collapse">
                                                <?php echo $isNew ? "Carta d'Identità dell'Immobile" : "Dettagli dell'Immobile"; ?>
                                                <i class="fas fa-chevron-down ml-2"></i>
                                            </button>
                                        </h4>
                                        <!-- Pulsante Modifica -->
                                        <button id="edit-toggle" class="btn btn-light btn-sm">
                                            <i class="fas fa-pencil-alt"></i> Modifica
                                        </button>
                                    </div>
                                    <!-- Contenuto collassabile -->
                                    <div id="details-collapse" class="collapse" aria-labelledby="details-heading">
                                        <div class="card-body">
                                            <form id="home-form">
                                                <input type="hidden" name="idhome" value="<?php echo $idhome; ?>">

                                                <!-- Sezione Nome e Foto -->
                                                <div class="row">
                                                    <div class="col-md-8">
                                                        <div class="form-group">
                                                            <label>Nome Immobile</label>
                                                            <input type="text" value="<?php echo htmlspecialchars($namedb); ?>" id="name" name="name" class="form-control form-field" readonly>
                                                        </div>
                                                        <!-- Sezione Note -->
                                                        <div class="form-group">
                                                            <h5 class="text-primary"><i class="fas fa-sticky-note"></i> Note</h5>
                                                            <textarea id="comment" name="comment" rows="3" class="form-control form-field" readonly><?php echo htmlspecialchars($commentdb); ?></textarea>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-4 text-center">
                                                        <label>Foto dell'Immobile</label>
                                                        <div class="photo-container">
                                                            <input type="file" id="photo" name="photo" class="form-control form-field d-none" accept="image/*" disabled>
                                                            <img id="photo-preview" src="<?php echo !empty($homeData['mainphoto']) ? 'mainphoto/' . $homeData['mainphoto'] : 'assets/images/no-image.jpg'; ?>" alt="Anteprima Foto" class="img-fluid mt-2 rounded shadow" style="max-width: 200px;">
                                                        </div>
                                                        <small class="text-muted photo-hint d-none">Carica un'unica foto, verrà sovrascritta se ne scegli un'altra.</small>
                                                    </div>
                                                </div>

                                                <!-- Sezione Indirizzo -->
                                                <div class="border rounded p-3 mt-4">
                                                    <h5 class="text-primary"><i class="fas fa-map-marker-alt"></i> Indirizzo</h5>
                                                    <label>Indirizzo Completo</label>
                                                    <input type="text" value="<?php echo htmlspecialchars($fulladdressdb); ?>" id="fulladdress" name="fulladdress" class="form-control form-field" readonly>
                                                    <div id="map" class="mt-3" style="height: 300px;"></div>
                                                </div>

                                                <!-- Sezione Dati Catastali -->
                                                <div class="border rounded p-3 mt-4">
                                                    <h5 class="text-primary"><i class="fas fa-building"></i> Dati Catastali</h5>
                                                    <div class="row">
                                                        <div class="col-md-4">
                                                            <label>Comune Catastale</label>
                                                            <input type="text" value="<?php echo htmlspecialchars($cadastral_municipalitydb); ?>" id="cadastral_municipality" name="cadastral_municipality" class="form-control form-field" readonly>
                                                        </div>
                                                        <div class="col-md-4">
                                                            <label>Sezione</label>
                                                            <input type="text" value="<?php echo htmlspecialchars($cadastral_sectiondb); ?>" id="cadastral_section" name="cadastral_section" class="form-control form-field" readonly>
                                                        </div>
                                                        <div class="col-md-4">
                                                            <label>Foglio</label>
                                                            <input type="text" value="<?php echo htmlspecialchars($cadastral_sheetdb); ?>" id="cadastral_sheet" name="cadastral_sheet" class="form-control form-field" readonly>
                                                        </div>
                                                    </div>
                                                    <div class="row mt-2">
                                                        <div class="col-md-4">
                                                            <label>Particella</label>
                                                            <input type="text" value="<?php echo htmlspecialchars($cadastral_particledb); ?>" id="cadastral_particle" name="cadastral_particle" class="form-control form-field" readonly>
                                                        </div>
                                                        <div class="col-md-4">
                                                            <label>Subalterno</label>
                                                            <input type="text" value="<?php echo htmlspecialchars($cadastral_subdb); ?>" id="cadastral_sub" name="cadastral_sub" class="form-control form-field" readonly>
                                                        </div>
                                                        <div class="col-md-4">
                                                            <label>Categoria Catastale</label>
                                                            <input type="text" value="<?php echo htmlspecialchars($cadastral_categorydb); ?>" id="cadastral_category" name="cadastral_category" class="form-control form-field" readonly>
                                                        </div>
                                                    </div>
                                                    <div class="row mt-2">
                                                        <div class="col-md-4">
                                                            <label>Classe Catastale</label>
                                                            <input type="text" value="<?php echo htmlspecialchars($cadastral_classdb); ?>" id="cadastral_class" name="cadastral_class" class="form-control form-field" readonly>
                                                        </div>
                                                        <div class="col-md-4">
                                                            <label>Superficie (mq)</label>
                                                            <input type="number" step="0.01" value="<?php echo htmlspecialchars($cadastral_surfacedb); ?>" id="cadastral_surface" name="cadastral_surface" class="form-control form-field" readonly>
                                                        </div>
                                                        <div class="col-md-4">
                                                            <label>Rendita (€)</label>
                                                            <input type="number" step="0.01" value="<?php echo htmlspecialchars($cadastral_renditadbs); ?>" id="cadastral_rendita" name="cadastral_rendita" class="form-control form-field" readonly>
                                                        </div>
                                                    </div>
                                                </div>

                                                <!-- Sezione Geolocalizzazione (campi nascosti) -->
                                                <div class="row mt-3">
                                                    <div class="col-md-6">
                                                        <input type="hidden" id="latitude" name="latitude" value="<?php echo htmlspecialchars($latitudedb); ?>">
                                                    </div>
                                                    <div class="col-md-6">
                                                        <input type="hidden" id="longitude" name="longitude" value="<?php echo htmlspecialchars($longitudedb); ?>">
                                                    </div>
                                                    <div class="col-md-4">
                                                        <input type="hidden" id="zip" name="zip" value="<?php echo htmlspecialchars($zipdb); ?>">
                                                    </div>
                                                    <div class="col-md-4">
                                                        <input type="hidden" id="city" name="city" value="<?php echo htmlspecialchars($citydb); ?>">
                                                    </div>
                                                    <div class="col-md-4">
                                                        <input type="hidden" id="country" name="country" value="<?php echo htmlspecialchars($countrydb); ?>">
                                                    </div>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- Fine Sezione Collassabile: Dettagli Immobile -->

                        <!-- Inizio Sezione Collassabile: Proprietari -->
                        <div class="row">
                            <div class="col-lg-12">
                                <div class="card">
                                    <div class="card-header bg-success d-flex justify-content-between align-items-center" id="owners-heading">
                                        <!-- Titolo con pulsante per collassare/espandere -->
                                        <h4 class="mb-0 text-white">
                                            <button class="btn btn-link text-white" type="button" data-toggle="collapse" data-target="#owners-collapse" aria-expanded="false" aria-controls="owners-collapse">
                                                Proprietari
                                                <i class="fas fa-chevron-down ml-2"></i>
                                            </button>
                                        </h4>
                                    </div>
                                    <!-- Contenuto collassabile -->
                                    <div id="owners-collapse" class="collapse" aria-labelledby="owners-heading">
                                        <div class="card-body">
                                            <?php
                                            // Recupera i proprietari associati all'immobile
                                            $queryOwners = $conn->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 = ?
                    ");
                                            $queryOwners->bind_param('i', $idhome);
                                            $queryOwners->execute();
                                            $resultOwners = $queryOwners->get_result();

                                            // Recupera tutti i proprietari disponibili dell'utente per la selezione
                                            $queryAvailableOwners = $conn->prepare("
                        SELECT 
                            owner_id, 
                            first_name, 
                            last_name, 
                            company_name, 
                            tax_code 
                        FROM 
                            property_owners 
                        WHERE 
                            user_id = ? 
                            AND owner_id NOT IN (
                                SELECT owner_id FROM home_owners WHERE home_id = ?
                            )
                    ");
                                            $queryAvailableOwners->bind_param('ii', $iduserlogin, $idhome);
                                            $queryAvailableOwners->execute();
                                            $resultAvailableOwners = $queryAvailableOwners->get_result();
                                            ?>

                                            <!-- Proprietari associati -->
                                            <?php if ($resultOwners->num_rows > 0) { ?>
                                                <div id="ownersTable">
                                                    <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;
                                                            while ($owner = $resultOwners->fetch_assoc()) {
                                                                $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>
                                                </div>
                                            <?php } else { ?>
                                                <p class="text-muted">Nessun proprietario associato.</p>
                                            <?php } ?>

                                            <!-- Aggiungi proprietari -->
                                            <div class="mt-4">
                                                <h5 class="text-info">Assegna Proprietari</h5>
                                                <form id="addOwnerForm" method="POST" action="add-owner-to-home.php">
                                                    <input type="hidden" name="idhome" value="<?php echo $idhome; ?>">
                                                    <div class="form-group">
                                                        <label for="ownerSelect">Seleziona Proprietario</label>
                                                        <div id="ownerSelectContainer">
                                                            <select class="form-control" id="ownerSelect" name="owner_id" required>
                                                                <option value="">-- Seleziona --</option>
                                                                <?php while ($availableOwner = $resultAvailableOwners->fetch_assoc()) { ?>
                                                                    <option value="<?php echo $availableOwner['owner_id']; ?>">
                                                                        <?php
                                                                        echo htmlspecialchars($availableOwner['first_name'] . ' ' . $availableOwner['last_name']);
                                                                        if ($availableOwner['company_name']) {
                                                                            echo ' (' . htmlspecialchars($availableOwner['company_name']) . ')';
                                                                        }
                                                                        echo ' - ' . htmlspecialchars($availableOwner['tax_code']);
                                                                        ?>
                                                                    </option>
                                                                <?php } ?>
                                                                <option value="new_owner">➕ Aggiungi nuovo proprietario</option>
                                                            </select>
                                                        </div>
                                                    </div>
                                                    <div class="form-group">
                                                        <label for="ownershipPercentage">Percentuale di Proprietà</label>
                                                        <input type="number" step="0.01" class="form-control" id="ownershipPercentage"
                                                            name="ownership_percentage" placeholder="Inserisci la percentuale (es. 50.00)"
                                                            oninput="validatePercentage()" required>
                                                    </div>
                                                    <div class="form-group">
                                                        <label for="notes">Note</label>
                                                        <textarea class="form-control" id="notes" name="notes" rows="3" placeholder="Aggiungi eventuali note"></textarea>
                                                    </div>
                                                    <!-- Messaggio di errore -->
                                                    <small id="percentageError" class="text-danger" style="display:none;">La somma totale non può superare il 100%.</small>
                                                    <button type="submit" id="addOwnerBtn" class="btn btn-success mt-3">Aggiungi</button>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- Fine Sezione Collassabile: Proprietari -->

                        <!-- Modal Aggiungi Nuovo Proprietario -->
                        <div class="modal fade" id="newOwnerModal" tabindex="-1" aria-labelledby="newOwnerModalLabel" aria-hidden="true">
                            <div class="modal-dialog modal-lg">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="newOwnerModalLabel">Aggiungi Nuovo Proprietario</h5>
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">×</span>
                                        </button>
                                    </div>
                                    <div class="modal-body">
                                        <form id="newOwnerForm">
                                            <input type="hidden" name="user_id" value="<?php echo $iduserlogin; ?>">

                                            <div class="row">
                                                <!-- Tipo Proprietario -->
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label for="ownerType">Tipo Proprietario</label>
                                                        <select class="form-control" id="ownerType" name="owner_type" required>
                                                            <option value="individual">Persona Fisica</option>
                                                            <option value="company">Azienda</option>
                                                        </select>
                                                    </div>
                                                </div>

                                                <!-- Codice Fiscale / P. IVA -->
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label for="taxCode">Codice Fiscale / Partita IVA</label>
                                                        <input type="text" class="form-control" id="taxCode" name="tax_code" required>
                                                    </div>
                                                </div>

                                                <!-- Nome -->
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label for="firstName">Nome</label>
                                                        <input type="text" class="form-control" id="firstName" name="first_name">
                                                    </div>
                                                </div>

                                                <!-- Cognome -->
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label for="lastName">Cognome</label>
                                                        <input type="text" class="form-control" id="lastName" name="last_name">
                                                    </div>
                                                </div>

                                                <!-- Nome Azienda -->
                                                <div class="col-md-12">
                                                    <div class="form-group">
                                                        <label for="companyName">Nome Azienda</label>
                                                        <input type="text" class="form-control" id="companyName" name="company_name" disabled>
                                                    </div>
                                                </div>

                                                <!-- Email -->
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label for="email">Email</label>
                                                        <input type="email" class="form-control" id="email" name="email" required>
                                                    </div>
                                                </div>

                                                <!-- Telefono -->
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label for="phone">Telefono</label>
                                                        <input type="text" class="form-control" id="phone" name="phone">
                                                    </div>
                                                </div>

                                                <!-- Indirizzo -->
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label for="address">Indirizzo</label>
                                                        <input type="text" class="form-control" id="address" name="address">
                                                    </div>
                                                </div>

                                                <!-- CAP -->
                                                <div class="col-md-3">
                                                    <div class="form-group">
                                                        <label for="postalCode">CAP</label>
                                                        <input type="text" class="form-control" id="postalCode" name="postal_code">
                                                    </div>
                                                </div>

                                                <!-- Città -->
                                                <div class="col-md-3">
                                                    <div class="form-group">
                                                        <label for="city">Città</label>
                                                        <input type="text" class="form-control" id="city" name="city">
                                                    </div>
                                                </div>

                                                <!-- Provincia -->
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label for="province">Provincia</label>
                                                        <input type="text" class="form-control" id="province" name="province">
                                                    </div>
                                                </div>

                                                <!-- Nazione (Select2) -->
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label for="country">Nazione</label>
                                                        <select class="form-control" id="country" name="country">
                                                            <option value="">-- Seleziona --</option>
                                                            <?php
                                                            $queryCountries = $conn->query("SELECT id, name FROM auth_countries ORDER BY name");
                                                            while ($country = $queryCountries->fetch_assoc()) {
                                                                echo "<option value='{$country['id']}'>" . htmlspecialchars($country['name']) . "</option>";
                                                            }
                                                            ?>
                                                        </select>
                                                    </div>
                                                </div>

                                                <!-- Ruolo -->
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label for="role">Ruolo</label>
                                                        <input type="text" class="form-control" id="role" name="role">
                                                    </div>
                                                </div>

                                                <!-- Note -->
                                                <div class="col-md-12">
                                                    <div class="form-group">
                                                        <label for="notes">Note</label>
                                                        <textarea class="form-control" id="notes" name="notes" rows="3"></textarea>
                                                    </div>
                                                </div>
                                            </div>

                                            <button type="submit" class="btn btn-success">Salva Proprietario</button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Include SweetAlert2 -->
                        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
                        <!-- Include Select2 -->
                        <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
                        <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>

                        <script>
                            // Rotazione della freccia per la sezione Proprietari
                            document.addEventListener('DOMContentLoaded', function() {
                                const ownersCollapseElement = document.getElementById('owners-collapse');
                                ownersCollapseElement.addEventListener('show.bs.collapse', function() {
                                    document.querySelector('#owners-heading .fas').classList.remove('fa-chevron-down');
                                    document.querySelector('#owners-heading .fas').classList.add('fa-chevron-up');
                                });
                                ownersCollapseElement.addEventListener('hide.bs.collapse', function() {
                                    document.querySelector('#owners-heading .fas').classList.remove('fa-chevron-up');
                                    document.querySelector('#owners-heading .fas').classList.add('fa-chevron-down');
                                });
                            });

                            // Select2 per il campo "Nazione" nel modale
                            $(document).ready(function() {
                                $("#country").select2({
                                    width: '100%',
                                    placeholder: "Seleziona un paese...",
                                    allowClear: true
                                });

                                // Selezione del proprietario nel dropdown
                                $("#ownerSelect").change(function() {
                                    if ($(this).val() === "new_owner") {
                                        $("#newOwnerModal").modal("show");
                                        $(this).val("");
                                    }
                                });

                                // Abilita/disabilita i campi in base al tipo di proprietario
                                $("#ownerType").change(function() {
                                    if ($(this).val() === "company") {
                                        $("#companyName").prop("disabled", false);
                                        $("#firstName, #lastName").prop("disabled", true).val("");
                                    } else {
                                        $("#companyName").prop("disabled", true).val("");
                                        $("#firstName, #lastName").prop("disabled", false);
                                    }
                                });

                                // Invio dati AJAX per aggiungere il nuovo proprietario
                                $("#newOwnerForm").submit(function(e) {
                                    e.preventDefault();
                                    let formData = $(this).serialize();

                                    $.post("add-new-owner.php", formData, function(response) {
                                        let result = JSON.parse(response);

                                        if (result.success) {
                                            Swal.fire({
                                                icon: "success",
                                                title: "Proprietario aggiunto!",
                                                text: result.message,
                                                timer: 1500,
                                                showConfirmButton: false
                                            }).then(() => {
                                                $("#newOwnerModal").modal("hide");

                                                // Aggiungi il nuovo proprietario al dropdown
                                                $("#ownerSelect").prepend(`<option value="${result.owner_id}" selected>
                        ${result.owner_name} - ${result.tax_code}
                    </option>`);
                                            });
                                        } else {
                                            Swal.fire({
                                                icon: "error",
                                                title: "Errore!",
                                                text: result.message
                                            });
                                        }
                                    }).fail(function() {
                                        Swal.fire({
                                            icon: "error",
                                            title: "Errore!",
                                            text: "Si è verificato un problema."
                                        });
                                    });
                                });
                            });

                            // Validazione percentuale
                            document.addEventListener("DOMContentLoaded", function() {
                                function getTotalOwnership() {
                                    let total = 0;
                                    document.querySelectorAll(".ownership-percentage").forEach(function(el) {
                                        total += parseFloat(el.textContent) || 0;
                                    });
                                    return total;
                                }

                                function validatePercentage() {
                                    let totalOwnership = getTotalOwnership();
                                    let newPercentage = parseFloat(document.getElementById("ownershipPercentage").value) || 0;
                                    let remainingPercentage = 100 - totalOwnership;

                                    let errorMsg = document.getElementById("percentageError");
                                    let submitBtn = document.getElementById("addOwnerBtn");

                                    if (newPercentage > remainingPercentage) {
                                        errorMsg.style.display = "block";
                                        submitBtn.disabled = true;
                                    } else {
                                        errorMsg.style.display = "none";
                                        submitBtn.disabled = false;
                                    }
                                }

                                // Disabilita il form se già 100%
                                let addOwnerForm = document.getElementById("addOwnerForm");
                                let addOwnerBtn = document.getElementById("addOwnerBtn");
                                if (getTotalOwnership() >= 100) {
                                    addOwnerForm.style.display = "none";
                                    document.getElementById("totalOwnership").style.backgroundColor = "#28a745";
                                    document.getElementById("totalOwnership").style.color = "#fff";
                                }

                                // Aggiorna il totale e il colore
                                let totalOwnership = getTotalOwnership();
                                let totalCell = document.getElementById("totalOwnership");
                                totalCell.textContent = totalOwnership.toFixed(2) + "%";
                                if (totalOwnership >= 100) {
                                    totalCell.style.backgroundColor = "#28a745";
                                    totalCell.style.color = "#fff";
                                } else {
                                    totalCell.style.backgroundColor = "#ffc107";
                                    totalCell.style.color = "#212529";
                                }
                            });

                            // Rimozione proprietario
                            $(document).on('click', '.remove-owner-btn', function() {
                                const ownerId = $(this).data('id');
                                const idhome = "<?php echo $idhome; ?>";

                                Swal.fire({
                                    title: 'Sei sicuro?',
                                    text: 'Questa azione rimuoverà il proprietario selezionato.',
                                    icon: 'warning',
                                    showCancelButton: true,
                                    confirmButtonColor: '#d33',
                                    cancelButtonColor: '#3085d6',
                                    confirmButtonText: 'Sì, rimuovi',
                                    cancelButtonText: 'Annulla',
                                }).then((result) => {
                                    if (result.isConfirmed) {
                                        $.post('remove-owner-from-home.php', {
                                            owner_id: ownerId,
                                            idhome: idhome
                                        }, function(response) {
                                            try {
                                                const result = JSON.parse(response);
                                                if (result.success) {
                                                    Swal.fire({
                                                        icon: 'success',
                                                        title: 'Rimosso',
                                                        text: result.message,
                                                        timer: 1500,
                                                        showConfirmButton: false,
                                                    }).then(() => {
                                                        location.reload();
                                                    });
                                                } else {
                                                    Swal.fire({
                                                        icon: 'error',
                                                        title: 'Errore',
                                                        text: result.message,
                                                    });
                                                }
                                            } catch (error) {
                                                console.error('Errore di parsing JSON:', error);
                                                Swal.fire({
                                                    icon: 'error',
                                                    title: 'Errore',
                                                    text: 'Si è verificato un problema.',
                                                });
                                            }
                                        }).fail(function() {
                                            Swal.fire({
                                                icon: 'error',
                                                title: 'Errore',
                                                text: 'Impossibile completare la richiesta.',
                                            });
                                        });
                                    }
                                });
                            });

                            // Aggiunta proprietario
                            document.getElementById("addOwnerForm").addEventListener("submit", function(e) {
                                e.preventDefault();

                                let formData = new FormData(this);

                                fetch("add-owner-to-home.php", {
                                        method: "POST",
                                        body: formData,
                                    })
                                    .then(response => response.json())
                                    .then(data => {
                                        if (data.success) {
                                            Swal.fire({
                                                icon: "success",
                                                title: "Proprietario aggiunto!",
                                                text: data.message,
                                                timer: 1500,
                                                showConfirmButton: false
                                            }).then(() => {
                                                // Ricarica la pagina per aggiornare la tabella e il dropdown
                                                location.reload();
                                            });
                                        } else {
                                            Swal.fire({
                                                icon: "error",
                                                title: "Errore!",
                                                text: data.message
                                            });
                                        }
                                    })
                                    .catch(error => {
                                        console.error("Errore AJAX:", error);
                                        Swal.fire({
                                            icon: "error",
                                            title: "Errore!",
                                            text: "Si è verificato un problema con la richiesta."
                                        });
                                    });
                            });
                        </script>
                        <!-- Aggiungi il seguente script JavaScript -->
                        <script>
                            document.addEventListener('DOMContentLoaded', function() {
                                const editToggleBtn = document.getElementById('edit-toggle');
                                const formFields = document.querySelectorAll('.form-field');
                                const saveBtn = document.querySelector('.save-btn');
                                const photoInput = document.getElementById('photo');
                                const photoHint = document.querySelector('.photo-hint');

                                // Ottieni il valore di isNew dalla pagina PHP
                                const isNewRecord = <?php echo $isNew ? 'true' : 'false'; ?>;

                                // Variabile per tenere traccia dello stato di modifica
                                let editMode = isNewRecord;

                                // Se è un nuovo record, entra automaticamente in modalità modifica
                                if (isNewRecord) {
                                    // Modifica il testo del pulsante
                                    editToggleBtn.innerHTML = '<i class="fas fa-save"></i> Salva';
                                    editToggleBtn.classList.remove('btn-light');
                                    editToggleBtn.classList.add('btn-info');

                                    // Abilita tutti i campi
                                    formFields.forEach(field => {
                                        field.readOnly = false;
                                        field.disabled = false;
                                        if (field.type === 'file') {
                                            field.classList.remove('d-none');
                                        }
                                    });

                                    // Mostra pulsante salva e suggerimento foto
                                    saveBtn.classList.remove('d-none');
                                    photoHint.classList.remove('d-none');
                                }

                                // Gestione del click sul pulsante di modifica
                                editToggleBtn.addEventListener('click', function() {
                                    editMode = !editMode;

                                    if (editMode) {
                                        // Attiva modalità modifica
                                        editToggleBtn.innerHTML = '<i class="fas fa-save"></i> Salva';
                                        editToggleBtn.classList.remove('btn-light');
                                        editToggleBtn.classList.add('btn-success');

                                        // Abilita tutti i campi
                                        formFields.forEach(field => {
                                            field.readOnly = false;
                                            field.disabled = false;
                                            if (field.type === 'file') {
                                                field.classList.remove('d-none');
                                            }
                                        });

                                        // Mostra pulsante salva e suggerimento foto
                                        saveBtn.classList.remove('d-none');
                                        photoHint.classList.remove('d-none');
                                    } else {
                                        // Torna alla modalità visualizzazione
                                        editToggleBtn.innerHTML = '<i class="fas fa-pencil-alt"></i> Modifica';
                                        editToggleBtn.classList.remove('btn-info');
                                        editToggleBtn.classList.add('btn-light');

                                        // Disabilita tutti i campi
                                        formFields.forEach(field => {
                                            field.readOnly = true;
                                            field.disabled = true;
                                            if (field.type === 'file') {
                                                field.classList.add('d-none');
                                            }
                                        });

                                        // Nascondi pulsante salva e suggerimento foto
                                        saveBtn.classList.add('d-none');
                                        photoHint.classList.add('d-none');
                                    }
                                });
                            });
                        </script>

                        <script>
                            // Caricamento della mappa
                            function initMap() {
                                let map = new google.maps.Map(document.getElementById("map"), {
                                    center: {
                                        lat: 41.9028,
                                        lng: 12.4964
                                    }, // Roma
                                    zoom: 14
                                });

                                let marker = new google.maps.Marker({
                                    position: {
                                        lat: 41.9028,
                                        lng: 12.4964
                                    },
                                    map: map,
                                    draggable: true
                                });

                                marker.addListener("dragend", function() {
                                    let position = marker.getPosition();
                                    document.getElementById("latitude").value = position.lat();
                                    document.getElementById("longitude").value = position.lng();
                                });
                            }

                            // Cambio immagine al clic sulla foto
                            document.getElementById("photo-preview").addEventListener("click", function() {
                                document.getElementById("photo").click();
                            });

                            // Anteprima immagine selezionata
                            document.getElementById('photo').addEventListener('change', function(event) {
                                let file = event.target.files[0];
                                if (!file) return;

                                let formData = new FormData();
                                formData.append("photo", file);
                                formData.append("idhome", <?php echo $idhome; ?>);

                                let xhr = new XMLHttpRequest();
                                xhr.open("POST", "save-home.php", true);
                                xhr.onreadystatechange = function() {
                                    if (xhr.readyState === XMLHttpRequest.DONE) {
                                        let response = JSON.parse(xhr.responseText);
                                        if (response.success) {
                                            document.getElementById('photo-preview').src = "mainphoto/" + response.filename;
                                        } else {
                                            alert("Errore nel caricamento: " + response.message);
                                        }
                                    }
                                };
                                xhr.send(formData);
                            });
                        </script>

                        <!-- Inclusione API Google Maps -->
                        <script src="https://maps.googleapis.com/maps/api/js?key=TUACHIAVEAPI&callback=initMap" async defer></script>


                    </div><!-- container -->
                </div> <!-- Page content Wrapper -->
            </div> <!-- content -->
            <?php include('include/footer.php'); ?>
        </div>
    </div>

    <!-- Google Maps API for Autocomplete and Geolocation -->
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyADtQRKgCpJNnQCP8QvBeKDcm0TrTPpsGY&libraries=places&callback=initAutocomplete"></script>
    <script>
        let map, marker, autocomplete;

        // Funzione per inviare i dati del campo tramite AJAX
        function updateField(field, value, additionalData = {}) {
            const idhome = <?php echo $idhome; ?>;
            const inputField = document.getElementById(field);


            var xhr = new XMLHttpRequest();
            xhr.open("POST", "save-home.php", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

            xhr.onreadystatechange = function() {
                if (xhr.readyState === XMLHttpRequest.DONE) {

                    if (xhr.status === 200) {
                        inputField.classList.add("success-flash");
                        setTimeout(function() {
                            inputField.classList.remove("success-flash");
                        }, 1000);
                    } else {
                        console.error("Errore durante l'aggiornamento: " + xhr.responseText);
                    }
                }
            };

            let params = `field=${encodeURIComponent(field)}&value=${encodeURIComponent(value)}&idhome=${idhome}`;
            for (let key in additionalData) {
                params += `&${key}=${encodeURIComponent(additionalData[key])}`;
            }

            xhr.send(params);
        }


        // Funzione per la mappa e autocomplete
        function initAutocomplete() {
            const latitude = parseFloat(document.getElementById('latitude').value);
            const longitude = parseFloat(document.getElementById('longitude').value);

            const defaultLocation = {
                lat: 41.9028,
                lng: 12.4964
            }; // Default: Roma
            const location = !isNaN(latitude) && !isNaN(longitude) ? {
                lat: latitude,
                lng: longitude
            } : defaultLocation;

            // Inizializza la mappa
            map = new google.maps.Map(document.getElementById('map'), {
                center: location,
                zoom: 14
            });

            // Aggiungi un marker
            marker = new google.maps.Marker({
                position: location,
                map: map,
                draggable: true
            });

            google.maps.event.addListener(marker, 'dragend', function() {
                const position = marker.getPosition();
                document.getElementById('latitude').value = position.lat();
                document.getElementById('longitude').value = position.lng();

                // Aggiorna latitudine e longitudine
                updateField('latitude', position.lat());
                updateField('longitude', position.lng());
            });

            // Autocomplete per l'indirizzo
            autocomplete = new google.maps.places.Autocomplete(document.getElementById('fulladdress'), {
                types: ['geocode']
            });
            autocomplete.addListener('place_changed', fillInAddress);
        }

        // Riempie i campi dopo che un indirizzo è stato selezionato
        function fillInAddress() {
            const place = autocomplete.getPlace();

            if (!place.geometry) {
                console.error("Errore: Il luogo selezionato non contiene informazioni di geolocalizzazione.");
                return;
            }

            const location = place.geometry.location;


            // Controlla se gli elementi esistono prima di impostare i valori
            if (document.getElementById('latitude')) {
                document.getElementById('latitude').value = location.lat();
            }
            if (document.getElementById('longitude')) {
                document.getElementById('longitude').value = location.lng();
            }

            const addressComponents = place.address_components;
            let zip = "",
                city = "",
                country = "",
                address = "";

            addressComponents.forEach(component => {
                const types = component.types;
                if (types.includes("postal_code")) zip = component.long_name;
                if (types.includes("locality")) city = component.long_name;
                if (types.includes("country")) country = component.long_name;
                if (types.includes("street_number") || types.includes("route")) {
                    address += component.long_name + " ";
                }
            });

            if (document.getElementById('zip')) {
                document.getElementById('zip').value = zip;
            }
            if (document.getElementById('city')) {
                document.getElementById('city').value = city;
            }
            if (document.getElementById('country')) {
                document.getElementById('country').value = country;
            }
            if (document.getElementById('address')) {
                document.getElementById('address').value = address.trim();
            }
            if (document.getElementById('fulladdress')) {
                document.getElementById('fulladdress').value = place.formatted_address;
            }



            // Centra la mappa e sposta il marker
            if (map && marker) {
                map.setCenter(location);
                marker.setPosition(location);
            } else {
                console.error("Errore: Mappa o Marker non inizializzati correttamente.");
            }

            // Aggiorna i campi tramite AJAX
            updateField('fulladdress', place.formatted_address, {
                address: address.trim(),
                zip: zip,
                city: city,
                country: country,
                latitude: location.lat(),
                longitude: location.lng()
            });
        }



        // Event listener per aggiornamento automatico dei dati al cambio di valore
        const fieldsToUpdate = [
            'name', 'comment', 'cadastral_municipality', 'cadastral_section', 'cadastral_sheet',
            'cadastral_particle', 'cadastral_sub', 'cadastral_category', 'cadastral_class',
            'cadastral_surface', 'cadastral_rendita', 'cadastral_notes'
        ];

        fieldsToUpdate.forEach(field => {
            const inputField = document.getElementById(field);
            if (inputField) {
                inputField.addEventListener('change', function() {
                    updateField(field, this.value);
                });
            }
        });
    </script>
    <script>
        // Rotazione della freccia quando si collassa/espande
        document.addEventListener('DOMContentLoaded', function() {
            const collapseElement = document.getElementById('details-collapse');
            collapseElement.addEventListener('show.bs.collapse', function() {
                document.querySelector('#details-heading .fas').classList.remove('fa-chevron-down');
                document.querySelector('#details-heading .fas').classList.add('fa-chevron-up');
            });
            collapseElement.addEventListener('hide.bs.collapse', function() {
                document.querySelector('#details-heading .fas').classList.remove('fa-chevron-up');
                document.querySelector('#details-heading .fas').classList.add('fa-chevron-down');
            });
        });
    </script>


    <!-- jQuery -->
    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/js/popper.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
</body>

</html>