<?php 
    $cal = $this->crea_calendario($id_sede);
    echo $this->handle_menu($id_sede); 
?>
<div class="container-table">
    <div class="content">

        <div class="form-page-grid">
            <div class="content-border-search">
                <div><h4>Ricerca Personalizzata</h4></div>
                <div class="form-page-grid">
                    <div>
                        <form action="" method="GET" class="form-ricerca">
                            <input type="hidden" name="idsede" value="<?php echo $id_sede; ?>">
                            <label for="parola">Cognome:</label><br>
                            <input type="text" id="parola" name="parola" placeholder="cognome" required>
                            <button type="submit" class="action-button">Cerca</button>
                        </form>
                    </div>
                    <div>
                        <form action="" method="GET" class="form-ricerca">
                            <input type="hidden" name="idsede" value="<?php echo $id_sede; ?>">
                            <label for="data">Stato:</label><br>
                            <select id="stato" name="stato" required>
                                <option value="active">Aperto</option>
                                <option value="sold">Pagato</option>
                                <option value="payment">In Pagamento</option>
                                <option value="closed">Chiuso</option>
                            </select>
                            <button type="submit" class="action-button">Cerca</button>
                        </form>
                    </div>
                </div>
                <div style="margin-top: 20px !important;"><hr></div>
                <div>
                    <div>
                        <?php                                                 
                        echo $orari;
                        ?>
                    </div>
                </div>
            </div>
            <div class="content-border-search">
                <div>
                    <div id="calendar-controls">
                        <a href="" id="prev-month">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6">
                                <path stroke-linecap="round" stroke-linejoin="round" d="m11.25 9-3 3m0 0 3 3m-3-3h7.5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
                            </svg>
                        </a>
                        <span id="current-month"></span>
                        <a href="" id="next-month">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6">
                                <path stroke-linecap="round" stroke-linejoin="round" d="m12.75 15 3-3m0 0-3-3m3 3h-7.5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
                            </svg>
                        </a>
                    </div>
                    <div id="calendar_be-weekdays"></div>
                    <div id="calendar_be"></div>
                </div>
                <script>
                    document.addEventListener('DOMContentLoaded', function () {
                        const calendar = document.getElementById('calendar_be');
                        const calendarWeekdays = document.getElementById('calendar_be-weekdays');
                        const currentMonth = document.getElementById('current-month');
                        const prevMonth = document.getElementById('prev-month');
                        const nextMonth = document.getElementById('next-month');

                        let currentYear = new Date().getFullYear();
                        let currentMonthIndex = new Date().getMonth();

                        function generateCalendar(year, month) {
                            calendar.innerHTML = ''; // Pulisce il calendario
                            currentMonth.textContent = `${new Date(year, month).toLocaleString('it-IT', { month: 'long' })} ${year}`; // Imposta il mese e l'anno correnti

                            const firstDay = new Date(year, month, 1);
                            const lastDay = new Date(year, month + 1, 0);
                            const firstDayOfWeek = firstDay.getDay();
                            const lastDayOfMonth = lastDay.getDate();

                            const jsonData = '<?php echo json_encode($cal); ?>'; 
                            const parsedData = JSON.parse(jsonData);
                            const dateArray = parsedData.map(item => item.giorni); 

                            // Intestazione dei giorni della settimana
                            const weekdayNames = ['Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab', 'Dom'];
                            calendarWeekdays.innerHTML = '';
                            weekdayNames.forEach(day => {
                                const dayHeader = document.createElement('div');
                                dayHeader.textContent = day;
                                calendarWeekdays.appendChild(dayHeader);
                            });

                            // Calcola il giorno di inizio della settimana (0 = domenica, 1 = lunedì, ecc.)
                            let firstDayOfWeekAdjusted = firstDayOfWeek;
                            if (firstDayOfWeek === 0) { // Se è domenica
                                firstDayOfWeekAdjusted = 6; // Sposta a sabato
                            } else {
                                firstDayOfWeekAdjusted = firstDayOfWeek - 1; // Sposta indietro di un giorno
                            }

                            // Crea le celle per i giorni precedenti al primo giorno del mese
                            for (let i = 0; i < firstDayOfWeekAdjusted; i++) {
                                const cell = document.createElement('div');
                                cell.textContent = '';
                                calendar.appendChild(cell);
                            }

                            // Crea le celle per i giorni del mese
                            const urlParams = new URLSearchParams(window.location.search);
                            const idsede = urlParams.get('idsede');
                            for (let i = 1; i <= lastDayOfMonth; i++) {
                                const cell = document.createElement('div');
                                cell.textContent = i;
                                cell.classList.add('available');
                                
                                const date = `${year}-${(month + 1).toString().padStart(2, '0')}-${i.toString().padStart(2, '0')}`;
                                cell.setAttribute('data-date', date);
                                
                                if (dateArray.includes(date)) {
                                    cell.classList.add('selected');
                                }
                                
                                calendar.appendChild(cell);
                            }

                            // Crea le celle per i giorni successivi all'ultimo giorno del mese
                            const lastDayOfWeek = (lastDay.getDay() + 6) % 7; // Adeguamento per iniziare la settimana con lunedì
                            for (let i = 1; i < (7 - lastDayOfWeek); i++) {
                                const cell = document.createElement('div');
                                cell.textContent = '';
                                calendar.appendChild(cell);
                            }

                            // Aggiungi il gestore di eventi per il click sulle celle del calendario
                            const calendarCells = document.querySelectorAll('#calendar_be div.available');
                            calendarCells.forEach(function (cell) {
                                cell.addEventListener('click', function () {
                                    // Ottieni la data dalla cella
                                    let selectedDate = this.getAttribute('data-date');
                                    
                                    // Crea l'URL per la ricerca
                                    let url = new URL(window.location.href);
                                    url.searchParams.set('dataRicerca', selectedDate);
                                    
                                    // Ricarica la pagina con il nuovo parametro
                                    window.location.href = url.href;
                                });
                            });
                            
                        }

                        // Gestisce la navigazione tra i mesi
                        prevMonth.addEventListener('click', (event) => {
                            event.preventDefault(); // Impedisce il caricamento della pagina
                            if (currentMonthIndex === 0) {
                                currentMonthIndex = 11;
                                currentYear--;
                            } else {
                                currentMonthIndex--;
                            }
                            generateCalendar(currentYear, currentMonthIndex);
                        });

                        nextMonth.addEventListener('click', (event) => {
                            event.preventDefault(); // Impedisce il caricamento della pagina
                            if (currentMonthIndex === 11) {
                                currentMonthIndex = 0;
                                currentYear++;
                            } else {
                                currentMonthIndex++;
                            }
                            generateCalendar(currentYear, currentMonthIndex);
                        });

                        generateCalendar(currentYear, currentMonthIndex);
                    });
                </script>
            </div>        
        </div>
    </div>
