<?php
global $idhome, $isNew, $homeData, $namedb, $addressdb, $countrydb, $citydb, $zipdb, $commentdb, $latitudedb, $longitudedb, $fulladdressdb,
    $cadastral_municipalitydb, $cadastral_sectiondb, $cadastral_sheetdb, $cadastral_particledb, $cadastral_subdb, $cadastral_categorydb,
    $cadastral_classdb, $cadastral_surfacedb, $cadastral_renditadb;

require_once dirname(__DIR__) . '/class/db-functions.php';
$dbHandler = DBHandlerSelect::getInstance();
$pdo = $dbHandler->getConnection();

// Recupera i dati della casa dal database
$stmt = $pdo->prepare("SELECT * FROM home WHERE idhome = ?");
$stmt->execute([$idhome]);
$homeData = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$homeData) {
    die("Errore: Casa non trovata.");
}

// Popola le variabili globali con i dati recuperati
$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'] ?? '';
$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_renditadb = $homeData['cadastral_rendita'] ?? '';
?>

<style>
    /* Stile per il lucchetto */
    .lock-btn {
        font-size: 1.5rem;
        padding: 0.5rem 1rem;
        transition: all 0.3s ease;
    }

    .lock-btn.locked {
        color: #dc3545;
    }

    .lock-btn.unlocked {
        color: #28a745;
    }

    /* Flash verde per l'input */
    .input-flash {
        animation: flashGreen 0.5s ease-in-out;
    }

    @keyframes flashGreen {
        0% {
            background-color: #d4edda;
        }

        50% {
            background-color: #d4edda;
        }

        100% {
            background-color: transparent;
        }
    }

    /* Stile per il messaggio di salvataggio */
    .save-flash {
        animation: flashGreen 1s ease-in-out;
    }
