<?php include('include/headscript.php');
$idyogaschool = 1;

?>
<?php
// Assuming you have an existing connection to the database
$conn = new mysqli($servername, $username, $password, $database);
// Fetch current values from the database
$query = $conn->prepare("SELECT * FROM yogaschool WHERE idyogaschool = ?");
$query->bind_param("i", $idyogaschool);
$query->execute();
$result = $query->get_result();
$schoolData = $result->fetch_assoc();

$schoolnamedb = $schoolData['nameschool'];
$addressdb = $schoolData['address'];
$countrydb = $schoolData['country'];
$referencemeailschooldb = $schoolData['referenceemailschool'];
$schooldescriptiondb = $schoolData['schooldescription'];
$shortschooldescription = $schoolData['shortschooldescription'];
$citydb = $schoolData['city'];
$zipdb = $schoolData['zip'];
$emailschooldb = $schoolData['emailschool'];
$referencenameschooldb = $schoolData['referencenameschool'];
$latitudedb = $schoolData['latitude'];
$longitudedb = $schoolData['longitude'];
?>
<!DOCTYPE html>
<html lang="en">

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

    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <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%;
        }
    </style>
</head>


<body class="fixed-left">

    <!-- Loader -->
    <div id="preloader">
        <div id="status">
            <div class="spinner"></div>
        </div>
    </div>

    <!-- Begin page -->
    <div id="wrapper">

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

        <!-- Start right Content here -->

        <div class="content-page">
            <!-- Start content -->
            <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">
                                    <div class="btn-group float-right">
                                        <ol class="breadcrumb hide-phone p-0 m-0">
                                            <li class="breadcrumb-item"><a href="#">YogiWhere</a></li>
                                            <li class="breadcrumb-item active">Dashboard</li>
                                        </ol>
                                    </div>
                                    <h4 class="page-title"><?php echo $myschool; ?></h4>
                                </div>
                            </div>
                        </div>
                        <!-- end page title end breadcrumb -->

                        <div class="row">

                            <div class="col-lg-12">
                                <div class="card card-body">
                                    <h4 class="card-title font-20 mt-0"><?php echo $myschool; ?></h4>
                                    <p class="font-13 text-muted">Here you can update your school details</p>
                                    <a href="#" class="btn btn-warning waves-effect waves-light"><?php echo $pagepreview; ?></a>
                                </div>
                            </div>



                        </div>
                        <div class="row">
                            <div class="col-xl-12">

                                <div class="card">
                                    <div class="card-body">

                                        <h4 class="mt-0 header-title"><?php echo $schooldetailstitle; ?></h4>
                                        <p class="text-muted mb-4 font-13"><?php echo $updateschooldetailstitle; ?>
                                        </p>

                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="p-20">
                                                    <form id="yogaschool-form">
                                                        <div class="form-group">
                                                            <label><?php echo $schoolname; ?></label>
                                                            <input type="text" value="<?php echo htmlspecialchars($schoolnamedb); ?>" id="nameschool" name="nameschool" class="form-control" onchange="updateField('nameschool', this.value)">
                                                        </div>

                                                        <div class="form-group">
                                                            <label><?php echo $referencemeailschool; ?></label>
                                                            <input type="text" value="<?php echo htmlspecialchars($referencemeailschooldb); ?>" id="referencemeailschool" name="referencemeailschool" class="form-control" onchange="updateField('referencemeailschool', this.value)">
                                                        </div>


                                                    </form>
                                                </div>
                                            </div>

                                            <div class="col-md-6">
                                                <div class="p-20">
                                                    <form>

                                                        <div class="form-group">
                                                            <label><?php echo $emailschool; ?></label>
                                                            <input type="text" value="<?php echo htmlspecialchars($emailschooldb); ?>" id="emailschool" name="emailschool" class="form-control" onchange="updateField('emailschool', this.value)">
                                                        </div>
                                                        <div class="form-group">
                                                            <label><?php echo $referencenameschool; ?></label>
                                                            <input type="text" value="<?php echo htmlspecialchars($referencenameschooldb); ?>" id="referencenameschool" name="referencenameschool" class="form-control" onchange="updateField('referencenameschool', this.value)">
                                                        </div>

                                                    </form>
                                                </div>
                                            </div> <!-- end col -->
                                        </div> <!-- end row -->
                                        <div class="row">
                                            <div class="col-md-12">
                                                <div class="p-20">
                                                    <div class="form-group">
                                                        <label><?php echo $shortschooldescriptiontitle; ?></label>
                                                        <input type="text" value="<?php echo htmlspecialchars($shortschooldescription); ?>" id="shortschooldescription" name="shortschooldescription" class="form-control" onchange="updateField('shortschooldescription', this.value)">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-12">
                                                <div class="p-20">
                                                    <div class="form-group">
                                                        <label><?php echo $schooldescription; ?></label>
                                                        <textarea id="schooldescription" name="schooldescription" rows="4" class="form-control" onchange="updateField('schooldescription', this.value)"><?php echo htmlspecialchars($schooldescriptiondb); ?></textarea>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="container mt-5">
                                            <h4 class="mb-4">Address (important for geolocalization)</h4>

                                            <!-- Full Address Input -->

                                            <!-- Full Address Input with Autocomplete -->
                                            <div class="form-group">
                                                <label><?php echo $fulladdresstitle; ?></label>
                                                <input type="text" id="fulladdress" name="fulladdress" class="form-control">
                                            </div>



                                            <!-- Geolocate Button -->
                                            <button id="geolocate-btn" class="btn btn-primary mb-4">Geolocate</button>

                                            <!-- Map -->
                                            <div id="map"></div>




                                            <!-- Display Address Components -->
                                            <div class="form-group">
                                                <label><?php echo $address; ?></label>
                                                <input type="text" value="<?php echo htmlspecialchars($addressdb); ?>" id="address" name="address" class="form-control" onchange="updateField('address', this.value)" readonly>
                                            </div>
                                            <div class="form-group">
                                                <label><?php echo $country; ?></label>
                                                <input type="text" value="<?php echo htmlspecialchars($countrydb); ?>" id="country" name="country" class="form-control" onchange="updateField('country', this.value)" readonly>
                                            </div>
                                            <div class="form-group">
                                                <label><?php echo $city; ?></label>
                                                <input type="text" value="<?php echo htmlspecialchars($citydb); ?>" id="city" name="city" class="form-control" onchange="updateField('city', this.value)" readonly>
                                            </div>
                                            <div class="form-group">
                                                <label><?php echo $zip; ?></label>
                                                <input type="text" value="<?php echo htmlspecialchars($zipdb); ?>" id="zip" name="zip" class="form-control" onchange="updateField('zip', this.value)" readonly>
                                            </div>
                                            <div class="form-group mt-4">
                                                <label>latitude</label>
                                                <input type="text" id="latitude" value="<?php echo htmlspecialchars($latitudedb); ?>" class="form-control" readonly>
                                            </div>
                                            <div class="form-group">
                                                <label>longitude</label>
                                                <input type="text" id="longitude" value="<?php echo htmlspecialchars($longitudedb); ?>" class="form-control" readonly>
                                            </div>


                                        </div>
                                    </div>
                                </div>

                            </div>


                        </div>

                        <!-- end row -->


                    </div><!-- container -->

                </div> <!-- Page content Wrapper -->

            </div> <!-- content -->

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

        </div>
        <!-- End Right content here -->

    </div>
    <!-- END wrapper -->



    <!-- Google Maps API with Places Library -->
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyADtQRKgCpJNnQCP8QvBeKDcm0TrTPpsGY&libraries=places&callback=initAutocomplete"></script>

    <script>
        let map, marker, geocoder, autocomplete;

        // Inizializza la mappa
        function initMap() {
            geocoder = new google.maps.Geocoder();

            // Recupera i valori di latitude e longitude dai campi input
            const latitude = parseFloat(document.getElementById('latitude').value);
            const longitude = parseFloat(document.getElementById('longitude').value);

            // Definisci un centro di default (Roma)
            let mapCenter = {
                lat: 41.9028, // latitudine di Roma
                lng: 12.4964 // longitudine di Roma
            };

            // Se latitude e longitude sono valide, usa quelle come centro
            if (!isNaN(latitude) && !isNaN(longitude)) {
                mapCenter = {
                    lat: latitude,
                    lng: longitude
                };
            }

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

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

            // Aggiungi l'evento per aggiornare latitudine e longitudine quando il marker viene spostato
            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 nel database tramite AJAX
                updateField('latitude', position.lat());
                updateField('longitude', position.lng());
            });
        }

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

            // Quando l'utente seleziona un indirizzo dalla lista
            autocomplete.addListener('place_changed', fillInAddress);

            // Inizializza anche la mappa dopo che l'Autocomplete è stato caricato
            initMap();
        }

        function fillInAddress() {
            // Ottieni i dettagli del luogo
            const place = autocomplete.getPlace();

            // Estrai le componenti dell'indirizzo
            splitAddress(place.address_components);

            // Posiziona il marker sulla mappa e aggiorna latitudine e longitudine
            const location = place.geometry.location;
            document.getElementById('latitude').value = location.lat();
            document.getElementById('longitude').value = location.lng();

            // Aggiorna latitudine e longitudine nel database tramite AJAX
            updateField('latitude', location.lat());
            updateField('longitude', location.lng());

            // Imposta la mappa con il nuovo centro
            map.setCenter(location);
            marker.setPosition(location);
        }

        function splitAddress(components) {
            let address = '';
            let city = '';
            let zip = '';
            let country = '';

            components.forEach(component => {
                const types = component.types;

                if (types.includes('street_number') || types.includes('route')) {
                    address += component.long_name + ' ';
                }

                if (types.includes('locality')) {
                    city = component.long_name;
                }

                if (types.includes('postal_code')) {
                    zip = component.long_name;
                }

                if (types.includes('country')) {
                    country = component.long_name;
                }
            });

            // Aggiorna i campi nel form
            document.getElementById('address').value = address.trim();
            document.getElementById('city').value = city;
            document.getElementById('zip').value = zip;
            document.getElementById('country').value = country;

            // Aggiorna anche nel database tramite AJAX
            updateField('address', address.trim());
            updateField('city', city);
            updateField('zip', zip);
            updateField('country', country);
        }
    </script>

    <script>
        function updateField(field, value) {
            var idyogaschool = <?php echo json_encode($idyogaschool); ?>;
            var inputField = document.getElementById(field);

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

            xhr.onreadystatechange = function() {
                if (xhr.readyState === XMLHttpRequest.DONE) {
                    if (xhr.status === 200) {
                        // Update the full address field
                        updateFullAddress();

                        // Show green flash on successful update
                        inputField.style.backgroundColor = "#d4edda"; // Light green
                        setTimeout(function() {
                            inputField.style.backgroundColor = ""; // Reset to original color
                        }, 500);
                    } else {
                        console.error("Error updating field: " + xhr.responseText);
                    }
                }
            };

            xhr.send("field=" + encodeURIComponent(field) + "&value=" + encodeURIComponent(value) + "&idyogaschool=" + encodeURIComponent(idyogaschool));
        }

        function updateFullAddress() {
            var address = document.getElementById('address').value;
            var city = document.getElementById('city').value;
            var zip = document.getElementById('zip').value;
            var country = document.getElementById('country').value;

            var fullAddress = address + ', ' + zip + ' ' + city + ', ' + country;
            document.getElementById('fulladdress').value = fullAddress;

            // Geocode the full address to get latitude and longitude
            geocodeAddress(fullAddress);
        }

        function geocodeAddress(fullAddress) {
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({
                'address': fullAddress
            }, function(results, status) {
                if (status === 'OK') {
                    var latitude = results[0].geometry.location.lat();
                    var longitude = results[0].geometry.location.lng();
                    document.getElementById('latitude').value = latitude;
                    document.getElementById('longitude').value = longitude;
                    updateLatLongInDatabase(latitude, longitude);
                } else {
                    console.error('Geocode was not successful for the following reason: ' + status);
                }
            });
        }

        function updateLatLongInDatabase(latitude, longitude) {
            var idyogaschool = <?php echo json_encode($idyogaschool); ?>;
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "update_yogaschool.php", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

            var data = "latitude=" + encodeURIComponent(latitude) +
                "&longitude=" + encodeURIComponent(longitude) +
                "&idyogaschool=" + encodeURIComponent(idyogaschool);

            xhr.send(data);
        }
    </script>

    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/js/popper.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
    <script src="assets/js/modernizr.min.js"></script>
    <script src="assets/js/detect.js"></script>
    <script src="assets/js/fastclick.js"></script>
    <script src="assets/js/jquery.slimscroll.js"></script>
    <script src="assets/js/jquery.blockUI.js"></script>
    <script src="assets/js/waves.js"></script>
    <script src="assets/js/jquery.nicescroll.js"></script>
    <script src="assets/js/jquery.scrollTo.min.js"></script>

    <script src="assets/plugins/chart.js/chart.min.js"></script>
    <script src="assets/pages/dashboard.js"></script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>


</body>

</html>