<div class="wrap menu-settings tools">
    <hr class="wp-header-end">
    
    <?php 
        include 'intestazione.php';
    ?>		

    <!-- Blocco prenotazioni -->
    <div class="row">
        <div class="col-6">
            <div class="postbox tools">
                <div class="inside">
                    <div>
                        <div class="text-center">

<?php 

    global $wpdb, $dataApi;
    $table_name = $wpdb->prefix.RINNOVOBOOKINGPREFIX.'_bookings';

    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_bookings'])) {
        $id_prenotazione = intval($_GET['id']);
        $cognome = sanitize_text_field($_POST['cognome']);
        $nome = sanitize_text_field($_POST['nome']);
        $email = sanitize_email($_POST['email']);    
        $telefono = sanitize_text_field($_POST['telefono']);
        $data = sanitize_text_field($_POST['data']);
        $ora = sanitize_text_field($_POST['ora']);
        $stato = sanitize_text_field($_POST['stato']);

        $risultato = $wpdb->update(
            $table_name,
            array(
                'cognome' => $cognome,      
                'nome' => $nome,
                'email' => $email,
                'telefono' => $telefono,
                'date' => $data,
                'time' => $ora,
                'stato' => $stato
            ),
            array('id' => $id_prenotazione),
            array('%s', '%s', '%s', '%s', '%s', '%s', '%s'),
            array('%d')
        );
    }

    if ($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['tipo'])) {
        $cosa = $_GET['tipo'];
        switch ($cosa) {
            case "modifica" :
                $id = intval($_GET['id']);                
                $results = $wpdb->get_results("SELECT * FROM $table_name WHERE `id` = '$id'");
                break; 
            case "elimina" :
                $id = intval($_GET['id']);
                $wpdb->delete($table_name, array('id' => $id));
                break;
        }
    }

    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_selected'])) {
        if (isset($_POST['selected_bookings']) && is_array($_POST['selected_bookings'])) {
            foreach ($_POST['selected_bookings'] as $booking_id) {
                $wpdb->delete($table_name, array('id' => intval($booking_id)));
            }
        }
    }

    $where_conditions ='';
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && (isset($_POST['cognome']) || isset($_POST['dataRicerca']) || isset($_POST['stato'])))  {
        $query_args = array();
        // Ricerca per cognome
        if (isset($_POST['cognome']) && !empty($_POST['cognome'])) {
            $where_conditions ="WHERE `cognome` LIKE '%".sanitize_text_field($_POST['cognome'])."%'";
        }
        
        // Ricerca per data
        if (isset($_POST['dataRicerca']) && !empty($_POST['dataRicerca'])) {
            $where_conditions ="WHERE `date` = '".date('Y-m-d', strtotime($_POST['dataRicerca']))."'";
        }
        
        // Ricerca per stato
        if (isset($_POST['stato']) && !empty($_POST['stato'])) {
            $stati_validi = array('active', 'closed', 'payment', 'sold');
            if (in_array($_POST['stato'], $stati_validi)) {
                $where_conditions ="WHERE `stato` = '".sanitize_text_field($_POST['stato'])."'"; 
            }
        }
    }
    
    $ricercaQuery = "SELECT * FROM $table_name $where_conditions ORDER BY 'idsede', 'date', 'time', 'cognome', 'nome' LIMIT %d OFFSET %d";

    // paginazione
    $pagina_corrente = isset($_GET['pagina']) ? max(1, intval($_GET['pagina'])) : 1;
    $record_per_pagina = 10;
    $offset = ($pagina_corrente - 1) * $record_per_pagina;

    $rb_bookings = $wpdb->get_results($wpdb->prepare(
        $ricercaQuery,
        $record_per_pagina,
        $offset
    ));

    $totale_record = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
    $totale_pagine = ceil($totale_record / $record_per_pagina);
?>

<!-- ricerca -->
<div class=" tools">
    <div class="inside">
        <div class="wrap">

            <div>
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <h3>Ricerca Personalizzata</h3>
                    <a href="<?php echo RINNOVOBOOKINGSTAGING ?>/wp-admin/admin.php?page=<?php echo RINNOVOBOOKINGPREFIX ?>prenotazioni" class="button button-primary">Elenco Generale</a>
                </div>
                <div><br><br></div>
                <div style="display: grid; grid-template-columns: repeat(3, 1fr);">
                    <div>
                        <form method="POST" action="<?php echo RINNOVOBOOKINGSTAGING ?>/wp-admin/admin.php?page=<?php echo RINNOVOBOOKINGPREFIX ?>prenotazioni">
                            <label for="cognome">Cognome:</label>
                            <input type="text" id="cognome" name="cognome" placeholder="cognome" required>
                            <button type="submit" class="button button-primary">Cerca</button>
                        </form>
                    </div>
                    <div>
                        <form method="POST">
                            <label for="data">Data:</label>
                            <input type="date" id="dataRicerca" name="dataRicerca" required>
                            <button type="submit" class="button button-primary">Cerca</button>
                        </form>
                    </div>
                    <div>
                        <form method="POST">
                            <label for="data">Stato:</label>
                            <select id="stato" name="stato" required>
                                <option value="active">Aperto</option>
                                <option value="sold">Pagato</option>
                                <option value="payment">Pagamento</option>
                                <option value="closed">Chiuso</option>
                            </select>
                            <button type="submit" class="button button-primary">Cerca</button>
                        </form>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>
