<style>
.badge-success {
    color: green;
    background-color: lightgreen;
    border: 1px solid green;
    border-radius: 5px;
    padding: 5px;
}

.badge-denied {
    color: white;
    background-color: lightcoral;
    border: 1px solid red;
    border-radius: 5px;
    padding: 5px;
}
</style>

<?php 
    require_once dirname(plugin_dir_path(__FILE__)) . '/core/RinnovoBookingService.php';
    use RinnovoBooking\Core\RinnovoBookingService;


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

    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_time_slot'])) {
        $idSede = sanitize_text_field($_POST['idsede']);
        $day_of_week = sanitize_text_field($_POST['day_of_week']);
        $start_time = sanitize_text_field($_POST['start_time']);
        $end_time = sanitize_text_field($_POST['end_time']);
        $max_bookings = intval($_POST['max_bookings']);
        $max_slots = intval($_POST['max_slots']);
        $minutes_slots = intval($_POST['minutes_slots']);
        $services = json_encode($_POST['services']);

        $wpdb->insert($table_name, [
            'idsede'=> $idSede, 
            'day_of_week' => $day_of_week,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'max_bookings' => $max_bookings,
            'max_slots' => $max_slots,
            'minutes_slots' => $minutes_slots,
            'services' => $services,    
        ]);
    }

    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_time_slot'])) {
        $idSede = sanitize_text_field($_POST['idsede']);
        $day_of_week = sanitize_text_field($_POST['upd_day_of_week']);
        $start_time = sanitize_text_field($_POST['upd_start_time']);
        $end_time = sanitize_text_field($_POST['upd_end_time']);
        $max_bookings = intval($_POST['upd_max_bookings']);
        $max_slots = intval($_POST['upd_max_slots']);
        $minutes_slots = intval($_POST['upd_minutes_slots']);
        $services = json_encode($_POST['services']);

        // Modifica l'entry esistente invece di inserire una nuova
        $wpdb->update($table_name, [
            'idsede' => $idSede,
            'day_of_week' => $day_of_week,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'max_bookings' => $max_bookings,
            'max_slots' => $max_slots,
            'minutes_slots' => $minutes_slots,
            'services' => $services,    
        ], ['id' => intval($_POST['id'])]); 
    }

    if ($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['tipo'])) {
        $cosa = $_GET['tipo'];
        switch ($cosa) {
            case "cancella" :
                $id = intval($_GET['id']);                
                $wpdb->delete($table_name, array('id' => $id), array('%d'));
                $RinnovoBookingService = new RinnovoBookingService();
                $RinnovoBookingService->scriviLog('sistema', 'Fascia oraria cancellata');
                break;

            case "modifica" :
                $id = intval($_GET['id']);                
                $results = $wpdb->get_results("SELECT * FROM $table_name WHERE `id` = '$id'");
                $results[0]->services = json_decode($results[0]->services) ?? [];
                break; 
        }
    }

    $time_slots = $wpdb->get_results("SELECT * FROM $table_name ORDER BY idsede, day_of_week, start_time");

