# Esempi di utilizzo della funzione entourance_get_paginated_items()

Questo documento mostra diversi esempi di come utilizzare la funzione `entourance_get_paginated_items()` per ottenere dati dall'API Entourance.

La funzione può essere utilizzata:
- Nel tuo tema WordPress
- In altri plugin
- In template personalizzati
- Nel file `functions.php` del tema

> **NOTA:** Copia gli esempi che ti servono nel tuo codice.

---

## Esempio 1: Ottenere le prime 20 experience di tipo 'tour'

```php
function get_tours() {
    $result = entourance_get_paginated_items( array(
        'type'            => 'experience',
        'experience_type' => 'event',
        'items_per_page'  => 20,
        'page'            => 1,
    ) );
    
    // Verifica se ci sono errori
    if ( is_wp_error( $result ) ) {
        echo 'Errore: ' . esc_html( $result->get_error_message() );
        return;
    }
    
    // Verifica se la chiamata è andata a buon fine
    if ( ! $result['success'] ) {
        echo 'La chiamata API non è riuscita';
        return;
    }
    
    // Mostra i risultati
    echo '<h2>Tour disponibili (' . esc_html( $result['pagination']['returned_items'] ) . ' risultati)</h2>';
    echo '<ul>';
    foreach ( $result['data'] as $tour ) {
        echo '<li>';
        echo '<strong>' . esc_html( $tour->title ?? $tour->name ?? 'Senza titolo' ) . '</strong><br>';
        if ( isset( $tour->description ) ) {
            echo '<p>' . esc_html( wp_trim_words( $tour->description, 20 ) ) . '</p>';
        }
        if ( isset( $tour->category ) ) {
            echo '<em>Categoria: ' . esc_html( $tour->category ) . '</em>';
        }
        echo '</li>';
    }
    echo '</ul>';
    
    // Mostra info paginazione
    echo '<p>Pagina ' . esc_html( $result['pagination']['current_page'] ) . ' - ';
    echo 'Elementi per pagina: ' . esc_html( $result['pagination']['items_per_page'] );
    if ( $result['pagination']['has_more'] ) {
        echo ' - <strong>Ci sono altre pagine disponibili</strong>';
    }
    echo '</p>';
}
```

---

## Esempio 2: Ottenere eventi futuri da oggi

```php
function get_future_events() {
    // Data di oggi in formato ISO 8601
    $today = gmdate( 'Y-m-d\T00:00:00\Z' );
    
    $result = entourance_get_paginated_items( array(
        'type'            => 'event',
        'date_start'      => $today,
        'items_per_page'  => 15,
        'page'            => 1,
        'order_field'     => 'title',
        'order_direction' => 'asc',
    ) );
    
    if ( is_wp_error( $result ) ) {
        echo 'Errore: ' . esc_html( $result->get_error_message() );
        return;
    }
    
    echo '<h2>Eventi futuri</h2>';
    if ( empty( $result['data'] ) ) {
        echo '<p>Nessun evento trovato</p>';
        return;
    }
    
    foreach ( $result['data'] as $event ) {
        echo '<div class="event-card">';
        echo '<h3>' . esc_html( $event->title ?? $event->name ?? 'Evento' ) . '</h3>';
        
        // Mostra la data se disponibile
        if ( isset( $event->start_date ) ) {
            $date = new DateTime( $event->start_date );
            echo '<p><strong>Data:</strong> ' . esc_html( $date->format( 'd/m/Y H:i' ) ) . '</p>';
        }
        
        // Mostra la città se disponibile
        if ( isset( $event->city ) ) {
            echo '<p><strong>Città:</strong> ' . esc_html( $event->city ) . '</p>';
        }
        
        echo '</div>';
    }
}
```

---

## Esempio 3: Ottenere eventi in un intervallo di date specifico

```php
function get_events_in_range() {
    $result = entourance_get_paginated_items( array(
        'type'           => 'event',
        'date_start'     => '2024-01-01T00:00:00Z',
        'date_end'       => '2024-03-31T23:59:59Z',
        'city'           => 'Milano',
        'items_per_page' => 25,
        'page'           => 1,
    ) );
    
    if ( is_wp_error( $result ) ) {
        return array();
    }
    
    return $result['data'];
}
```

---

## Esempio 4: Implementare una paginazione completa

