<?php
/**
 * Plugin Name: ARIA Maintenance
 * Plugin URI:  https://demo.sohos.fr
 * Description: Connecteur ARIA — signalement de problèmes et monitoring de site
 * Version:     1.0.0
 * Author:      agence
 * License:     Proprietary
 */

if (!defined('ABSPATH')) exit;

define('ARIA_API_URL', 'https://demo.sohos.fr/api/maintenance');

// ── Admin page ──────────────────────────────────────────────────────────────

add_action('admin_menu', function () {
    add_menu_page(
        'ARIA Maintenance',
        'ARIA Maintenance',
        'manage_options',
        'aria-maintenance',
        'aria_maintenance_settings_page',
        'dashicons-shield',
        80
    );
});

function aria_maintenance_settings_page() {
    if (isset($_POST['aria_save']) && check_admin_referer('aria_save_settings')) {
        update_option('aria_api_key',  sanitize_text_field($_POST['aria_api_key']  ?? ''));
        update_option('aria_site_url', sanitize_text_field($_POST['aria_site_url'] ?? get_site_url()));
        echo '<div class="notice notice-success"><p>Paramètres sauvegardés.</p></div>';
    }
    $api_key  = get_option('aria_api_key', '');
    $site_url = get_option('aria_site_url', get_site_url());
    ?>
    <div class="wrap">
        <h1><span class="dashicons dashicons-shield"></span> ARIA Maintenance</h1>
        <form method="post">
            <?php wp_nonce_field('aria_save_settings'); ?>
            <table class="form-table">
                <tr>
                    <th scope="row">Clé API ARIA</th>
                    <td>
                        <input type="text" name="aria_api_key" value="<?php echo esc_attr($api_key); ?>"
                               class="regular-text" placeholder="aria_xxxxxxxxxxxxxxxx..." />
                        <p class="description">Générez cette clé depuis ARIA → Admin → Connecteur WordPress</p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">URL de ce site</th>
                    <td>
                        <input type="url" name="aria_site_url" value="<?php echo esc_attr($site_url); ?>"
                               class="regular-text" />
                    </td>
                </tr>
            </table>
            <p>
                <button type="submit" name="aria_save" class="button button-primary">Sauvegarder</button>
                <button type="button" id="aria-test-btn" class="button">Tester la connexion</button>
            </p>
        </form>

        <hr>
        <h2>Statut de monitoring</h2>
        <div id="aria-status-box" style="padding:12px;background:#f0f0f1;border-radius:4px;max-width:500px;">
            <span id="aria-status-text">Cliquez sur "Tester la connexion" pour vérifier.</span>
        </div>
    </div>

    <script>
    document.getElementById('aria-test-btn').addEventListener('click', function() {
        var btn = this;
        btn.disabled = true;
        btn.textContent = 'Test en cours…';
        fetch(ajaxurl, {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'action=aria_test_connection&_ajax_nonce=' + aria_nonce.nonce
        })
        .then(r => r.json())
        .then(data => {
            document.getElementById('aria-status-text').innerHTML = data.html;
            btn.disabled = false;
            btn.textContent = 'Tester la connexion';
        })
        .catch(() => {
            document.getElementById('aria-status-text').textContent = 'Erreur de connexion.';
            btn.disabled = false;
            btn.textContent = 'Tester la connexion';
        });
    });
    </script>
    <?php
}

// ── AJAX test connection ─────────────────────────────────────────────────────

add_action('wp_ajax_aria_test_connection', function () {
    check_ajax_referer('aria_nonce', '_ajax_nonce');
    $api_key  = get_option('aria_api_key', '');
    $site_url = get_option('aria_site_url', get_site_url());

    if (empty($api_key)) {
        wp_send_json(['html' => '<span style="color:orange">⚠️ Clé API non configurée.</span>']);
    }

    $response = wp_remote_get(ARIA_API_URL . '/monitoring/status', [
        'headers' => ['X-API-Key' => $api_key, 'Accept' => 'application/json'],
        'timeout' => 10,
    ]);

    if (is_wp_error($response)) {
        wp_send_json(['html' => '<span style="color:red">❌ Connexion impossible : ' . esc_html($response->get_error_message()) . '</span>']);
    }

    $body = json_decode(wp_remote_retrieve_body($response), true);
    if (empty($body['success'])) {
        wp_send_json(['html' => '<span style="color:red">❌ Clé API invalide ou erreur serveur.</span>']);
    }

    if (empty($body['monitored'])) {
        wp_send_json(['html' => '<span style="color:blue">✅ Connexion OK — Site pas encore monitoré dans ARIA.</span>']);
    }

    $status    = $body['status'] === 'up' ? '<span style="color:green">✅ En ligne</span>' : '<span style="color:red">❌ Hors ligne</span>';
    $uptime    = number_format($body['uptime_pct'] ?? 100, 1);
    $response_ms = $body['response_ms'] ?? '-';
    wp_send_json(['html' => "Statut : {$status} | Uptime : {$uptime}% | Temps de réponse : {$response_ms} ms"]);
});

// ── Admin bar "Signaler un problème" button ──────────────────────────────────

add_action('admin_bar_menu', function ($wp_admin_bar) {
    if (!get_option('aria_api_key')) return;
    $wp_admin_bar->add_node([
        'id'    => 'aria-report',
        'title' => '<span class="ab-icon dashicons dashicons-warning" style="color:#e53e3e;margin-top:2px;"></span> Signaler un problème',
        'href'  => '#aria-report-modal',
    ]);
}, 999);

