<?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>
        .upload-area {
            border: 2px dashed #007bff;
            border-radius: 5px;
            background-color: #e9f7ff;
            text-align: center;
            padding: 20px;
            cursor: pointer;
        }

        .upload-area:hover {
            background-color: #d4efff;
        }

        .upload-icon {
            font-size: 50px;
            color: #007bff;
            margin-bottom: 10px;
        }

        .thumbnail {
            width: 50px;
            height: 50px;
            margin: 5px;
            display: inline-block;
        }

        .cover-photo {
            display: none;
        }

        .cover-photo+label {
            cursor: pointer;
            padding: 5px 10px;
            border: 2px solid #007bff;
            border-radius: 5px;
            background-color: #e9f7ff;
            color: #007bff;
            margin-left: 5px;
        }

        .cover-photo:checked+label {
            background-color: #007bff;
            color: white;
            border-color: #0056b3;
        }
    </style>


    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const uploadArea = document.querySelector('.upload-area');
            const fileUploadInput = document.getElementById('fileupload');
            const messageContainer = document.createElement('p');
            messageContainer.style.color = 'red';
            uploadArea.appendChild(messageContainer); // Aggiungi un messaggio sotto l'area di upload

            let currentPhotoCount = 0; // Variabile per tracciare il numero attuale di foto

            // Inizializza la tabella al caricamento della pagina
            updatePhotoTable();

            // Click sull'area di upload per attivare l'input file
            uploadArea.addEventListener('click', function() {
                fileUploadInput.click();
            });

            // Gestione dell'evento di selezione del file tramite input
            fileUploadInput.addEventListener('change', function(e) {
                const files = e.target.files;
                handleFiles(files);
            });

            // Gestione dell'evento dragover (trascinamento sopra l'area)
            uploadArea.addEventListener('dragover', function(e) {
                e.preventDefault();
                e.stopPropagation();
                uploadArea.style.backgroundColor = '#d4efff'; // Cambia colore durante il trascinamento
            });

            // Gestione dell'evento dragleave (uscita dall'area di trascinamento)
            uploadArea.addEventListener('dragleave', function(e) {
                e.preventDefault();
                e.stopPropagation();
                uploadArea.style.backgroundColor = '#e9f7ff'; // Ripristina il colore originale
            });

            // Gestione dell'evento drop (rilascio dell'immagine nell'area di upload)
            uploadArea.addEventListener('drop', function(e) {
                e.preventDefault();
                e.stopPropagation();
                uploadArea.style.backgroundColor = '#e9f7ff'; // Ripristina il colore dopo il rilascio
                const files = e.dataTransfer.files;
                handleFiles(files);
            });

            // Funzione per gestire il caricamento dei file
            function handleFiles(files) {
                const thumbnailContainer = document.getElementById('thumbnail-container');

                // Controlla se ci sono già più di 5 foto
                if (currentPhotoCount + files.length > 5) {
                    messageContainer.textContent = 'Non puoi caricare più di 5 foto!';
                    return;
                } else {
                    messageContainer.textContent = ''; // Rimuovi il messaggio di errore se il caricamento è valido
                }

                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    console.log('Elaborazione file:', file);

                    const fileType = file.type.toLowerCase();
                    const validImageTypes = ["image/jpeg", "image/png", "image/jpg"];

                    if (!validImageTypes.includes(fileType)) {
                        alert('Solo file JPG, JPEG e PNG sono consentiti.');
                        continue;
                    }

                    // Anteprima delle immagini
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const img = document.createElement('img');
                        img.src = e.target.result;
                        img.classList.add('thumbnail');
                        thumbnailContainer.appendChild(img);
                    };
                    reader.readAsDataURL(file);

                    // Invia il file tramite AJAX
                    const formData = new FormData();
                    formData.append('file', file);
                    formData.append('idyogaschool', '<?php echo $idyogaschool; ?>'); // Pass idyogaschool da PHP a JS

                    fetch('uploadphotos.php', {
                            method: 'POST',
                            body: formData
                        })
                        .then(response => response.json())
                        .then(data => {
                            console.log('Risposta del server:', data);
                            if (data.success) {
                                console.log('File caricato con successo');
                                updatePhotoTable();
                            } else {
                                console.error('Errore nel caricamento: ', data.message);
                                messageContainer.textContent = data.message; // Mostra l'errore del server
                            }
                        })
                        .catch(error => {
                            console.error('Errore nella richiesta:', error);
                        });
                }
            }

            // Funzione per aggiornare la tabella delle foto
            function updatePhotoTable() {
                fetch('getphotos.php?idyogaschool=<?php echo $idyogaschool; ?>')
                    .then(response => response.json())
                    .then(data => {
                        let html = '';
                        currentPhotoCount = data.length;

                        let coverFound = false;

                        data.forEach((photo, index) => {
                            if (photo.priority === '1') {
                                coverFound = true; // Trovata una foto con priority '1'
                            }

                            html += `<tr>
                    <td><img src="uploadphotoschool/${photo.photofilename}" class="thumbnail"></td>
                    <td>${photo.photofilename}</td>
                    <td>
                        <input type="radio" id="cover-${photo.id}" name="cover-photo" class="cover-photo" data-idphoto="${photo.id}" ${photo.priority === '1' ? 'checked' : ''}>
                        <label for="cover-${photo.id}">Set as Cover</label>
                    </td>
                    <td><a href="#" class="delete-photo" data-idphoto="${photo.id}">
                        <i class="fas fa-trash-alt text-danger font-16"></i>
                    </a></td>
                </tr>`;
                        });

                        document.getElementById('cont_file_photo').innerHTML = html;

                        // Se nessuna immagine ha priority '1', seleziona automaticamente la prima immagine
                        if (!coverFound && data.length > 0) {
                            const firstPhotoId = data[0].id;
                            setCoverPhoto(firstPhotoId); // Imposta la prima immagine come cover di default
                        }

                        // Aggiungi un listener per la selezione della cover
                        document.querySelectorAll('.cover-photo').forEach(input => {
                            input.addEventListener('change', function() {
                                const idphoto = this.dataset.idphoto;
                                setCoverPhoto(idphoto);
                            });
                        });
                    })
                    .catch(error => {
                        console.error('Errore nel recupero delle foto:', error);
                    });
            }


            function setCoverPhoto(idphoto) {
                fetch(`setcoverphoto.php?idphoto=${idphoto}&idyogaschool=<?php echo $idyogaschool; ?>`, {
                        method: 'GET'
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            console.log('Cover image impostata con successo');
                            updatePhotoTable();
                        } else {
                            console.error('Errore durante l\'impostazione della cover:', data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Errore nella richiesta:', error);
                    });
            }

            // Funzione per cancellare le foto
            document.addEventListener('click', function(event) {
                if (event.target.closest('.delete-photo')) {
                    event.preventDefault();
                    const idphoto = event.target.closest('.delete-photo').dataset.idphoto; // Recupera l'ID della foto
                    console.log('ID della foto:', idphoto);

                    if (idphoto) {
                        fetch(`deleteaddedphotos.php?idphoto=${idphoto}`, {
                                method: 'GET'
                            })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    console.log('Foto eliminata con successo');
                                    updatePhotoTable(); // Ricarica la tabella dopo la cancellazione
                                } else {
                                    console.error('Errore durante la cancellazione:', data.message);
                                }
                            })
                            .catch(error => {
                                console.error('Errore nella richiesta:', error);
                            });
                    } else {
                        console.error('ID della foto non definito!');
                    }
                }
            });
        });
    </script>


</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>
                                    <!-- Area di caricamento -->
                                    <div class="upload-area" id="uploadfile">
                                        <div class="upload-icon">
                                            <i class="fas fa-cloud-upload-alt"></i>
                                        </div>
                                        <p>Aggiungi Foto</p>
                                        <input type="file" id="fileupload" multiple accept="image/*" style="display:none;">
                                    </div>



                                    <!-- Tabella per visualizzare le immagini caricate -->
                                    <table class="table table-bordered mt-3">
                                        <thead>
                                            <tr>
                                                <th>Thumbnail</th>
                                                <th>Nome File</th>
                                                <th>Cover Image</th>
                                                <th>Azione</th>
                                            </tr>
                                        </thead>
                                        <tbody id="cont_file_photo">
                                            <!-- Le foto caricate saranno mostrate qui -->
                                        </tbody>
                                    </table>


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





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