</div>
<div>
    <div>
        <div>
            <br>
            <hr>
            <h3 class="rb-h3"> Ricerca: <?php if (strtotime($data) !== false) {
                            $data_estesa = $this->meseItaliano(date('j F Y', strtotime($data)));
                            echo $data_estesa;
                        } else {
                            switch($data) {
                                case 'active':
                                    echo 'Aperto';
                                    break;
                                case 'payment':
                                    echo 'In Pagamento';
                                    break;
                                case 'closed':
                                    echo 'Chiuso';
                                    break;
                                case 'sold':
                                    echo 'Pagato';
                                    break;
                                default:
                                    echo $data;
                                    break;
                                }
                        } ?>
            </h3>
        </div>

        <div>
            <div>
                <table class="table">
                    <tr>
                        <th width="30px"></th>
                        <th width="30px">N</th>
                        <th width="200px">Cognome e Nome</th>
                        <th width="100px">Data e Ora</th>                        
                        <th width="350px">Contatti</th>
                        <th width="130px">Provenienza</th>
                        <th width="50px">Tipo</th>
                        <th width="50px">Invio</th>
                        <th width="100px" style="text-align: center;">Stato</th>
                        <th width="100px" style="text-align: center;">Azioni</th>
                    </tr>
                    <?php echo $this->genera_tabella_prenotazioni($risultati, $id_sede); ?>
                </table>
            </div>
        </div>
    </div>
</div>


<div id="modalDettagli" class="modal">
    <div class="modal-content">
        <span class="close">&times;</span>
        <h2>Dettagli Prenotazione</h2>
        <div id="modalContent">
            <!-- Il contenuto verrà popolato dinamicamente -->
        </div>
    </div>
</div>
