# Guida Utilizzo API Entourance

## Funzione `entourance_get_paginated_items()`

Questa funzione permette di ottenere dati paginati e filtrabili dall'API Entourance. Può essere utilizzata nel tuo tema WordPress, in altri plugin o in qualsiasi file PHP del tuo progetto.

---

## Utilizzo Base

```php
$result = entourance_get_paginated_items(array(
    'type' => 'experience',  // o 'event', 'eatery', 'host', 'poi', 'itinerary'
    'items_per_page' => 10,
    'page' => 1
));

if (!is_wp_error($result) && $result['success']) {
    foreach ($result['data'] as $item) {
        echo $item->title . '<br>';
    }
}
```

---

## Parametri Disponibili

| 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'). Solo per type='experience' |
| `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 (es: '2024-12-31T23:59:59Z') |
| `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', 'price') |
| `order_direction` | string | null | Direzione ordinamento: 'asc' o 'desc' |
| `by_organization` | bool | false | Filtra per organizzazione corrente |

---

## Struttura Risposta

```php
array(
    'success' => true,                    // bool: successo della chiamata
    'data' => array(...),                 // array: risultati
    'pagination' => array(
        'current_page' => 1,              // pagina corrente
        'items_per_page' => 10,           // elementi per pagina
        'returned_items' => 10,           // elementi restituiti
        'has_more' => true                // true se ci sono altre pagine
    ),
    'filters_applied' => array(...),      // filtri applicati
    'api_url' => 'https://...'           // URL chiamato (per debug)
)
```

---

## Esempi Pratici

### 1. Eventi Futuri (da oggi in poi)

```php
$today = date('Y-m-d\T00:00:00\Z');

$eventi = entourance_get_paginated_items(array(
    'type' => 'event',
    'date_start' => $today,
    'items_per_page' => 20,
    'order_field' => 'title',
    'order_direction' => 'asc'
));

if (!is_wp_error($eventi) && $eventi['success']) {
    foreach ($eventi['data'] as $evento) {
        echo '<h3>' . esc_html($evento->title) . '</h3>';
        if (isset($evento->start_date)) {
            $date = new DateTime($evento->start_date);
            echo '<p>Data: ' . $date->format('d/m/Y H:i') . '</p>';
        }
    }
}
```

### 2. Eventi in un Intervallo di Date

```php
$eventi_gennaio = entourance_get_paginated_items(array(
    'type' => 'event',
    'date_start' => '2024-01-01T00:00:00Z',
    'date_end' => '2024-01-31T23:59:59Z',
    'city' => 'Milano',
    'items_per_page' => 50
));
```

### 3. Experience di Tipo Specifico

```php
$tour = entourance_get_paginated_items(array(
    'type' => 'experience',
    'experience_type' => 'tour',
    'category' => 'cultural',
    'items_per_page' => 15
));
```

### 4. Paginazione Completa

```php
$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
));

// Mostra risultati
foreach ($result['data'] as $item) {
    // ... output ...
}

// Navigazione
if ($current_page > 1) {
    echo '<a href="?paged=' . ($current_page - 1) . '">« Precedente</a>';
}
if ($result['pagination']['has_more']) {
    echo '<a href="?paged=' . ($current_page + 1) . '">Successiva »</a>';
}
```

### 5. Uso in Template WordPress

```php
<?php
$prossimi_eventi = entourance_get_paginated_items(array(
    'type' => 'event',
    'date_start' => date('Y-m-d\T00:00:00\Z'),
    'items_per_page' => 6
));
?>

<?php if (!is_wp_error($prossimi_eventi) && $prossimi_eventi['success']) : ?>
    <section class="eventi">
        <h2>Prossimi Eventi</h2>
        <div class="eventi-grid">
            <?php foreach ($prossimi_eventi['data'] as $evento) : ?>
                <article>
                    <h3><?php echo esc_html($evento->title ?? 'Evento'); ?></h3>
                    <?php if (isset($evento->description)) : ?>
                        <p><?php echo esc_html(wp_trim_words($evento->description, 20)); ?></p>
                    <?php endif; ?>
                </article>
            <?php endforeach; ?>
        </div>
    </section>
<?php endif; ?>
```

### 6. Creare uno Shortcode Personalizzato