```php
function paginated_experiences() {
    // Ottieni il numero di pagina dall'URL (es: ?paged=2)
    $current_page = isset( $_GET['paged'] ) ? max( 1, intval( $_GET['paged'] ) ) : 1;
    
    $result = entourance_get_paginated_items( array(
        'type'            => 'experience',
        'items_per_page'  => 12,
        'page'            => $current_page,
        'order_field'     => 'title',
        'order_direction' => 'asc',
    ) );
    
    if ( is_wp_error( $result ) || ! $result['success'] ) {
        echo '<p>Errore nel caricamento delle experience</p>';
        return;
    }
    
    // Mostra i risultati
    echo '<div class="experiences-grid">';
    foreach ( $result['data'] as $experience ) {
        echo '<div class="experience-item">';
        echo '<h3>' . esc_html( $experience->title ?? $experience->name ?? 'Experience' ) . '</h3>';
        // ... altro contenuto ...
        echo '</div>';
    }
    echo '</div>';
    
    // Mostra la paginazione
    echo '<div class="pagination">';
    if ( $current_page > 1 ) {
        echo '<a href="?paged=' . ( $current_page - 1 ) . '">&laquo; Precedente</a> ';
    }
    echo 'Pagina ' . esc_html( $current_page );
    if ( $result['pagination']['has_more'] ) {
        echo ' <a href="?paged=' . ( $current_page + 1 ) . '">Successiva &raquo;</a>';
    }
    echo '</div>';
}
```

---

## Esempio 5: Filtrare per categoria e sottocategoria

```php
function filter_by_category() {
    $result = entourance_get_paginated_items( array(
        'type'           => 'experience',
        'category'       => 'tour',
        'subcategory'    => 'cultural',
        'items_per_page' => 20,
    ) );
    
    if ( is_wp_error( $result ) || ! $result['success'] ) {
        return array();
    }
    
    return $result['data'];
}
```

---

## Esempio 6: Utilizzare in un template WordPress

```php
function template_usage() {
    ?>
    <div class="entourance-events-section">
        <h2>Prossimi Eventi</h2>
        
        <?php
        $events_result = entourance_get_paginated_items( array(
            'type'            => 'event',
            'date_start'      => gmdate( 'Y-m-d\T00:00:00\Z' ),
            'items_per_page'  => 6,
            'order_field'     => 'title',
            'order_direction' => 'asc',
        ) );
        
        if ( ! is_wp_error( $events_result ) && $events_result['success'] && ! empty( $events_result['data'] ) ) :
        ?>
            <div class="events-list">
                <?php foreach ( $events_result['data'] as $event ) : ?>
                    <article class="event-item">
                        <h3><?php echo esc_html( $event->title ?? $event->name ?? 'Evento' ); ?></h3>
                        
                        <?php if ( isset( $event->start_date ) ) : ?>
                            <time datetime="<?php echo esc_attr( $event->start_date ); ?>">
                                <?php 
                                $date = new DateTime( $event->start_date );
                                echo esc_html( $date->format( 'd F Y' ) );
                                ?>
                            </time>
                        <?php endif; ?>
                        
                        <?php if ( isset( $event->description ) ) : ?>
                            <p><?php echo esc_html( wp_trim_words( $event->description, 30 ) ); ?></p>
                        <?php endif; ?>
                        
                        <a href="<?php echo esc_url( $event->url ?? '#' ); ?>" class="btn">
                            Scopri di più
                        </a>
                    </article>
                <?php endforeach; ?>
            </div>
        <?php else : ?>
            <p>Nessun evento disponibile al momento.</p>
        <?php endif; ?>
    </div>
    <?php
}
```

---

## Esempio 7: Creare un widget con eventi futuri

```php
function widget_future_events() {
    // Ottieni i prossimi 5 eventi
    $result = entourance_get_paginated_items( array(
        'type'            => 'event',
        'date_start'      => gmdate( 'Y-m-d\T00:00:00\Z' ),
        'items_per_page'  => 5,
        'order_field'     => 'title',
        'order_direction' => 'asc',
    ) );
    
    if ( is_wp_error( $result ) || ! $result['success'] || empty( $result['data'] ) ) {
        return;
    }
    
    echo '<aside class="widget events-widget">';
    echo '<h3 class="widget-title">Prossimi Eventi</h3>';
    echo '<ul class="events-list">';
    
    foreach ( $result['data'] as $event ) {
        echo '<li>';
        echo '<a href="' . esc_url( $event->url ?? '#' ) . '">';
        echo esc_html( $event->title ?? $event->name ?? 'Evento' );
        echo '</a>';
        
        if ( isset( $event->start_date ) ) {
            $date = new DateTime( $event->start_date );
            echo '<small>' . esc_html( $date->format( 'd/m/Y' ) ) . '</small>';
        }
        echo '</li>';
    }
    
    echo '</ul>';
    echo '</aside>';
}
```

---

## Esempio 8: API REST personalizzata che utilizza la funzione