<!-- ricerca -->

<div class=" tools">
    <div class="inside">
        <div class="wrap">
            <?php 
                if ($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['tipo']) && ($_GET['tipo'] == 'modifica')) {
            ?>
                <div class="postbox inside" style="background-color: lightblue;">
                    <h3>Modifica</h3>
                    <form method="POST">
                        <table class="form-table">
                            <tr>
                                <td>
                                    <label>Seleziona la sede</label>
                                    <select name="idsede" id="idsede" required>
                                        <?php
                                        $table_name = $wpdb->prefix . RINNOVOBOOKINGPREFIX . '_sedi';
                                        $sedi = $wpdb->get_results("SELECT idsede, nome FROM $table_name");
                                        foreach ($sedi as $sede) {
                                            $selected = ($sede->idsede == $results[0]->idsede) ? 'selected' : '';
                                            echo "<option value='{$sede->idsede}' {$selected}>{$sede->nome}</option>";
                                        }
                                        ?>
                                    </select>
                                </td>
                                <td>
                                    <label for="cognome">Cognome:</label>
                                    <input type="text" id="cognome" name="cognome" value="<?php echo $results[0]->cognome?>" required>
                                </td>
                                <td>
                                    <label for="nome">Nome:</label>
                                    <input type="text" id="nome" name="nome" value="<?php echo $results[0]->nome?>" required>
                                </td>
                                <td>
                                    <label for="data">Data:</label>
                                    <input type="date" id="data" name="data" value="<?php echo $results[0]->date?>" required>
                                </td>
                                <td>
                                    <label for="ora">Ora:</label>
                                    <input type="time" id="ora" name="ora" value="<?php echo $results[0]->time?>" required>
                                </td>
                                <td>
                                    <label for="email">Email:</label>
                                    <input type="email" id="email" name="email" value="<?php echo $results[0]->email?>" required>
                                </td>
                                <td>
                                    <label for="email">Telefono:</label>
                                    <input type="text" id="telefono" name="telefono" value="<?php echo $results[0]->telefono?>" required>
                                </td>
                                <td>
                                    <label for="stato">Stato:</label>
                                    <select name="stato" id="stato">
                                        <option value="active" <?php echo ($results[0]->stato == 'active') ? 'selected' :'' ?>>Aperto</option>
                                        <option value="closed" <?php echo ($results[0]->stato == 'closed') ? 'selected' :'' ?>>Chiuso</option>
                                        <option value="payment" <?php echo ($results[0]->stato == 'payment') ? 'selected' :'' ?>>Pagamento</option>
                                        <option value="sold" <?php echo ($results[0]->stato == 'sold') ? 'selected' :'' ?>>Pagato</option>
                                    </select>
                                </td>
                                <td>
                                    <input type="hidden" name="id" value="<?php echo $_GET['id'];?>">
                                    <input type="submit" name="update_bookings" class="button button-primary" value="Aggiorna">
                                </td>
                            </tr>
                        </table>
                    </form>
                </div>
            <?php
                }
            ?>
            
            <!-- Tabella di visualizzazione -->
            <h3>Elenco prenotazioni</h3>
            <form method="POST" action="">
                <div style="margin-bottom: 10px;">
                    <button type="submit" name="delete_selected" class="button button-primary" onclick="return confirm('Sei sicuro di voler eliminare le prenotazioni selezionate?');">Elimina selezionati</button>
                </div>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th style="width: 30px;"><input type="checkbox" id="select-all" class="booking-checkbox"></th>
                            <th>Sede</th>
                            <th>Cognome</th>
                            <th>Nome</th>
                            <th>Data</th>
                            <th>Ora</th>
                            <th>Email</th>
                            <th>Telefono</th>
                            <th>Stato</th>
                            <th>Azioni</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php                         
                        foreach ($rb_bookings as $slot) :
                        ?>
                            <tr>
                                <td>
                                    <input type="checkbox" name="selected_bookings[]" value="<?php echo $slot->id; ?>" class="booking-checkbox">
                                </td>
                                <td>
                                    <?php
                                    $table_name = $wpdb->prefix . RINNOVOBOOKINGPREFIX . '_sedi';
                                    $sede = $wpdb->get_var($wpdb->prepare("SELECT nome FROM $table_name WHERE idsede = %s", $slot->idsede));
                                    echo esc_html($sede);
                                    ?>
                                </td>
                                <td><?php echo esc_html($slot->cognome); ?></td>
                                <td><?php echo esc_html($slot->nome); ?></td>
                                <td><?php echo esc_html(date('d-m-Y', strtotime($slot->date))); ?></td>
                                <td><?php echo esc_html($slot->time); ?></td>
                                <td><?php echo esc_html($slot->email); ?></td>
                                <td><?php echo esc_html($slot->telefono); ?></td> 
                                <td>
                                    <?php 
                                    echo (($slot->stato == 'active') ? '<span class="badge badge-success">Aperto</span>' :
                                    (($slot->stato == 'closed') ? '<span class="badge badge-denied">Chiuso</span>' :
                                    (($slot->stato == 'payment') ? '<span class="badge badge-payment">Pagamento</span>' :
                                    (($slot->stato == 'sold') ? '<span class="badge badge-sold">Pagato</span>' :
                                    esc_html($slot->stato)))));                                 
                                    ?>
                                </td>
                                <td>
                                    <a href="<?php echo RINNOVOBOOKINGSTAGING ?>/wp-admin/admin.php?page=<?php echo RINNOVOBOOKINGPREFIX ?>prenotazioni&tipo=modifica&id=<?php echo $slot->id ?>" alt="modifica">
                                        <img src="<?php echo RINNOVOBOOKINGSTAGING ?>/wp-content/plugins/rinnovo_booking/admin/images/modifica.svg" alt="modifica" style="width: 20px; height: 20px;">
                                    </a>
                                    <a href="<?php echo RINNOVOBOOKINGSTAGING ?>/wp-admin/admin.php?page=<?php echo RINNOVOBOOKINGPREFIX ?>prenotazioni&tipo=elimina&id=<?php echo $slot->id ?>" alt="elimina">
                                        <img src="<?php echo RINNOVOBOOKINGSTAGING ?>/wp-content/plugins/rinnovo_booking/admin/images/cestino.svg" alt="elimina" style="width: 20px; height: 20px;">
                                    </a>
                                </td>
                            </tr>
                        <?php 
                        endforeach; 
                        ?>
                    </tbody>
                </table>
            </form>

            <script>
            document.addEventListener('DOMContentLoaded', function() {
                const selectAllCheckbox = document.getElementById('select-all');
                const bookingCheckboxes = document.getElementsByClassName('booking-checkbox');

                selectAllCheckbox.addEventListener('change', function() {
                    Array.from(bookingCheckboxes).forEach(checkbox => {
                        checkbox.checked = selectAllCheckbox.checked;
                    });
                });
            });
            </script>

            <!-- Paginazione -->
            <div class="bottom" style="padding-top: 10px;">
                <div class="tablenav-pages">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <span class="displaying-num">Visualizzato da <?php echo $offset + 1; ?> a <?php echo min($offset + $record_per_pagina, $totale_record); ?> di <?php echo $totale_record; ?></span>
                        <div class="pagination-links">
                            <a href="<?php echo RINNOVOBOOKINGSTAGING ?>/wp-admin/admin.php?page=<?php echo RINNOVOBOOKINGPREFIX ?>prenotazioni&pagina=1" class="button"><<</a>

                            <?php if ($pagina_corrente > 1) : ?>
                                <a href="<?php echo RINNOVOBOOKINGSTAGING ?>/wp-admin/admin.php?page=<?php echo RINNOVOBOOKINGPREFIX ?>prenotazioni&pagina=<?php echo $pagina_corrente - 1; ?>" class="prev-page button"><</a>
                            <?php endif; ?>
                            
                            <?php
                            $start_page = max(1, $pagina_corrente - 2);
                            $end_page = min($totale_pagine, $start_page + 4);
                            $start_page = max(1, $end_page - 4);

                            for ($i = $start_page; $i <= $end_page; $i++) :
                                $class = ($i == $pagina_corrente) ? 'button current' : 'button';
                            ?>
                                <a href="<?php echo RINNOVOBOOKINGSTAGING ?>/wp-admin/admin.php?page=<?php echo RINNOVOBOOKINGPREFIX ?>prenotazioni&pagina=<?php echo $i; ?>" class="<?php echo $class; ?>"><?php echo $i; ?></a>
                            <?php endfor; ?>
                            
                            <?php if ($pagina_corrente < $totale_pagine) : ?>
                                <a href="<?php echo RINNOVOBOOKINGSTAGING ?>/wp-admin/admin.php?page=<?php echo RINNOVOBOOKINGPREFIX ?>prenotazioni&pagina=<?php echo $pagina_corrente + 1; ?>" class="next-page button">></a>
                            <?php endif; ?>
                            <a href="<?php echo RINNOVOBOOKINGSTAGING ?>/wp-admin/admin.php?page=<?php echo RINNOVOBOOKINGPREFIX ?>prenotazioni&pagina=<?php echo $totale_pagine; ?>" class="button">>></a>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Paginazione -->

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

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