<?php

namespace GriffinForms\Includes\Notifications\Channels;

use GriffinForms\Includes\Notifications\NotificationChannelInterface;
use GriffinForms\Admin\App\FormControls\Factory;

class EmailAutoresponder implements NotificationChannelInterface
{
    public function getChannelId(): string
    {
        return 'email_autoresponder';
    }

    public function getLabel(): string
    {
        return __('Autoresponder', 'griffinforms-form-builder');
    }

    public function getStorageKey(): string
    {
        return 'email_autoresponder';
    }

    public function getJsGetterId(): string
    {
        return 'getEmailAutoresponderData';
    }

    public function getJsValidatorId(): string
    {
        return 'validateEmailAutoresponder';
    }

    public function renderSection(array $current_data): void
    {
        $enabled       = !empty($current_data['enabled']);
        $field_mapping = $current_data['field_mapping'] ?? '{}';

        $sql      = \GriffinForms\Admin\Sql\App::getInstance();
        $messages = $sql->getItems('message', ['id', 'name', 'heading']) ?: [];

        $nonce   = wp_create_nonce('check_email_field');
        $form_id = absint($_GET['form_id'] ?? 0);

        $message_options = [];
        foreach ($messages as $msg) {
            $message_options[(string) $msg->id] = $msg->name ?: sprintf(__('Message #%d', 'griffinforms-form-builder'), $msg->id);
        }

        echo '<div class="gf-notif-autoresponder-panel">';

        // Toggle
        echo '<div class="row mb-3"><div class="col-md-10">';
        echo Factory::create('checkbox', 'ar-toggle', $enabled ? 1 : 0, 'notif', [
            'name'          => 'email_autoresponder_enabled',
            'show_label'    => false,
            'checkbox_label' => __('Send an autoresponder email to the submitter', 'griffinforms-form-builder'),
        ])->render();
        echo '</div></div>';

        // Configuration panel (shown when toggle is on)
        $config_display = $enabled ? '' : ' style="display:none;"';
        echo '<div id="gf-notif-ar-config"' . $config_display . '>';

        // Email field status area
        echo '<div id="gf-notif-ar-field-status" class="mb-3">';
        echo '<span id="gf-notif-ar-verifying" class="text-muted small" style="display:none;">';
        echo esc_html__('Checking for email fields…', 'griffinforms-form-builder');
        echo '</span>';
        echo '<span id="gf-notif-ar-no-email" class="text-danger small" style="display:none;">';
        echo esc_html__('No email field found on this form. Add one to enable autoresponder.', 'griffinforms-form-builder');
        echo '</span>';
        echo '</div>';

        // Mapping table (shown when form has multiple email fields, built by JS)
        echo '<div id="gf-notif-ar-mapping-wrap" style="display:none;">';
        echo '<p class="small text-muted mb-2">' . esc_html__('Map a message to each email field:', 'griffinforms-form-builder') . '</p>';
        echo '<div class="gf-notif-ar-scrollarea mb-2" style="max-height: 260px; overflow-y: auto;">';
        echo '<table class="table table-sm small" id="gf-notif-ar-mapping-table">';
        echo '<thead><tr>';
        echo '<th>' . esc_html__('Email Field', 'griffinforms-form-builder') . '</th>';
        echo '<th class="text-center">&rArr;</th>';
        echo '<th>' . esc_html__('Message', 'griffinforms-form-builder') . '</th>';
        echo '</tr></thead>';
        echo '<tbody></tbody>';
        echo '</table>';
        echo '</div>';
        echo '</div>';

        // Message select (shown when form has exactly 1 email field)
        echo '<div id="gf-notif-ar-single-wrap" style="display:none;">';
        echo Factory::create('select', 'ar-message-select', '', 'notif', [
            'show_label'  => false,
            'placeholder' => __('— Select a message —', 'griffinforms-form-builder'),
            'options'     => $message_options,
            'input_classes' => 'form-select-sm',
        ])->render();
        echo '</div>';

        // Create message link
        echo '<div class="mt-1 mb-2">';
        $create_url = admin_url('admin.php?page=griffinforms-message');
        echo '<a href="' . esc_url($create_url) . '" target="_blank" rel="noopener noreferrer" class="small">';
        echo esc_html__('Create a new message', 'griffinforms-form-builder') . ' &rarr;';
        echo '</a>';
        echo '</div>';

        // Hidden storage field
        echo '<input type="hidden" id="gf-notif-ar-field-mappings" value="' . esc_attr($field_mapping) . '">';

        // Data attributes for JS
        echo '<div id="gf-notif-ar-js-data"';
        echo ' data-nonce="' . esc_attr($nonce) . '"';
        echo ' data-form-id="' . esc_attr($form_id) . '"';
        echo '></div>';

        echo '</div>'; // #gf-notif-ar-config
        echo '</div>'; // .gf-notif-autoresponder-panel
    }

    public function secureData(array $raw): array
    {
        $enabled = !empty($raw['enabled']);

        $field_mapping_raw = isset($raw['field_mapping']) ? $raw['field_mapping'] : '[]';
        $secured_mappings  = [];

        if ($enabled && is_string($field_mapping_raw) && !empty($field_mapping_raw)) {
            $decoded = json_decode($field_mapping_raw, true);

            if (is_array($decoded)) {
                foreach ($decoded as $mapping) {
                    if (
                        is_array($mapping) &&
                        isset($mapping['email_field_id'], $mapping['message_id']) &&
                        is_numeric($mapping['email_field_id']) &&
                        is_numeric($mapping['message_id'])
                    ) {
                        $secured_mappings[] = [
                            'email_field_id' => absint($mapping['email_field_id']),
                            'message_id'     => absint($mapping['message_id']),
                        ];
                    }
                }
            }
        }

        return [
            'enabled'       => $enabled,
            'field_mapping' => json_encode($secured_mappings),
        ];
    }
}
