<?php
// Configura la tua API key di Brevo
$apiKey = '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';
$apiUrl = 'https://api.brevo.com/v3';

// Funzione per effettuare richieste API Brevo
function callBrevoApi($endpoint, $method = 'GET', $data = null) {
    global $apiKey, $apiUrl;

    $url = "$apiUrl$endpoint";
    $headers = [
        "accept: application/json",
        "api-key: $apiKey",
        "content-type: application/json"
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    if ($data) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    }

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return ['response' => json_decode($response, true), 'httpCode' => $httpCode];
}

// Funzione per ottenere statistiche della campagna 351 per un contatto specifico
function getCampaignStatsByEmail($email) {
    $campaignId = 351;
    $encodedEmail = urlencode($email);
    $response = callBrevoApi("/emailCampaigns/$campaignId/reports?email=$encodedEmail", 'GET');

    if ($response['httpCode'] === 200 && isset($response['response']['statistics'])) {
        return [
            'uniqueViews' => $response['response']['statistics']['uniqueViews'] ?? '0',
            'uniqueClicks' => $response['response']['statistics']['uniqueClicks'] ?? '0'
        ];
    }
    return ['uniqueViews' => '0', 'uniqueClicks' => '0'];
}

// Verifica connessione API Brevo
$connectionStatus = callBrevoApi('/account');
$brevoConnected = $connectionStatus['httpCode'] === 200;
$brevoMessage = $brevoConnected ? 'Connesso a Brevo' : 'Errore di connessione: ' . $connectionStatus['httpCode'];

// Recupera i contatti della lista 148
$response = callBrevoApi('/contacts/lists/148/contacts');
$contacts = $response['response']['contacts'] ?? [];
$errorFetchingContacts = $response['httpCode'] !== 200 ? 'Errore nel recupero contatti: ' . $response['httpCode'] : '';
?>

<!DOCTYPE html>
<html lang="it">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestione Contatti Brevo</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/uikit@3.16.21/dist/css/uikit.min.css" />
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.1/css/jquery.dataTables.min.css">
</head>
<body>
<div class="uk-container uk-margin-top">
    <h2>Gestione Contatti della Lista 148</h2>

    <div class="uk-alert-<?= $brevoConnected ? 'success' : 'danger' ?>" uk-alert>
        <p><?= $brevoMessage ?></p>
    </div>

    <?php if ($errorFetchingContacts): ?>
        <div class="uk-alert-danger" uk-alert>
            <p><?= $errorFetchingContacts ?></p>
        </div>
    <?php endif; ?>

    <table id="contactsTable" class="uk-table uk-table-divider uk-table-striped">
        <thead>
        <tr>
            <th>Email</th>
            <th>Nome</th>
            <th>Cognome</th>
            <th>Titolo</th>
            <th>Società</th>
            <th>Paese</th>
            <th>Tipologia</th>
            <th>Città</th>
            <th>Telefono</th>
            <th>Aperture</th>
            <th>Click</th>
            <th>Azioni</th>
        </tr>
        </thead>
        <tbody>
        <?php foreach ($contacts as $contact): ?>
            <?php $campaignStats = getCampaignStatsByEmail($contact['email']); ?>
            <tr>
                <td><?= htmlspecialchars($contact['email']) ?></td>
                <td><?= htmlspecialchars($contact['attributes']['NOME'] ?? '') ?></td>
                <td><?= htmlspecialchars($contact['attributes']['COGNOME'] ?? '') ?></td>
                <td><?= htmlspecialchars($contact['attributes']['TITOLO'] ?? '') ?></td>
                <td><?= htmlspecialchars($contact['attributes']['ENTE_O_SOCIETA'] ?? '') ?></td>
                <td><?= htmlspecialchars($contact['attributes']['PAESE'] ?? '') ?></td>
                <td><?= htmlspecialchars($contact['attributes']['TIPOLOGIA'] ?? '') ?></td>
                <td><?= htmlspecialchars($contact['attributes']['CITTA'] ?? '') ?></td>
                <td><?= htmlspecialchars($contact['attributes']['TELEFONO_TEXT'] ?? '') ?></td>
                <td><?= $campaignStats['uniqueViews'] ?></td>
                <td><?= $campaignStats['uniqueClicks'] ?></td>
                <td>
                    <button class="uk-button uk-button-primary edit-button" data-email="<?= htmlspecialchars($contact['email']) ?>">Modifica</button>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- Modal per modifica contatto -->
<div id="edit-modal" uk-modal>
    <div class="uk-modal-dialog uk-modal-body">
        <h2 class="uk-modal-title">Modifica Contatto</h2>
        <form id="edit-form">
            <input type="hidden" id="edit-email" name="email">
            <label>Nome: <input class="uk-input" type="text" id="edit-nome" name="NOME"></label>
            <label>Cognome: <input class="uk-input" type="text" id="edit-cognome" name="COGNOME"></label>
            <label>Telefono: <input class="uk-input" type="text" id="edit-telefono" name="TELEFONO_TEXT"></label>
            <button type="submit" class="uk-button uk-button-primary">Salva</button>
        </form>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.1/js/jquery.dataTables.min.js"></script>
<script>
    $(document).ready(function() {
        $('#contactsTable').DataTable({ scrollX: true });

        $('.edit-button').on('click', function() {
            const email = $(this).data('email');
            $('#edit-email').val(email);
            UIkit.modal('#edit-modal').show();
        });

        $('#edit-form').on('submit', function(e) {
            e.preventDefault();
            $.post('edit_contact.php', $(this).serialize(), function(response) {
                alert('Contatto aggiornato con successo!');
                location.reload();
            });
        });
    });
</script>
</body>
</html>