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

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

// 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
}

// Se esiste già l'idhome, carica i dati della casa
$query = $conn->prepare("SELECT * FROM home WHERE idhome = ? AND iduser = ?");
$query->bind_param("ii", $idhome, $iduserlogin);
$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>


                        <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">
                                        <h4 class="mb-0 text-white"><?php echo $isNew ? "Carta d'Identità dell'Immobile" : "Dettagli dell'Immobile"; ?></h4>
                                        <button id="edit-toggle" class="btn btn-light btn-sm">
                                            <i class="fas fa-pencil-alt"></i> Modifica
                                        </button>
                                    </div>
                                    <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>

                                            <button type="submit" class="btn btn-primary mt-3 w-100 save-btn d-none"><i class="fas fa-save"></i> Salva</button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>

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

                                let editMode = false;

                                editToggleBtn.addEventListener('click', function() {
                                    editMode = !editMode;

                                    if (editMode) {
                                        // Attiva modalità modifica
                                        editToggleBtn.innerHTML = '<i class="fas fa-eye"></i> Visualizza';
                                        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');
                                    } 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) {
                                    let reader = new FileReader();
                                    reader.onload = function(e) {
                                        document.getElementById("photo-preview").src = e.target.result;
                                    };
                                    reader.readAsDataURL(file);
                                }
                            });
                        </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>



    <!-- 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>