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

    <!-- intestazione -->
    <?php include 'intestazione.php';?>

    <!-- Card di conteggio -->
    <div class="postbox tools" style="margin-bottom: 20px;">
        <div class="inside">
            <h3>Statistiche Operazioni iPatente</h3>
            <div class="stats-cards" style="display: flex; gap: 20px; flex-wrap: wrap;">
                <?php
                global $wpdb;
                $table_name = $wpdb->prefix.RINNOVOBOOKINGPREFIX.'_iPatente_Api';
                
                // Gestione filtri - definita all'inizio per essere disponibile ovunque
                $filtro_tipo = isset($_GET['filtro']) ? sanitize_text_field($_GET['filtro']) : '';
                
                // Conteggio totale operazioni
                $totale_operazioni = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
                $ultimo_totale = $wpdb->get_row("SELECT * FROM $table_name ORDER BY created_at DESC LIMIT 1");
                
                // Conteggio errori di autenticazione
                $errori_autenticazione = $wpdb->get_var(
                    $wpdb->prepare(
                        "SELECT COUNT(*) FROM $table_name WHERE risultato LIKE %s",
                        '%Autenticazione fallita%'
                    )
                );
                $ultimo_autenticazione = $wpdb->get_row($wpdb->prepare(
                    "SELECT * FROM $table_name WHERE risultato LIKE %s ORDER BY created_at DESC LIMIT 1",
                    '%Autenticazione fallita%'
                ));
                
                // Conteggio errori Too many requests
                $errori_too_many_requests = $wpdb->get_var($wpdb->prepare(
                    "SELECT COUNT(*) FROM $table_name WHERE risultato LIKE %s",
                    '%Too many requests%'
                ));
                $ultimo_too_many = $wpdb->get_row($wpdb->prepare(
                    "SELECT * FROM $table_name WHERE risultato LIKE %s ORDER BY created_at DESC LIMIT 1",
                    '%Too many requests%'
                ));
                ?>
                
                <!-- Card Totale -->
                <div class="stat-card" style="background: #f0f8ff; border: 1px solid #0073aa; border-radius: 8px; padding: 20px; min-width: 200px; text-align: center;">
                    <div class="stat-label" style="color: #666; font-size: 14px; margin-bottom: 10px;">
                        Totale Operazioni
                    </div>
                    <div class="stat-number" style="font-size: 32px; font-weight: bold; color: #0073aa; margin-bottom: 10px;">
                        <?php echo $totale_operazioni; ?>
                    </div>
                    <?php if ($ultimo_totale) : ?>
                        <div class="stat-last" style="font-size: 12px; color: #888; border-top: 1px solid #ddd; padding-top: 8px; margin-bottom: 10px;">
                            <div><strong>Ultimo:</strong> <?php echo date_format(date_create($ultimo_totale->created_at), 'd-m-Y H:i:s'); ?></div>
                        </div>
                    <?php endif; ?>
                    <button onclick="resetFiltri()" class="button button-secondary" style="font-size: 12px; padding: 5px 10px;">
                        Visualizza
                    </button>
                </div>
                
                <!-- Card Errori Autenticazione -->
                <div class="stat-card" style="background: #fff5f5; border: 1px solid #dc3232; border-radius: 8px; padding: 20px; min-width: 200px; text-align: center;">
                    <div class="stat-label" style="color: #666; font-size: 14px; margin-bottom: 10px;">
                        Errori Autenticazione
                    </div>
                    <div class="stat-number" style="font-size: 32px; font-weight: bold; color: #dc3232; margin-bottom: 10px;">
                        <?php echo $errori_autenticazione; ?>
                    </div>
                    <?php if ($ultimo_autenticazione) : ?>
                        <div class="stat-last" style="font-size: 12px; color: #888; border-top: 1px solid #ddd; padding-top: 8px; margin-bottom: 10px;">
                            <div><strong>Ultimo:</strong> <?php echo date_format(date_create($ultimo_autenticazione->created_at), 'd-m-Y H:i:s'); ?></div>
                        </div>
                    <?php endif; ?>
                    <button onclick="filtraPerTipo('autenticazione')" class="button button-secondary" style="font-size: 12px; padding: 5px 10px;">
                        Visualizza
                    </button>
                </div>
                
                <!-- Card Errori Too Many Requests -->
                <div class="stat-card" style="background: #fff8e1; border: 1px solid #f56e28; border-radius: 8px; padding: 20px; min-width: 200px; text-align: center;">
                    <div class="stat-label" style="color: #666; font-size: 14px; margin-bottom: 10px;">
                        Too Many Requests
                    </div>
                    <div class="stat-number" style="font-size: 32px; font-weight: bold; color: #f56e28; margin-bottom: 10px;">
                        <?php echo $errori_too_many_requests; ?>
                    </div>
                    <?php if ($ultimo_too_many) : ?>
                        <div class="stat-last" style="font-size: 12px; color: #888; border-top: 1px solid #ddd; padding-top: 8px; margin-bottom: 10px;">
                            <div><strong>Ultimo:</strong> <?php echo date_format(date_create($ultimo_too_many->created_at), 'd-m-Y H:i:s'); ?></div>
                        </div>
                    <?php endif; ?>
                    <button onclick="filtraPerTipo('too_many')" class="button button-secondary" style="font-size: 12px; padding: 5px 10px;">
                        Visualizza
                    </button>
                </div>
            </div>
        </div>
    </div>

    <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">
                        <h3>Elenco iPatente Api</h3>
                        Elenco delle operazioni registrate da iPatente.
                        
                        <?php if ($filtro_tipo) : ?>
                            <div style="background: #e7f3ff; border: 1px solid #0073aa; border-radius: 4px; padding: 10px; margin: 10px 0;">
                                <strong>Filtro attivo:</strong> 
                                <?php 
                                if ($filtro_tipo === 'autenticazione') {
                                    echo 'Errori di Autenticazione';
                                } elseif ($filtro_tipo === 'too_many') {
                                    echo 'Errori Too Many Requests';
                                }
                                ?>
                                <button onclick="resetFiltri()" class="button button-small" style="margin-left: 10px; font-size: 11px; padding: 2px 8px;">
                                    Rimuovi Filtro
                                </button>
                            </div>
                        <?php endif; ?>

                        <table class="wp-list-table widefat fixed striped table-view-list">                 
                        <thead>
                        <tr>
                            <th scope="col" class="manage-column column-name" width="50"><strong>ID</strong></th>
                        	<th scope="col" class="manage-column column-name" width="150"><strong>DATA ORA</strong></th>
                        	<th scope="col" class="manage-column column-name" width="200"><strong>SEDE</strong></th>
                        	<th scope="col" class="manage-column column-name" width="200"><strong>IP ORIGINE</strong></th>
                        	<th scope="col" class="manage-column column-name" width="200"><strong>FUNZIONE</strong></th>	
                        	<th scope="col" class="manage-column column-name" ><strong>RISULTATO</strong></th>
                        </tr>
                        </thead>
                        
                        <tbody id="the-list" >
    						<tr>
    							<td colspan="6" style="padding-left:0px; padding-right:0px;">
    								<div style="overflow-y:scroll;">
    									<table class="wp-list-table widefat fixed striped table-view-list" style="border:0px;">      											
                                        	<?php    
                                                // elenco delle operazioni log
                                                global $wpdb;

                                                $table_name = $wpdb->prefix.RINNOVOBOOKINGPREFIX.'_iPatente_Api';
                                                
                                                // Gestione filtri
                                                $where_conditions = "WHERE 1";
                                                $query_params = array();
                                                
                                                if ($filtro_tipo === 'autenticazione') {
                                                    $where_conditions .= " AND risultato LIKE %s";
                                                    $query_params[] = '%Autenticazione fallita%';
                                                } elseif ($filtro_tipo === 'too_many') {
                                                    $where_conditions .= " AND risultato LIKE %s";
                                                    $query_params[] = '%Too many requests%';
                                                }
                                                
                                                $ricercaQuery = "SELECT * FROM $table_name $where_conditions ORDER BY `created_at` DESC LIMIT %d OFFSET %d";

                                                // paginazione
                                                $pagina_corrente = isset($_GET['pagina']) ? max(1, intval($_GET['pagina'])) : 1;
                                                $record_per_pagina = 20;
                                                $offset = ($pagina_corrente - 1) * $record_per_pagina;
                                            
                                                // Aggiungi i parametri del filtro e della paginazione
                                                $all_params = array_merge($query_params, array($record_per_pagina, $offset));
                                                $results = $wpdb->get_results($wpdb->prepare(
                                                    $ricercaQuery,
                                                    $all_params
                                                ));
                                            
                                                // paginazione - conta i record filtrati
                                                $count_query = "SELECT COUNT(*) FROM $table_name $where_conditions";
                                                if (!empty($query_params)) {
                                                    $totale_record = $wpdb->get_var($wpdb->prepare($count_query, $query_params));
                                                } else {
                                                    $totale_record = $wpdb->get_var($count_query);
                                                }
                                                $totale_pagine = ceil($totale_record / $record_per_pagina);
                                                
                                                if ($results == null) { 
                                            ?>       
                                                <tr> 
                                                    <td class="column-primary"  colspan="4">
                                                    Nessuna operazione registrata.
                                                    </td>                                                   
                                                </tr>
                                      		<?php 
                                                } else {     
                                                    foreach ($results as $result) {
                                            ?>
                                        		<tr>
                                                    <td class="column-primary" width="50"><?php echo $result->id;?></td>
                                                    <td class="column-primary" width="150"><?php echo date_format(date_create($result->created_at),'d-m-Y H:i:s');?></td>
                                                    <td class="column-primary" width="200"><?php echo $result->sede;?></td>
                                                    <td class="column-primary" width="200"><?php echo $result->ip_origine;?></td>
                                                    <td class="column-primary" width="200"><?php echo $result->funzione;?></td>
                                                    <td class="column-primary" 
                                                        onclick="openRisultatoModal(this)"
                                                        data-risultato="<?php echo esc_attr($result->risultato); ?>">
                                                        <?php echo mb_strimwidth($result->risultato, 0, 100, '...'); ?>
                                                    </td>
                                                </tr>
                                            <?php          
                                                    }//foreach ($results as $result)
                                                }//if (mysqli_num_rows($results) != 0)
                                            ?>                                            
        								</table>
    								</div>
    							</td>
							</tr>
                        </tbody>
                        </table>

                        <!-- 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">
                                        <?php if ($pagina_corrente > 1) : ?>
                                            <a href="<?php echo RINNOVOBOOKINGSTAGING ?>/wp-admin/admin.php?page=<?php echo RINNOVOBOOKINGPREFIX ?>ipatenteapi&pagina=<?php echo $pagina_corrente - 1; ?><?php echo $filtro_tipo ? '&filtro=' . $filtro_tipo : ''; ?>" class="prev-page button">Precedente</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 ?>ipatenteapi&pagina=<?php echo $i; ?><?php echo $filtro_tipo ? '&filtro=' . $filtro_tipo : ''; ?>" class="<?php echo $class; ?>"><?php echo $i; ?></a>
                                        <?php } ?>
                                        
                                        <?php if ($pagina_corrente < $totale_pagine) { ?>
                                            <a href="<?php echo RINNOVOBOOKINGSTAGING ?>/wp-admin/admin.php?page=<?php echo RINNOVOBOOKINGPREFIX ?>ipatenteapi&pagina=<?php echo $pagina_corrente + 1; ?><?php echo $filtro_tipo ? '&filtro=' . $filtro_tipo : ''; ?>" class="next-page button">Successiva</a>
                                        <?php } ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- Paginazione -->
                            
                    </div>
                </div>
            </div>
        </div>  
    </div>