// ── Modal + JS sur toutes les pages admin ────────────────────────────────────

add_action('admin_footer', function () {
    if (!get_option('aria_api_key')) return;
    $current_url = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $current_user = wp_get_current_user();
    ?>
    <div id="aria-report-modal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:999999;align-items:center;justify-content:center;">
        <div style="background:#fff;border-radius:8px;padding:28px;width:480px;max-width:95vw;box-shadow:0 20px 60px rgba(0,0,0,.4);">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;">
                <h2 style="margin:0;font-size:18px;">🛠 Signaler un problème</h2>
                <button id="aria-modal-close" style="background:none;border:none;cursor:pointer;font-size:22px;line-height:1;">&times;</button>
            </div>
            <form id="aria-report-form">
                <div style="margin-bottom:14px;">
                    <label style="display:block;margin-bottom:4px;font-weight:600;">Titre du problème <span style="color:red">*</span></label>
                    <input type="text" id="aria-titre" required style="width:100%;padding:8px;border:1px solid #ddd;border-radius:4px;font-size:14px;" />
                </div>
                <div style="margin-bottom:14px;">
                    <label style="display:block;margin-bottom:4px;font-weight:600;">Description <span style="color:red">*</span></label>
                    <textarea id="aria-description" required rows="4" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:4px;font-size:14px;resize:vertical;"></textarea>
                </div>
                <div style="margin-bottom:20px;">
                    <label style="display:block;margin-bottom:4px;font-weight:600;">Priorité</label>
                    <select id="aria-priorite" style="padding:8px;border:1px solid #ddd;border-radius:4px;font-size:14px;">
                        <option value="normale">Normale</option>
                        <option value="haute">Haute</option>
                        <option value="urgente">Urgente</option>
                        <option value="faible">Faible</option>
                    </select>
                </div>
                <div id="aria-form-msg" style="display:none;padding:10px;border-radius:4px;margin-bottom:14px;font-size:13px;"></div>
                <div style="display:flex;gap:10px;justify-content:flex-end;">
                    <button type="button" id="aria-cancel" style="padding:8px 18px;border:1px solid #ddd;background:#f7f7f7;border-radius:4px;cursor:pointer;">Annuler</button>
                    <button type="submit" id="aria-submit" style="padding:8px 18px;background:#2563eb;color:#fff;border:none;border-radius:4px;cursor:pointer;font-weight:600;">Envoyer</button>
                </div>
            </form>
        </div>
    </div>

    <script>
    (function() {
        var modal    = document.getElementById('aria-report-modal');
        var form     = document.getElementById('aria-report-form');
        var msgBox   = document.getElementById('aria-form-msg');
        var apiKey   = <?php echo json_encode(get_option('aria_api_key', '')); ?>;
        var siteUrl  = <?php echo json_encode(get_option('aria_site_url', get_site_url())); ?>;
        var pageUrl  = <?php echo json_encode($current_url); ?>;
        var wpUser   = <?php echo json_encode($current_user->display_name ?? ''); ?>;
        var wpEmail  = <?php echo json_encode($current_user->user_email ?? ''); ?>;
        var apiBase  = <?php echo json_encode(ARIA_API_URL); ?>;

        function openModal() { modal.style.display = 'flex'; }
        function closeModal() { modal.style.display = 'none'; form.reset(); msgBox.style.display = 'none'; }

        document.querySelector('#wp-admin-bar-aria-report a')?.addEventListener('click', function(e) {
            e.preventDefault(); openModal();
        });
        document.getElementById('aria-modal-close').addEventListener('click', closeModal);
        document.getElementById('aria-cancel').addEventListener('click', closeModal);
        modal.addEventListener('click', function(e) { if (e.target === modal) closeModal(); });

        form.addEventListener('submit', function(e) {
            e.preventDefault();
            var btn = document.getElementById('aria-submit');
            btn.disabled = true;
            btn.textContent = 'Envoi…';
            msgBox.style.display = 'none';

            fetch(apiBase + '/ticket', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-API-Key': apiKey
                },
                body: JSON.stringify({
                    titre:          document.getElementById('aria-titre').value,
                    description:    document.getElementById('aria-description').value,
                    priorite:       document.getElementById('aria-priorite').value,
                    reporter_name:  wpUser,
                    reporter_email: wpEmail,
                    page_url:       pageUrl,
                    site_url:       siteUrl
                })
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    msgBox.style.cssText = 'display:block;background:#d1fae5;border:1px solid #6ee7b7;color:#065f46;padding:10px;border-radius:4px;margin-bottom:14px;font-size:13px;';
                    msgBox.textContent = '✅ Ticket ' + data.ticket.numero + ' créé avec succès !';
                    form.reset();
                    setTimeout(closeModal, 2000);
                } else {
                    throw new Error(data.message || 'Erreur inconnue');
                }
            })
            .catch(err => {
                msgBox.style.cssText = 'display:block;background:#fee2e2;border:1px solid #fca5a5;color:#991b1b;padding:10px;border-radius:4px;margin-bottom:14px;font-size:13px;';
                msgBox.textContent = '❌ ' + err.message;
            })
            .finally(() => {
                btn.disabled = false;
                btn.textContent = 'Envoyer';
            });
        });
    })();
    </script>
    <?php
});

// ── Enqueue nonce for AJAX ───────────────────────────────────────────────────

add_action('admin_enqueue_scripts', function () {
    wp_localize_script('jquery', 'aria_nonce', ['nonce' => wp_create_nonce('aria_nonce')]);
});