</style>

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

    <!-- Lucchetto -->
    <div class="d-flex justify-content-between align-items-center mb-3">
        <button type="button" id="lock-btn" class="btn lock-btn locked" data-locked="true">
            <i class="fas fa-lock"></i>
        </button>
        <div id="save-message" class="alert d-none" role="alert"></div>
    </div>

    <form id="home-form">
        <input type="hidden" name="idhome" value="<?php echo $idhome; ?>">

        <!-- Sezione Dati Principali -->
        <h4 class="mt-4">Dati Principali</h4>
        <div class="form-group">
            <label>Nome</label>
            <input type="text" value="<?php echo htmlspecialchars($namedb); ?>" id="name" name="name" class="form-control" required readonly>
        </div>

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

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

        <!-- Sezione Mappa e Foto -->
        <div class="row mt-4">
            <div class="col-md-6 mb-3">
                <h5>Geolocalizzazione</h5>
                <div id="map" style="height: 200px; width: 100%; border-radius: 8px; border: 1px solid #ddd;"></div>
            </div>
            <div class="col-md-6 mb-3">
                <h5>Foto dell'immobile</h5>
                <div class="form-group">
                    <label for="photo">Carica Foto</label>
                    <input type="file" id="photo" name="photo" class="form-control" accept="image/*" readonly disabled>
                    <small class="text-muted">Carica un'unica foto, verrà sovrascritta se ne scegli un'altra.</small>
                </div>
                <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: 100%; height: 200px; object-fit: cover; border-radius: 8px; border: 1px solid #ddd;">
                </div>
            </div>
        </div>

        <!-- Sezione Dati Catastali -->
        <h4 class="mt-4">Dati Catastali (opzionali)</h4>
        <p class="text-muted mb-3">Questi campi non sono obbligatori e possono essere lasciati vuoti.</p>

        <h5>Identificativi Catastali</h5>
        <div class="row">
            <div class="col-md-6 form-group">
                <label>Comune Catastale</label>
                <input type="text" id="cadastral_municipality" name="cadastral_municipality" value="<?php echo htmlspecialchars($cadastral_municipalitydb); ?>" class="form-control" readonly>
            </div>
            <div class="col-md-6 form-group">
                <label>Sezione Catastale</label>
                <input type="text" id="cadastral_section" name="cadastral_section" value="<?php echo htmlspecialchars($cadastral_sectiondb); ?>" class="form-control" readonly>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6 form-group">
                <label>Foglio Catastale</label>
                <input type="text" id="cadastral_sheet" name="cadastral_sheet" value="<?php echo htmlspecialchars($cadastral_sheetdb); ?>" class="form-control" readonly>
            </div>
            <div class="col-md-6 form-group">
                <label>Particella Catastale</label>
                <input type="text" id="cadastral_particle" name="cadastral_particle" value="<?php echo htmlspecialchars($cadastral_particledb); ?>" class="form-control" readonly>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6 form-group">
                <label>Subalterno Catastale</label>
                <input type="text" id="cadastral_sub" name="cadastral_sub" value="<?php echo htmlspecialchars($cadastral_subdb); ?>" class="form-control" readonly>
            </div>
        </div>

        <h5 class="mt-3">Caratteristiche Catastali</h5>
        <div class="row">
            <div class="col-md-6 form-group">
                <label>Categoria Catastale</label>
                <input type="text" id="cadastral_category" name="cadastral_category" value="<?php echo htmlspecialchars($cadastral_categorydb); ?>" class="form-control" readonly>
            </div>
            <div class="col-md-6 form-group">
                <label>Classe Catastale</label>
                <input type="text" id="cadastral_class" name="cadastral_class" value="<?php echo htmlspecialchars($cadastral_classdb); ?>" class="form-control" readonly>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6 form-group">
                <label>Superficie Catastale (m²)</label>
                <input type="number" step="0.01" id="cadastral_surface" name="cadastral_surface" value="<?php echo htmlspecialchars($cadastral_surfacedb); ?>" class="form-control" readonly>
            </div>
            <div class="col-md-6 form-group">
                <label>Rendita Catastale (€)</label>
                <input type="text" id="cadastral_rendita" name="cadastral_rendita" value="<?php echo htmlspecialchars($cadastral_renditadb); ?>" class="form-control" readonly>
            </div>
        </div>

        <!-- Sezione Dettagli Indirizzo -->
        <h4 class="mt-4">Dettagli Indirizzo</h4>
        <div class="row">
            <div class="col-md-6 form-group">
                <label>CAP</label>
                <input type="text" id="zip" name="zip" value="<?php echo htmlspecialchars($zipdb); ?>" class="form-control" readonly>
            </div>
            <div class="col-md-6 form-group">
                <label>Città</label>
                <input type="text" id="city" name="city" value="<?php echo htmlspecialchars($citydb); ?>" class="form-control" readonly>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6 form-group">
                <label>Nazione</label>
                <select id="country" name="country" class="form-control">
                    <option value="<?php echo htmlspecialchars($countrydb); ?>" selected><?php echo htmlspecialchars($countrydb); ?></option>
                    <!-- Aggiungi altre opzioni se necessario -->
                </select>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6 form-group">
                <label>Latitudine</label>
                <input type="text" id="latitude" name="latitude" value="<?php echo htmlspecialchars($latitudedb); ?>" class="form-control" readonly>
            </div>
            <div class="col-md-6 form-group">
                <label>Longitudine</label>
                <input type="text" id="longitude" name="longitude" value="<?php echo htmlspecialchars($longitudedb); ?>" class="form-control" readonly>
            </div>
        </div>
    </form>
</div>

