<?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'];
?>



<!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 card-body">
                                    <h4 class="card-title font-20 mt-0"><?php echo $isNew ? "Aggiungi una nuova casa" : "Modifica la tua casa"; ?></h4>
                                    <form id="home-form">
                                        <input type="hidden" name="idhome" value="<?php echo $idhome; ?>">

                                        <div class="form-group">
                                            <label>Nome</label>
                                            <input type="text" value="<?php echo htmlspecialchars($namedb); ?>" id="name" name="name" class="form-control" required>
                                        </div>

                                        <div class="form-group">
                                            <label>Nota</label>
                                            <textarea id="comment" name="comment" rows="4" class="form-control"><?php echo htmlspecialchars($commentdb); ?></textarea>
                                        </div>

                                        <h4 class="mt-4">Carica Foto</h4>
                                        <div class="form-group">
                                            <label for="photo">Foto dell'immobile</label>
                                            <input type="file" id="photo" name="photo" class="form-control" accept="image/*">
                                            <small class="text-muted">Carica un'unica foto, verrà sovrascritta se ne scegli un'altra.</small>
                                        </div>

                                        <!-- Anteprima della foto -->
                                        <div class="form-group">
                                            <img id="photo-preview" src="<?php echo !empty($homeData['mainphoto']) ? 'mainphoto/' . $homeData['mainphoto'] : 'assets/images/no-image.jpg'; ?>" alt="Anteprima Foto" style="max-width: 200px; display: block; margin-top: 10px;">
                                        </div>

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


                                        <h4 class="mt-4">Indirizzo Completo</h4>
                                        <div class="form-group">
                                            <label>Indirizzo Completo</label>
                                            <input type="text" value="<?php echo htmlspecialchars($fulladdressdb); ?>" id="fulladdress" name="fulladdress" class="form-control">
                                        </div>

                                        <h4 class="mt-4">Geolocalizzazione</h4>
                                        <div id="map"></div>

                                        <div class="form-group mt-4">
                                            <label>CAP</label>
                                            <input type="text" id="zip" name="zip" value="<?php echo htmlspecialchars($zipdb); ?>" class="form-control" readonly>
                                        </div>
                                        <div class="form-group">
                                            <label>Città</label>
                                            <input type="text" id="city" name="city" value="<?php echo htmlspecialchars($citydb); ?>" class="form-control" readonly>
                                        </div>
                                        <div class="form-group">
                                            <label>Nazione</label>
                                            <input type="text" id="country" name="country" value="<?php echo htmlspecialchars($countrydb); ?>" class="form-control" readonly>
                                        </div>

                                        <div class="form-group mt-4">
                                            <label>Latitudine</label>
                                            <input type="text" id="latitude" name="latitude" value="<?php echo htmlspecialchars($latitudedb); ?>" class="form-control" readonly>
                                        </div>
                                        <div class="form-group">
                                            <label>Longitudine</label>
                                            <input type="text" id="longitude" name="longitude" value="<?php echo htmlspecialchars($longitudedb); ?>" class="form-control" readonly>
                                        </div>

                                    </form>
                                </div>
                            </div>
                        </div>
                    </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 location: Rome
            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;

            // Imposta latitudine e longitudine se esistono gli elementi corrispondenti
            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 = "";

            // Itera sui componenti dell'indirizzo per assegnare valori a CAP, città, nazione e indirizzo
            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 + " ";
                }
            });

            // Imposta i valori se esistono gli elementi corrispondenti
            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();
            }

            // Centra la mappa e sposta il marker nella nuova posizione
            map.setCenter(location);
            marker.setPosition(location);

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



        // Aggiorna i dati tramite AJAX al cambio di valore
        document.getElementById('name').addEventListener('change', function() {
            updateField('name', this.value);
        });

        document.getElementById('comment').addEventListener('change', function() {
            updateField('comment', 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>