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

.badge-denied {
    color: red;
    background-color: lightcoral;
    border: 1px solid red;
    border-radius: 5px;
    padding: 5px;
}

.badge-default {
    color: blue;
    background-color: lightblue;
    border: 1px solid blue;
    border-radius: 5px;
    padding: 5px;
}

</style>

<div class="wrap menu-settings tools">
<hr class="wp-header-end" />

    <!-- intestazione -->
    <?php 
        include 'intestazione.php';
        require_once dirname(plugin_dir_path(__FILE__)) . '/core/RinnovoBookingService.php';
        use RinnovoBooking\Core\RinnovoBookingService;
    ?>

    <div class="postbox tools">
        <div class="inside">
            <div>
                <div class="upload-form" data-file-size="3145728" data-file-type="settings" class="wrap">
                    <div class="iupload-form" data-file-size="3145728" data-file-type="settings" class="wrap"></div>
                        
                        <?php 
                            global $wpdb;
                            $table_name = $wpdb->prefix.RINNOVOBOOKINGPREFIX.'_utenti';
                            $table_name2 = $wpdb->prefix.RINNOVOBOOKINGPREFIX.'_sedi';
                            $cosa = '';

                            if(isset($_GET['tipo'])) {
                                $cosa = $_GET['tipo'];
                                switch ($cosa) {
                                    // aggiunge nuovo utente
                                    case "addDBase" :
                                        $results = $wpdb->get_results(
                                            "SELECT `email` FROM $table_name WHERE `email` = '".$_POST['email']."'"
                                        );

                                        if (count($results) > 0) {
                                            echo '<script>alert("Email esistente");</script>';
                                        } else {
                                            try {
                                                $cognome = $_POST['cognome'];
                                                $nome = $_POST['nome'];
                                                $email = $_POST['email'];
                                                $ruolo = $_POST['ruolo'];   
                                                $idsede = $_POST['idsede'];
                                                $password = sanitize_text_field($_POST['password']);
                                                $hashed_password = wp_hash_password($password);
                                                
                                                $results = $wpdb->insert(
                                                    $table_name,
                                                    array(
                                                        'cognome' => $cognome,
                                                        'nome' => $nome,
                                                        'email' => $email,
                                                        'password' => $hashed_password,
                                                        'ruolo' => $ruolo,
                                                        'idsede' => $idsede
                                                    ),
                                                    array('%s', '%s', '%s', '%s', '%s', '%s')
                                                );
                                                    
                                                if ($results) {
                                                    $RinnovoBookingService = new RinnovoBookingService();
                                                    $RinnovoBookingService->scriviLog('sistema', 'Aggiunto utente: '.$email);
                                                } else {
                                                    $RinnovoBookingService = new RinnovoBookingService();
                                                    $RinnovoBookingService->scriviLog('sistema', 'Errore inserimento utente: '.$email);
                                                }
                                            } catch (Exception $e) {
                                                $RinnovoBookingService = new RinnovoBookingService();
                                                $RinnovoBookingService->scriviLog('sistema', 'Aggiunto utente '.$e->getMessage()); 
                                            }
                                        }
                                        break;

                                // cancella sede
                                    case "cancella" :
                                        $results = $wpdb->delete(
                                            $table_name,
                                            array('id' => intval($_GET['id'])),
                                            array('%d')
                                        );
                                        $RinnovoBookingService = new RinnovoBookingService();
                                        $RinnovoBookingService->scriviLog('sistema', 'Cancellato utente con ID: ' . intval($_GET['id']));
                                        break;

                                // modifica sede
                                    case "modifica" :
                                        $modifica = $wpdb->get_results(
                                            "SELECT * FROM $table_name WHERE `id` = '".$_GET['id']."'");
                                        break;

                                    case "updDBase" :
                                        $cognome = $_POST['cognome'];
                                        $nome = $_POST['nome'];
                                        $email = $_POST['email'];
                                        $ruolo = $_POST['ruolo'];
                                        $idsede = $_POST['idsede'];
                                        $password = sanitize_text_field($_POST['password']);
                                        
                                        $update_data = array(
                                            'cognome' => $cognome,
                                            'nome' => $nome,
                                            'email' => $email,
                                            'ruolo' => $ruolo,
                                            'idsede' => $idsede
                                        );
                                        
                                        if (!empty($password)) {
                                            $hashed_password = wp_hash_password($password);
                                            $update_data['password'] = $hashed_password;

                                            $results = $wpdb->update(
                                                $table_name,
                                                array(
                                                    'cognome' => $cognome,
                                                    'nome' => $nome,
                                                    'email' => $email,
                                                    'password' => $hashed_password,
                                                    'ruolo' => $ruolo,
                                                    'idsede' => $idsede
                                                ),
                                                array('id' => $_POST['id']),
                                                array(
                                                    '%s', '%s', '%s', '%s', '%s', '%s'
                                                ),
                                                array('%d')
                                            );
                                        } else {
                                            $results = $wpdb->update(
                                                $table_name,
                                                array(
                                                    'cognome' => $cognome,
                                                    'nome' => $nome,
                                                    'email' => $email,
                                                    'ruolo' => $ruolo,
                                                    'idsede' => $idsede
                                                ),
                                                array('id' => $_POST['id']),
                                                array(
                                                    '%s', '%s', '%s', '%s', '%s'
                                                ),
                                                array('%d')
                                            );
                                        }

                                        if ($results !== false) {
                                            $RinnovoBookingService = new RinnovoBookingService();
                                            $RinnovoBookingService->scriviLog('sistema', 'Aggiornato utente: ' . $email);
                                        } else {
                                            $RinnovoBookingService = new RinnovoBookingService();
                                            $RinnovoBookingService->scriviLog('sistema', 'Errore nell\'aggiornamento dell\'utente: ' . $email);
                                        }
                                        break;
                                }//switch ($cosa)
                            }

                            $results = $wpdb->get_results("SELECT * FROM $table_name");
                            $sedi = $wpdb->get_results("SELECT * FROM $table_name2");
                        ?>       
                        
                        <!-- aggiungi utente -->
                        <div class="postbox tools">
                            <div class="inside">
                                <h3><span class="vendor">Aggiungi nuovo utente</span></h3>
                                <form method="post" action="<?php echo RINNOVOBOOKINGSTAGING ?>/wp-admin/admin.php?page=<?php echo RINNOVOBOOKINGPREFIX ?>utenti&tipo=addDBase">
                                    <table cellspacing="10">
                                        <tr>
                                            <td width="20%">
                                                <p><strong>Cognome</strong> </p>
                                                <input type="text" name="cognome" id="cognome" value="" placeholder="inserire cognome utente" required>
                                            </td>
                                            <td width="20%">
                                                <p><strong>Nome</strong></p>
                                                <input type="text" name="nome" id="nome" value="" placeholder="inserire nome utente" required>
                                            </td>
                                            <td width="20%">
                                                <p><strong>Email</strong></p>
                                                <input type="email" name="email" id="email" value="" placeholder="inserire email utente" required>
                                            </td>
                                            <td width="20%">
                                                <p><strong>Password</strong></p>
                                                <input type="password" name="password" id="password" value="" placeholder="inserire password utente" required>
                                            </td>
                                            <td width="20%">
                                                <p><strong></strong>Ruolo</strong></p>
                                                <select name="ruolo" id="ruolo" required>
                                                    <option value="">Seleziona un ruolo</option>
                                                    <option value="admin">Amministratore</option>
                                                    <option value="operatore">Operatore</option>
                                                </select>
                                            </td>
                                            <td width="20%">
                                                <p><strong>Sede</strong></p>
                                                <select name="idsede" id="idsede" required>
                                                    <option value="">Seleziona una sede</option>
                                                    <option value="0">Tutte le sedi</option>
                                                    <?php
                                                        foreach ($sedi as $sediArray) {
                                                    ?>
                                                            <option value="<?php echo $sediArray->idsede; ?>"><?php echo $sediArray->nome; ?></option>
                                                    <?php
                                                        }
                                                    ?>
                                                </select>
                                            </td>
                                            <td colspan="4"><p><strong>&nbsp;</strong></p><input type="submit" name="aggiungiSede" id="aggiungiSede" class="button button-primary" value="Inserisci"></td>
                                        </tr>
                                    </table>
                                </form>
                            </div>  
                        </div>	

                        <!-- modifica utente -->
                        <?php 
                            if ($cosa == 'modifica') {
                        ?>
                            <div class="postbox inside" style="background-color: lightblue;">
                                <h3>Modifica</h3>
                                <form method="post" action="<?php echo RINNOVOBOOKINGSTAGING ?>/wp-admin/admin.php?page=<?php echo RINNOVOBOOKINGPREFIX ?>utenti&tipo=updDBase">
                                    <table cellspacing="10">
                                        <tr>
                                            <td width="20%">
                                                <p><strong>Cognome</strong></p>
                                                <input type="text" name="cognome" id="cognome" value="<?php echo $modifica[0]->cognome; ?>" required>
                                            </td>
                                            <td width="20%">
                                                <p><strong>Nome</strong></p>
                                                <input type="text" name="nome" id="nome" value="<?php echo $modifica[0]->nome; ?> " required>
                                            </td>                                            
                                            <td width="20%">
                                                <p><strong>Email</strong></p>
                                                <input type="email" name="email" id="email" value="<?php echo $modifica[0]->email; ?> " required>
                                            </td>
                                            <td width="20%">
                                                <p><strong>Password</strong></p>
                                                <input type="password" name="password" id="password" value="" placeholder="inserire password utente">
                                            </td>
                                            <td width="20%">
                                                <p><strong>Ruolo</strong></p>
                                                <select name="ruolo" id="ruolo" required>
                                                    <option value="admin" <?php echo $modifica[0]->ruolo == 'admin' ? 'selected' : ''; ?>>Amministratore</option>
                                                    <option value="operatore" <?php echo $modifica[0]->ruolo == 'operatore' ? 'selected' : ''; ?>>Operatore</option>
                                                    <option value="utente" <?php echo $modifica[0]->ruolo == 'utente' ? 'selected' : ''; ?>>Utente</option>
                                                </select>
                                            </td>                   
                                            <td width="20%">
                                                <p><strong>Sede</strong></p>
                                                <select name="idsede" id="idsede" required>
                                                    <option value="0" <?php echo $modifica[0]->idsede == '0' ? 'selected' : ''; ?>>Tutte le sedi</option>
                                                    <?php
                                                        foreach ($sedi as $sediArray) {
                                                    ?>
                                                            <option value="<?php echo $sediArray->idsede; ?>" <?php echo $modifica[0]->idsede == $sediArray->idsede ? 'selected' : ''; ?>><?php echo $sediArray->nome; ?></option>
                                                    <?php
                                                        }
                                                    ?>
                                                </select>
                                            </td>
                                            <td colspan="4">
                                                <input type="hidden" name="id" value="<?php echo $_GET['id'];?>">
                                                <p><strong>&nbsp;</strong></p>
                                                <input type="submit" name="updateSede" id="updateSede" class="button button-primary" value="Aggiorna">
                                            </td>
                                        </tr>
                                    </table>
                                </form>
                            </div>
                        <?php
                            }
                        ?>

                        <div class="postbox tools">
                            <div class="inside">
                                <div>
                                    <h3><span class="vendor">Elenco utenti</span></h3>
                                    <table cellspacing="10" width="100%">
                                        <tr>
                                            <td width="10%"><strong>Cognome</strong></td>
                                            <td width="10%"><strong>Nome</strong></td>
                                            <td width="10%"><strong>Email</strong></td>
                                            <td width="10%"><strong>Ruolo</strong></td>
                                            <td width="10%"><strong>Sede</strong></td>
                                            <td width="10%"><strong>Azioni</strong></td>
                                        </tr>            
                                        <?php
                                            // Verifica se ci sono risultati
                                            if (count($results) > 0) {
                                                foreach ($results as $utentiArray) {
                                        ?>
                                                    <tr>
                                                        <td><?php echo $utentiArray->cognome; ?></td>
                                                        <td><?php echo $utentiArray->nome; ?></td>
                                                        <td><?php echo $utentiArray->email; ?></td>
                                                        <td>
                                                            <?php
                                                            switch ($utentiArray->ruolo) {
                                                                case 'admin':
                                                                    echo '<label class="badge-success">Amministratore</label>';
                                                                    break;
                                                                case 'operatore':
                                                                    echo '<label class="badge-denied">Operatore</label>';
                                                                    break;
                                                                case 'utente':
                                                                    echo '<label class="badge-default">Utente</label>';
                                                                    break;
                                                                default:
                                                                    echo $utentiArray->ruolo;
                                                            }
                                                            ?>                                                    
                                                        </td>
                                                        <td>
                                                        <?php
                                                            $trovataSede = $utentiArray->idsede == '0' 
                                                                ? 'Tutte le sedi' 
                                                                : array_filter($sedi, function ($sede) use ($utentiArray) {
                                                                    return $sede->idsede == $utentiArray->idsede;
                                                                });

                                                            echo is_array($trovataSede) && !empty($trovataSede) 
                                                                ? reset($trovataSede)->nome 
                                                                : 'Sede non trovata';
                                                        ?>

                                                        </td>
                                                        <td>
                                                            <a href="<?php echo RINNOVOBOOKINGSTAGING ?>/wp-admin/admin.php?page=<?php echo RINNOVOBOOKINGPREFIX ?>utenti&tipo=modifica&id=<?php echo $utentiArray->id ?>" class="button button-primary">Modifica</a>
                                                            <a href="<?php echo RINNOVOBOOKINGSTAGING ?>/wp-admin/admin.php?page=<?php echo RINNOVOBOOKINGPREFIX ?>utenti&tipo=cancella&id=<?php echo $utentiArray->id ?>" class="button button-primary" onclick="return confirm('Sei sicuro di voler eliminare:\n <?php echo strtoupper($utentiArray->cognome);?> ?' );">Elimina</a>
                                                        </td>
                                                    </tr> 
                                        <?php 
                                                } //foreach ($results as $result)
                                            } else {
                                                echo "<tr><td colspan='5'>Nessun risultato trovato.</td></tr>";
                                            }
                                        ?>
                                    </table>
                                </div>
                            </div>  
                        </div>	
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>