?>
<div class="postbox tools">
    <div class="inside">
        <div class="wrap">

            <div>                
                <form method="POST">                    
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                        <div>
                            <h3>Configura Fasce Orarie</h3>
                            <div style="margin-bottom: 20px;">
                                <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) {
                                        echo "<option value='{$sede->idsede}'>{$sede->nome}</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                            <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px;">                                
                                <div>
                                    <label for="day_of_week">Giorno della Settimana</label>
                                    <select name="day_of_week" id="day_of_week" style="width: 120px;" required>
                                        <option value="Lunedì">Lunedì</option>
                                        <option value="Martedì">Martedì</option>
                                        <option value="Mercoledì">Mercoledì</option>
                                        <option value="Giovedì">Giovedì</option>
                                        <option value="Venerdì">Venerdì</option>
                                        <option value="Sabato">Sabato</option>
                                        <option value="Domenica">Domenica</option>
                                    </select>
                                </div>
                                <div>
                                    <label>Ora di Inizio</label><br>
                                    <input type="time" name="start_time" id="start_time" style="width: 120px;" required>
                                </div>
                                <div>
                                    <label>Ora di Fine</label><br>
                                    <input type="time" name="end_time" id="end_time" style="width: 120px;" required>
                                </div>
                                <div>
                                    <label>Prenotazioni per fascia</label><br>
                                    <input type="number" name="max_bookings" id="max_bookings" value="1" style="width: 120px;" required>
                                </div>
                                <div>
                                    <label>Numero di slot aperti</label><br>
                                    <input type="number" name="max_slots" id="max_slots" value="3" style="width: 120px;" required>
                                </div>
                                <div>
                                    <label>Minuti tra slots</label><br>
                                    <input type="number" name="minutes_slots" id="minutes_slots" value="5" style="width: 120px;" required>
                                </div>                            
                            </div>
                        </div>
                        <div style="border-left: 1px solid #ddd; padding-left: 20px;">
                            <h3>Servizi Attivi</h3>
                                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                                    <div>
                                        <input type="checkbox" name="services[]" id="services" value="rinnovo" checked>
                                        <label for="services">Rinnovo</label>
                                    </div>
                                    <div>
                                        <input type="checkbox" name="services[]" id="services" value="conseguimento">
                                        <label for="services">Conseguimento</label>
                                    </div>
                                    <div>
                                        <input type="checkbox" name="services[]" id="services" value="porto_d_armi">
                                        <label for="services">Porto d'armi</label>
                                    </div>
                                    <div>
                                        <input type="checkbox" name="services[]" id="services" value="estensione">
                                        <label for="services">Estensione</label>
                                    </div>
                                    <div>
                                        <input type="checkbox" name="services[]" id="services" value="duplicato_documento">
                                        <label for="services">Duplicato documento</label>
                                    </div>
                                    <div>
                                        <input type="checkbox" name="services[]" id="services" value="rinnovo_patente_nautica">
                                        <label for="services">Rinnovo nautica</label>                                    
                                    </div>
                                </div>

                        </div>
                    </div>
                    <div style="margin-top: 20px; display: flex; justify-content: center;">
                        <input type="submit" name="save_time_slot" class="button button-primary" value="Salva Fascia Oraria">
                    </div>
                </form>
            </div>  

            <br><hr><br>

            <?php 
                if ($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['tipo']) && ($_GET['tipo'] == 'modifica')) {
            ?>
                <div class="postbox inside">
                    <div style="background-color: lightblue; margin: 10px; padding: 10px;">
                        <form method="POST">
                            <input type="hidden" name="id" value="<?php echo $_GET['id'];?>">
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                                <div>
                                    <h3>Modifica Fasce Orarie</h3>
                                    <div style="margin-bottom: 20px;">
                                        <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>
                                    </div>
                                    <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px;">                                
                                        <div>
                                            <label for="upd_day_of_week">Giorno della Settimana</label>
                                            <select name="upd_day_of_week" id="upd_day_of_week" style="width: 120px;" required>
                                                <option value="Lunedì" <?php echo $results[0]->day_of_week == 'Lunedì' ? 'selected' : ''; ?> >Lunedì</option>
                                                <option value="Martedì" <?php echo $results[0]->day_of_week == 'Martedì' ? 'selected' : ''; ?> >Martedì</option>
                                                <option value="Mercoledì" <?php echo $results[0]->day_of_week == 'Mercoledì' ? 'selected' : ''; ?> >Mercoledì</option>
                                                <option value="Giovedì" <?php echo $results[0]->day_of_week == 'Giovedì' ? 'selected' : ''; ?> >Giovedì</option>
                                                <option value="Venerdì" <?php echo $results[0]->day_of_week == 'Venerdì' ? 'selected' : ''; ?> >Venerdì</option>
                                                <option value="Sabato" <?php echo $results[0]->day_of_week == 'Sabato' ? 'selected' : ''; ?> >Sabato</option>
                                                <option value="Domenica" <?php echo $results[0]->day_of_week == 'Domenica' ? 'selected' : ''; ?> >Domenica</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label>Ora di Inizio</label><br>
                                            <input type="time" name="upd_start_time" id="upd_start_time" value="<?php echo $results[0]->start_time?>" style="width: 120px;" required>
                                        </div>
                                        <div>
                                            <label>Ora di Fine</label><br>
                                            <input type="time" name="upd_end_time" id="upd_end_time" value="<?php echo $results[0]->end_time?>" style="width: 120px;" required>
                                        </div>
                                        <div>
                                            <label>Prenotazioni per fascia</label><br>
                                            <input type="number" name="upd_max_bookings" id="upd_max_bookings" value="<?php echo $results[0]->max_bookings?>" style="width: 120px;" required>
                                        </div>
                                        <div>
                                            <label>Numero di slot aperti</label><br>
                                            <input type="number" name="upd_max_slots" id="upd_max_slots" value="<?php echo $results[0]->max_slots?>" style="width: 120px;" required>
                                        </div>
                                        <div>
                                            <label>Minuti tra slots</label><br>
                                            <input type="number" name="upd_minutes_slots" id="upd_minutes_slots" value="<?php echo $results[0]->minutes_slots?>" style="width: 120px;" required>
                                        </div>                            
                                    </div>
                                </div>
                                <div style="border-left: 1px solid #ddd; padding-left: 20px;">
                                    <h3>Modifica Servizi</h3>
                                        <div style="display: grid; grid-template-columns: 1fr 1fr ; gap: 20px;">
                                                <div>
                                                    <input type="checkbox" name="services[]" value="rinnovo" <?php echo in_array('rinnovo', $results[0]->services) ? 'checked' : ''; ?>>
                                                    <label for="services">Rinnovo</label>
                                                </div>
                                                <div>
                                                    <input type="checkbox" name="services[]" value="conseguimento" <?php echo in_array('conseguimento', $results[0]->services) ? 'checked' : ''; ?>>
                                                    <label for="services">Conseguimento</label>
                                                </div>
                                                <div>
                                                    <input type="checkbox" name="services[]" value="porto_d_armi" <?php echo in_array('porto_d_armi', $results[0]->services) ? 'checked' : ''; ?>>
                                                    <label for="services">Porto d'armi</label>
                                                </div>
                                                <div>
                                                    <input type="checkbox" name="services[]" value="estensione" <?php echo in_array('estensione', $results[0]->services) ? 'checked' : ''; ?>>
                                                    <label for="services">Estensione</label>
                                                </div>
                                                <div>
                                                    <input type="checkbox" name="services[]" value="duplicato_documento" <?php echo in_array('duplicato_documento', $results[0]->services) ? 'checked' : ''; ?>>
                                                    <label for="services">Duplicato documento</label>
                                                </div>
                                                <div>
                                                    <input type="checkbox" name="services[]" value="rinnovo_patente_nautica" <?php echo in_array('rinnovo_patente_nautica', $results[0]->services) ? 'checked' : ''; ?>>
                                                    <label for="services">Rinnovo nautica</label>
                                                </div>

                                </div>
                            </div>
                            <div style="margin-top: 20px; display: flex; justify-content: center;">                            
                                <input type="submit" name="update_time_slot" class="button button-primary" value="Aggiorna">
                            </div>
                        </form>
                    </div>
                </div>
            <?php
                }
            ?>
            
            <!-- Tabella di visualizzazione -->
            <h3>Fasce Orarie Esistenti</h3>
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th style="width: 200px;">Sede</th>
                        <th style="width: 100px;">Giorno</th>
                        <th style="width: 100px;">Ora di Inizio</th>
                        <th style="width: 100px;">Ora di Fine</th>
                        <th style="width: 80px;">Per Fascia</th>
                        <th style="width: 80px;">Aperte</th>
                        <th style="width: 80px;">Minuti</th>
                        <th style="width: 100%;">Servizi</th>
                        <th style="width: 100px;">Azioni</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                        
                            foreach ($time_slots as $slot) :
                    ?>
                        <tr>
                            <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->day_of_week); ?></td>
                            <td><?php echo esc_html($slot->start_time); ?></td>
                            <td><?php echo esc_html($slot->end_time); ?></td>
                            <td><?php echo esc_html($slot->max_bookings); ?></td>
                            <td><?php echo esc_html($slot->max_slots); ?></td>
                            <td><?php echo esc_html($slot->minutes_slots); ?></td>
                            <td>
                                <?php
                                    if ($slot->services === null || $slot->services === 'null' || empty($slot->services)) {
                                        echo 'Nessun servizio impostato';
                                    } else {
                                        $services = json_decode($slot->services);
                                        $servizi = implode(", ", $services);
                                        $services = array_map(function($service) {
                                            $service = str_replace('_', ' ', $service);
                                            return ucwords($service);
                                        }, $services);
                                        $servizi = implode(", ", $services);
                                        echo esc_html($servizi);
                                    }

                                ?>
                            </td>
                            <td>
                                <a href="<?php echo RINNOVOBOOKINGSTAGING ?>/wp-admin/admin.php?page=<?php echo RINNOVOBOOKINGPREFIX ?>fasceorarie&tipo=modifica&id=<?php echo $slot->id ?>" >
                                    <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 ?>fasceorarie&tipo=cancella&id=<?php echo $slot->id ?>" onclick="return confirm('Sei sicuro di voler eliminare:\n <?php echo strtoupper($slot->day_of_week);?> ?' );">
                                    <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>
        </div>
    </div>
</div>