</div>

<!-- Modal per visualizzare il risultato -->
<div id="risultato-modal" class="risultato-modal">
    <div class="risultato-modal-content">
        <span class="risultato-modal-close" onclick="closeRisultatoModal()">&times;</span>
        <pre id="risultato-modal-text" style="white-space:pre-wrap;"></pre>
    </div>
</div>
<style>
.risultato-modal {
  display: none; 
  position: fixed; 
  z-index: 9999; 
  left: 0; top: 0;
  width: 100%; height: 100%; 
  background-color: rgba(0,0,0,0.6);
}

.risultato-modal-content {
  background: #fff;
  margin: 10% auto;
  padding: 20px;
  border-radius: 6px;
  width: 80%;
  max-width: 700px;
  max-height: 70vh;
  overflow-y: auto;
  box-shadow: 0 4px 10px rgba(0,0,0,0.3);
}

.risultato-modal-close {
  float: right;
  font-size: 24px;
  font-weight: bold;
  cursor: pointer;
}
</style>

<script>
function openRisultatoModal(el) {
    const text = el.getAttribute("data-risultato");
    document.getElementById("risultato-modal-text").textContent = text;
    document.getElementById("risultato-modal").style.display = "block";
}

function closeRisultatoModal() {
    document.getElementById("risultato-modal").style.display = "none";
}

// Chiudi cliccando fuori dalla finestra
window.onclick = function(event) {
    const modal = document.getElementById("risultato-modal");
    if (event.target === modal) {
        modal.style.display = "none";
    }
}

// Funzioni per i filtri
function filtraPerTipo(tipo) {
    const url = new URL(window.location);
    url.searchParams.set('filtro', tipo);
    url.searchParams.delete('pagina'); // Reset alla prima pagina
    window.location.href = url.toString();
}

function resetFiltri() {
    const url = new URL(window.location);
    url.searchParams.delete('filtro');
    url.searchParams.delete('pagina'); // Reset alla prima pagina
    window.location.href = url.toString();
}
</script>