```php
/**
 * Registra un endpoint REST API personalizzato.
 */
function register_custom_api() {
    register_rest_route(
        'mio-tema/v1',
        '/events',
        array(
            'methods'             => 'GET',
            'callback'            => 'custom_api_callback',
            'permission_callback' => '__return_true',
        )
    );
}
add_action( 'rest_api_init', 'register_custom_api' );

/**
 * Callback per l'endpoint REST API.
 *
 * @param WP_REST_Request $request La richiesta REST.
 * @return WP_REST_Response|WP_Error La risposta.
 */
function custom_api_callback( $request ) {
    $params = $request->get_params();
    
    $args = array(
        'type'           => isset( $params['type'] ) ? $params['type'] : 'event',
        'page'           => isset( $params['page'] ) ? intval( $params['page'] ) : 1,
        'items_per_page' => isset( $params['per_page'] ) ? intval( $params['per_page'] ) : 10,
    );
    
    // Aggiungi filtro per data se specificato.
    if ( isset( $params['date_start'] ) ) {
        $args['date_start'] = $params['date_start'];
    }
    
    if ( isset( $params['date_end'] ) ) {
        $args['date_end'] = $params['date_end'];
    }
    
    $result = entourance_get_paginated_items( $args );
    
    if ( is_wp_error( $result ) ) {
        return new WP_Error( 'api_error', $result->get_error_message(), array( 'status' => 500 ) );
    }
    
    return rest_ensure_response( $result );
}
```

---

## Esempio 9: Shortcode personalizzato

```php
/**
 * Shortcode per mostrare elementi Entourance.
 *
 * @param array $atts Attributi dello shortcode.
 * @return string HTML output.
 */
function custom_shortcode( $atts ) {
    $atts = shortcode_atts(
        array(
            'type'     => 'experience',
            'limit'    => 10,
            'category' => '',
        ),
        $atts
    );
    
    $args = array(
        'type'           => $atts['type'],
        'items_per_page' => intval( $atts['limit'] ),
    );
    
    if ( ! empty( $atts['category'] ) ) {
        $args['category'] = $atts['category'];
    }
    
    $result = entourance_get_paginated_items( $args );
    
    if ( is_wp_error( $result ) || ! $result['success'] ) {
        return '<p>Nessun elemento trovato</p>';
    }
    
    ob_start();
    ?>
    <div class="entourance-items">
        <?php foreach ( $result['data'] as $item ) : ?>
            <div class="item">
                <h4><?php echo esc_html( $item->title ?? $item->name ?? 'Item' ); ?></h4>
            </div>
        <?php endforeach; ?>
    </div>
    <?php
    return ob_get_clean();
}
add_shortcode( 'entourance_items', 'custom_shortcode' );
```

**Utilizzo:**

```
[entourance_items type="event" limit="5" category="tour"]
```

---

## Esempio 10: Debugging - Vedere tutti i filtri applicati

```php
function debug_filters() {
    $result = entourance_get_paginated_items( array(
        'type'           => 'event',
        'date_start'     => '2024-01-01T00:00:00Z',
        'date_end'       => '2024-12-31T23:59:59Z',
        'city'           => 'Milano',
        'items_per_page' => 10,
    ) );
    
    if ( is_wp_error( $result ) ) {
        echo 'Errore: ' . esc_html( $result->get_error_message() );
        return;
    }
    
    // Mostra informazioni di debug
    echo '<h3>Debug Info</h3>';
    echo '<pre>';
    echo 'Filtri applicati: ' . "\n";
    // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r
    print_r( $result['filters_applied'] );
    echo "\n\nURL API chiamato: " . "\n";
    echo esc_html( $result['api_url'] );
    echo "\n\nNumero risultati: " . esc_html( $result['pagination']['returned_items'] );
    echo '</pre>';
}
```

---

## Parametri disponibili per entourance_get_paginated_items()

| Parametro | Tipo | Default | Descrizione |
|-----------|------|---------|-------------|
| `type` | string | `'experience'` | Tipo di contenuto: `experience`, `event`, `eatery`, `host`, `poi`, `itinerary`, `article` |
| `experience_type` | string | `null` | Tipo specifico di experience (es: `tour`, `activity`) |
| `date_start` | string | `null` | Data inizio filtro in formato ISO 8601 (es: `2024-01-01T00:00:00Z`) |
| `date_end` | string | `null` | Data fine filtro in formato ISO 8601 |
| `category` | string | `null` | Filtra per categoria |
| `subcategory` | string | `null` | Filtra per sottocategoria |
| `city` | string | `null` | Filtra per città |
| `tag` | string | `null` | Filtra per tag |
| `page` | int | `1` | Numero di pagina (partendo da 1) |
| `items_per_page` | int | `10` | Numero di elementi per pagina (max 100) |
| `order_field` | string | `null` | Campo per ordinamento (es: `title`, `name`, `price`) |
| `order_direction` | string | `null` | Direzione ordinamento: `asc` o `desc` |
| `by_organization` | bool | `false` | Filtra per organizzazione corrente |

---

## Struttura della risposta

```php
array(
    'success' => true,                    // bool: se la chiamata è riuscita
    'data' => array(...),                 // array: elementi restituiti
    'pagination' => array(
        'current_page'    => 1,           // int: pagina corrente
        'items_per_page'  => 10,          // int: elementi per pagina
        'returned_items'  => 10,          // int: elementi restituiti
        'has_more'        => true,        // bool: se ci sono altre pagine
    ),
    'filters_applied' => array(...),      // array: filtri applicati
    'api_url' => 'https://...',           // string: URL API (utile per debug)
);
```