<script>
    // Gestione caricamento foto
    document.getElementById('photo').addEventListener('change', function(event) {
        if (document.getElementById('lock-btn').dataset.locked === 'true') {
            alert('Devi sbloccare la modifica prima di caricare una foto.');
            this.value = '';
            return;
        }

        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;
                    showSaveMessage("Foto caricata con successo!", "success");
                    document.getElementById('photo').value = '';
                    document.getElementById('photo').classList.add('input-flash');
                } else {
                    showSaveMessage("Errore nel caricamento della foto: " + response.message, "danger");
                }
            }
        };
        xhr.send(formData);
    });

    // Funzione per mostrare il messaggio di salvataggio
    function showSaveMessage(message, type) {
        const saveMessage = document.getElementById('save-message');
        saveMessage.className = `alert alert-${type} d-block save-flash`;
        saveMessage.textContent = message;
        setTimeout(() => {
            saveMessage.className = 'alert d-none';
        }, 3000);
    }

    // Gestione lucchetto e modalità modifica
    document.getElementById('lock-btn').addEventListener('click', function() {
        const isLocked = this.dataset.locked === 'true';

        if (isLocked) {
            Swal.fire({
                title: 'Conferma',
                text: 'Vuoi procedere alla modifica dei dati?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#28a745',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Sì, modifica',
                cancelButtonText: 'Annulla'
            }).then((result) => {
                if (result.isConfirmed) {
                    this.classList.remove('locked');
                    this.classList.add('unlocked');
                    this.innerHTML = '<i class="fas fa-lock-open"></i>';
                    this.dataset.locked = 'false';

                    // Rendi i campi editabili
                    document.querySelectorAll('input:not(#country), textarea').forEach(element => {
                        element.removeAttribute('readonly');
                        element.removeAttribute('disabled');
                    });
                }
            });
        } else {
            Swal.fire({
                title: 'Conferma',
                text: 'Vuoi bloccare le modifiche e salvare i dati?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Sì, blocca',
                cancelButtonText: 'Annulla'
            }).then((result) => {
                if (result.isConfirmed) {
                    this.classList.remove('unlocked');
                    this.classList.add('locked');
                    this.innerHTML = '<i class="fas fa-lock"></i>';
                    this.dataset.locked = 'true';

                    // Rendi i campi read-only
                    document.querySelectorAll('input:not(#country), textarea').forEach(element => {
                        element.setAttribute('readonly', true);
                        if (element.type === 'file') element.setAttribute('disabled', true);
                    });
                }
            });
        }
    });

    // Salvataggio automatico al cambio di un campo
    const fields = [
        'name', 'comment', 'fulladdress',
        'cadastral_municipality', 'cadastral_section', 'cadastral_sheet', 'cadastral_particle', 'cadastral_sub',
        'cadastral_category', 'cadastral_class', 'cadastral_surface', 'cadastral_rendita',
        'latitude', 'longitude', 'zip', 'city', 'country'
    ];

    fields.forEach(field => {
        const element = document.getElementById(field);
        if (element) {
            element.addEventListener('change', function() {
                if (field !== 'country' && document.getElementById('lock-btn').dataset.locked === 'true') return;

                let params = `idhome=${encodeURIComponent(<?php echo $idhome; ?>)}`;
                fields.forEach(f => {
                    const value = document.getElementById(f)?.value || '';
                    params += `&${f}=${encodeURIComponent(value)}`;
                });

                const 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) {
                            let response;
                            try {
                                response = JSON.parse(xhr.responseText);
                            } catch (e) {
                                showSaveMessage("Errore: Risposta non valida dal server.", "danger");
                                return;
                            }
                            if (response.success) {
                                showSaveMessage("Modifiche salvate con successo!", "success");
                                element.classList.add('input-flash');
                            } else {
                                showSaveMessage("Errore durante il salvataggio: " + response.message, "danger");
                            }
                        } else {
                            showSaveMessage("Errore di connessione: " + xhr.statusText, "danger");
                        }
                    }
                };

                xhr.send(params);
            });
        }
    });

    // Gestione mappa
    let map, marker, 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
        };
        const location = !isNaN(latitude) && !isNaN(longitude) ? {
            lat: latitude,
            lng: longitude
        } : defaultLocation;

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

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

        google.maps.event.addListener(marker, 'dragend', function() {
            if (document.getElementById('lock-btn').dataset.locked === 'true') return;

            const position = marker.getPosition();
            document.getElementById('latitude').value = position.lat();
            document.getElementById('longitude').value = position.lng();
            document.getElementById('latitude').dispatchEvent(new Event('change'));
        });

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

    function fillInAddress() {
        if (document.getElementById('lock-btn').dataset.locked === 'true') return;

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

        const location = place.geometry.location;

        document.getElementById('latitude').value = location.lat();
        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 + " ";
            }
        });

        document.getElementById('zip').value = zip;
        document.getElementById('city').value = city;
        document.getElementById('country').value = country;
        document.getElementById('fulladdress').value = address.trim();

        map.setCenter(location);
        marker.setPosition(location);
        document.getElementById('fulladdress').dispatchEvent(new Event('change'));
    }

    // Inizializza la mappa quando il DOM è pronto
    document.addEventListener('DOMContentLoaded', initAutocomplete);
</script>