```php
function mio_shortcode_eventi($atts) {
    $atts = shortcode_atts(array(
        'limit' => 5,
        'city' => ''
    ), $atts);
    
    $args = array(
        'type' => 'event',
        'date_start' => date('Y-m-d\T00:00:00\Z'),
        'items_per_page' => intval($atts['limit'])
    );
    
    if (!empty($atts['city'])) {
        $args['city'] = $atts['city'];
    }
    
    $result = entourance_get_paginated_items($args);
    
    if (is_wp_error($result) || !$result['success']) {
        return '<p>Nessun evento disponibile</p>';
    }
    
    ob_start();
    foreach ($result['data'] as $evento) {
        echo '<div class="evento">';
        echo '<h4>' . esc_html($evento->title ?? 'Evento') . '</h4>';
        echo '</div>';
    }
    return ob_get_clean();
}
add_shortcode('miei_eventi', 'mio_shortcode_eventi');

// Uso: [miei_eventi limit="10" city="Milano"]
```

---

## Gestione Errori

```php
$result = entourance_get_paginated_items(array(
    'type' => 'event'
));

// Verifica errori WP
if (is_wp_error($result)) {
    error_log('Errore API Entourance: ' . $result->get_error_message());
    // Mostra messaggio all'utente
    echo '<p>Si è verificato un errore. Riprova più tardi.</p>';
    return;
}

// Verifica successo chiamata
if (!$result['success']) {
    echo '<p>Nessun risultato disponibile</p>';
    return;
}

// Verifica se ci sono dati
if (empty($result['data'])) {
    echo '<p>Nessun elemento trovato</p>';
    return;
}

// Procedi con l'elaborazione
foreach ($result['data'] as $item) {
    // ...
}
```

---

## Debug

Per vedere quali filtri sono stati applicati e l'URL API chiamato:

```php
$result = entourance_get_paginated_items(array(
    'type' => 'event',
    'date_start' => '2024-01-01T00:00:00Z',
    'city' => 'Milano'
));

// Mostra info debug
echo '<pre>';
print_r($result['filters_applied']);
echo "\n\nURL: " . $result['api_url'];
echo '</pre>';
```

---

## Note Importanti

1. **Formato Date**: Usa sempre il formato ISO 8601 per le date: `YYYY-MM-DDTHH:MM:SSZ`
   ```php
   $data = date('Y-m-d\T00:00:00\Z'); // Oggi
   $data = '2024-12-25T10:30:00Z';    // Data specifica
   ```

2. **Paginazione**: Il numero massimo di elementi per pagina è 100

3. **Performance**: Usa la cache se fai molte richieste:
   ```php
   $cache_key = 'entourance_events_' . md5(serialize($args));
   $result = get_transient($cache_key);
   
   if (false === $result) {
       $result = entourance_get_paginated_items($args);
       set_transient($cache_key, $result, HOUR_IN_SECONDS);
   }
   ```

4. **Sicurezza**: Sanifica sempre i dati in output:
   ```php
   echo esc_html($item->title);
   echo esc_url($item->url);
   echo esc_attr($item->id);
   ```

---

## Campi Validi per l'Ordinamento

L'ordinamento viene passato all'API come JSON array: `[{"field":"title","direction":"asc"}]`

### Campi comuni:

| Campo | Descrizione | Valido per |
|-------|-------------|-----------|
| `title` | Titolo | experience, event, article |
| `name` | Nome | poi, itinerary, host, eatery |
| `price` | Prezzo | Tutti i tipi |
| `created_at` | Data di creazione | Tutti i tipi |

**Note importanti:**
- La funzione converte automaticamente `name` ↔ `title` in base al tipo di contenuto
- Per experience e event, usa `title` (la funzione converte automaticamente `name` in `title`)
- Per poi e itinerary, usa `name` (la funzione converte automaticamente `title` in `name`)
- **Non usare** `start_date` per l'ordinamento ma `date`
- Per filtrare per date usa i parametri `date_start` e `date_end`

### Esempio:

```php
// Corretto - ordina per titolo
$result = entourance_get_paginated_items(array(
    'type' => 'event',
    'order_field' => 'title',
    'order_direction' => 'asc'
));

// Corretto - anche 'name' funziona (viene convertito automaticamente in 'title')
$result = entourance_get_paginated_items(array(
    'type' => 'event',
    'order_field' => 'name',  // Convertito in 'title'
    'order_direction' => 'desc'
));
```

---

## Supporto

Per domande o problemi, consulta la documentazione completa del plugin Entourance o contatta il supporto tecnico.

