<?php

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

// Valeurs actuelles en base
$api_key  = get_option('esi_peppol_api_key', '');
$password = get_option('esi_peppol_password', '');
$email    = get_option('esi_peppol_email', '');
$logo_email_id = get_option('esi_peppol_logo_email_id', '');

// Récupérer l'URL de l'image pour la preview
$logo_email_url = '';
if ($logo_email_id) {
    $logo_email_url = wp_get_attachment_image_url((int) $logo_email_id, 'medium');
}

// Messages de feedback (optionnels, passés via $notice / $error)
/** @var string|null $notice */
/** @var string|null $error */
?>

<div class="wrap esi-peppol-settings-wrap">
    <h1><?php esc_html_e('Configuration ESI Peppol', 'esi_peppol'); ?></h1>

    <!-- <p>
        <?php
        printf(
            wp_kses_post(
                /* translators: %s: URL de la page de démonstration API */
                __('Vous pouvez tester et consulter la documentation de l\'API sur la page de démonstration&nbsp;: <a href="%s" target="_blank" rel="noopener noreferrer">ESIPeppol API Demo</a>.', 'esi_peppol')
            ),
            esc_url('https://scrada.esiweb.pro/api-demo.html')
        );
        ?>
    </p> -->

    <?php
    $vat_notices = \ESI_PEPPOL\controllers\PEPPOL_Plugin::get_vat_notice_message();
    if (!empty($vat_notices)) :
        foreach ($vat_notices as $notice) :
            $notice_class = 'notice-' . $notice['type'];
            ?>
            <div class="notice <?php echo esc_attr($notice_class); ?>">
                <p><?php echo wp_kses_post($notice['message']); ?></p>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>

    <?php if (!empty($notice)) : ?>
        <div class="notice notice-success is-dismissible">
            <p><?php echo esc_html($notice); ?></p>
        </div>
    <?php endif; ?>

    <?php if (!empty($error)) : ?>
        <div class="notice notice-error">
            <p><?php echo esc_html($error); ?></p>
        </div>
    <?php endif; ?>

    <div class="esi-peppol-settings-card">
        <form method="post">
            <?php wp_nonce_field('esi_peppol_save_settings', 'esi_peppol_nonce'); ?>

            <table class="form-table" role="presentation">
                <tbody>
                <tr>
                    <th scope="row">
                        <label for="esi_peppol_api_key"><?php esc_html_e('API Key', 'esi_peppol'); ?></label>
                    </th>
                    <td>
                        <input type="text"
                               class="regular-text"
                               id="esi_peppol_api_key"
                               name="esi_peppol_api_key"
                               value="<?php echo esc_attr($api_key); ?>"
                        />
                    </td>
                </tr>

                <tr>
                    <th scope="row">
                        <label for="esi_peppol_password"><?php esc_html_e('Password', 'esi_peppol'); ?></label>
                    </th>
                    <td>
                        <div class="esi-peppol-password-wrapper">
                            <input type="password"
                                   class="regular-text"
                                   id="esi_peppol_password"
                                   name="esi_peppol_password"
                                   value="<?php echo esc_attr($password); ?>"
                            />
                            <button type="button"
                                    class="button button-small esi-peppol-password-toggle"
                                    aria-label="<?php esc_attr_e('Afficher/Masquer le mot de passe', 'esi_peppol'); ?>"
                                    data-target="#esi_peppol_password">
                                <?php esc_html_e('Afficher', 'esi_peppol'); ?>
                            </button>
                        </div>
                    </td>
                </tr>

                <tr>
                    <th scope="row">
                        <label for="esi_peppol_email"><?php esc_html_e('Email', 'esi_peppol'); ?></label>
                    </th>
                    <td>
                        <input type="email"
                               class="regular-text"
                               id="esi_peppol_email"
                               name="esi_peppol_email"
                               value="<?php echo esc_attr($email); ?>"
                        />
                        <p class="description">
                            <?php esc_html_e('En cas d\'erreur d\'envoi des factures vous recevrez un email via l\'adresse encodée ci-dessus.', 'esi_peppol'); ?>
                        </p>
                    </td>
                </tr>

                <tr>
                    <th scope="row">
                        <label><?php esc_html_e('URL Webhook', 'esi_peppol'); ?></label>
                    </th>
                    <td>
                        <?php
                        $webhook_url = \ESI_PEPPOL\controllers\PEPPOL_Webhook_controller::get_webhook_url();
                        ?>
                        <div class="esi-peppol-webhook-url-wrapper">
                            <code id="esi_peppol_webhook_url" class="esi-peppol-webhook-url-display"><?php echo esc_html($webhook_url); ?></code>
                            <button type="button"
                                    class="button button-small esi-peppol-copy-webhook-url"
                                    data-target="#esi_peppol_webhook_url"
                                    aria-label="<?php esc_attr_e('Copier l\'URL du webhook', 'esi_peppol'); ?>">
                                <?php esc_html_e('Copier', 'esi_peppol'); ?>
                            </button>
                        </div>
                        <p class="description">
                            <?php
                            printf(
                                wp_kses_post(
                                    /* translators: %s: URL de la documentation */
                                    __('Configurez cette URL dans votre profil d\'entreprise sur la plateforme https://peppol.esi-web.be/. Les webhooks permettent de recevoir des notifications automatiques lorsque le statut d\'un document change. <a href="%s" target="_blank" rel="noopener noreferrer">En savoir plus</a>.', 'esi_peppol')
                                ),
                                esc_url('https://demo.esi-peppol.be/api-demo.html#webhooks')
                            );
                            ?>
                        </p>
                    </td>
                </tr>

                <tr>
                    <th scope="row">
                        <label><?php esc_html_e('Champ TVA', 'esi_peppol'); ?></label>
                    </th>
                    <td>
                        <?php
                        $saved_vat_field = get_option('esi_peppol_vat_field_key', '');
                        $auto_detected = (bool) get_option('esi_peppol_vat_field_auto_detected', false);
                        ?>
                        <div class="esi-peppol-vat-field-wrapper">
                            <button type="button"
                                    id="esi-peppol-detect-vat-fields"
                                    class="button button-secondary">
                                <?php esc_html_e('Détecter les champs TVA', 'esi_peppol'); ?>
                            </button>
                            <div id="esi-peppol-vat-fields-result" style="margin-top: 15px;"></div>
                            
                            <?php if ($saved_vat_field) : ?>
                                <div style="margin-top: 15px; padding: 10px; background-color: #f0f0f1; border-left: 4px solid #2271b1;">
                                    <p style="margin: 0;">
                                        <strong><?php esc_html_e('Champ TVA détecté :', 'esi_peppol'); ?></strong>
                                        <code style="margin-left: 5px; padding: 2px 6px; background-color: #fff; border: 1px solid #c3c4c7;"><?php echo esc_html($saved_vat_field); ?></code>
                                    </p>
                                    <?php if ($auto_detected) : ?>
                                        <p style="margin: 5px 0 0 0; font-size: 12px; color: #646970;">
                                            <?php esc_html_e('✓ Détecté automatiquement lors de l\'installation', 'esi_peppol'); ?>
                                        </p>
                                    <?php endif; ?>
                                </div>
                            <?php elseif ($auto_detected) : ?>
                                <div style="margin-top: 15px; padding: 10px; background-color: #fff3cd; border-left: 4px solid #dba617;">
                                    <p style="margin: 0;">
                                        <?php esc_html_e('Aucun champ TVA n\'a été détecté automatiquement lors de l\'installation. Utilisez le bouton ci-dessus pour rechercher manuellement les champs TVA dans vos commandes.', 'esi_peppol'); ?>
                                    </p>
                                </div>
                            <?php endif; ?>
                        </div>
                        <p class="description">
                            <?php esc_html_e('Utilisez cet utilitaire pour détecter automatiquement le champ TVA utilisé dans vos commandes WooCommerce. Si un seul champ est trouvé, il sera automatiquement sélectionné. Si plusieurs champs sont détectés, vous pourrez choisir celui à utiliser.', 'esi_peppol'); ?>
                        </p>
                    </td>
                </tr>

                <tr>
                    <th scope="row">
                        <label for="esi_peppol_invoice_number_format"><?php esc_html_e('Format num facture', 'esi_peppol'); ?></label>
                    </th>
                    <td>
                        <?php
                        $backup_invoice_format = (string) get_option('esi_peppol_invoice_number_format', '');
                        if ($backup_invoice_format === '') {
                            $backup_invoice_format = (string) get_option('esi_peppol_vat_number_format', '');
                        }
                        $has_wpo_invoices = \ESI_PEPPOL\helpers\PEPPOL_Woo_Helper::esi_has_wpo_invoice_numbers();
                        $detected_format = $has_wpo_invoices
                            ? \ESI_PEPPOL\helpers\PEPPOL_Woo_Helper::esi_get_wpo_invoice_number_format_label()
                            : '';
                        ?>
                        <?php if ($detected_format !== '') : ?>
                            <p style="margin: 0;">
                                <strong><?php esc_html_e('Format détecté :', 'esi_peppol'); ?></strong>
                                <code style="margin-left: 5px; padding: 2px 6px; background-color: #fff; border: 1px solid #c3c4c7;">
                                    <?php echo esc_html($detected_format); ?>
                                </code>
                            </p>
                            <p class="description">
                                <?php esc_html_e('Le format est détecté automatiquement via WPO WCPDF. Le champ de backup n\'est pas requis.', 'esi_peppol'); ?>
                            </p>
                        <?php else : ?>
                            <input type="text"
                                   class="regular-text esi-peppol-invoice-format-input"
                                   id="esi_peppol_invoice_number_format"
                                   name="esi_peppol_invoice_number_format"
                                   value="<?php echo esc_attr($backup_invoice_format); ?>"
                            />
                            <div class="esi-peppol-placeholder-buttons" style="margin-top: 8px;">
                                <button type="button" class="button button-secondary esi-peppol-placeholder-btn" data-placeholder="{YYYY}">{YYYY}</button>
                                <button type="button" class="button button-secondary esi-peppol-placeholder-btn" data-placeholder="{YY}">{YY}</button>
                                <button type="button" class="button button-secondary esi-peppol-placeholder-btn" data-placeholder="{MM}">{MM}</button>
                                <button type="button" class="button button-secondary esi-peppol-placeholder-btn" data-placeholder="{DD}">{DD}</button>
                                <button type="button" class="button button-secondary esi-peppol-placeholder-btn" data-placeholder="{ORDER_ID}">{ORDER_ID}</button>
                                <button type="button" class="button button-secondary esi-peppol-placeholder-btn" data-placeholder="{ORDER_NUMBER}">{ORDER_NUMBER}</button>
                                <button type="button" class="button button-secondary esi-peppol-placeholder-btn" data-placeholder="{number}">{number}</button>
                            </div>
                            <p class="description">
                                <?php esc_html_e('Format de secours si aucun format n\'est détecté automatiquement. Doit se terminer par {number}. Placeholders : {YYYY}, {YY}, {MM}, {DD}, {ORDER_ID}, {ORDER_NUMBER}, {number}.', 'esi_peppol'); ?>
                            </p>
                        <?php endif; ?>
                    </td>
                </tr>

                <!-- <tr>
                    <th scope="row">
                        <label for="esi_peppol_logo_email"><?php esc_html_e('Logo Email', 'esi_peppol'); ?></label>
                    </th>
                    <td>
                        <input type="hidden"
                               id="esi_peppol_logo_email_id"
                               name="esi_peppol_logo_email_id"
                               value="<?php echo esc_attr($logo_email_id); ?>"
                        />
                        <button type="button"
                                id="esi-peppol-upload-logo"
                                class="button">
                            <?php esc_html_e('Choisir un logo', 'esi_peppol'); ?>
                        </button>
                        <button type="button"
                                id="esi-peppol-remove-logo"
                                class="button button-link-delete"
                                style="<?php echo $logo_email_id ? '' : 'display:none;'; ?>">
                            <?php esc_html_e('Supprimer', 'esi_peppol'); ?>
                        </button>
                        <div id="esi-peppol-logo-preview" class="esi-peppol-logo-preview" style="<?php echo $logo_email_url ? '' : 'display:none;'; ?>">
                            <?php if ($logo_email_url) : ?>
                                <img src="<?php echo esc_url($logo_email_url); ?>" alt="<?php esc_attr_e('Logo email', 'esi_peppol'); ?>" />
                            <?php endif; ?>
                        </div>
                        <p class="description">
                            <?php esc_html_e('Logo affiché dans les emails Peppol.', 'esi_peppol'); ?>
                        </p>
                    </td>
                </tr> -->
                </tbody>
            </table>

            <p class="submit">
                <button type="submit"
                        name="esi_peppol_action"
                        value="save"
                        class="button button-primary">
                    <?php esc_html_e('Enregistrer', 'esi_peppol'); ?>
                </button>

                <button type="button"
                        id="esi-peppol-test-connection"
                        class="button button-secondary"
                        style="margin-left: 10px;">
                    <?php esc_html_e('Tester la connexion', 'esi_peppol'); ?>
                </button>
            </p>

            <div id="esi-peppol-test-result"></div>
        </form>
    </div>
</div>


