<?php

namespace GriffinForms\Includes\Notifications\Channels;

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

class EmailAlerts implements NotificationChannelInterface
{
    public function getChannelId(): string
    {
        return 'email_alerts';
    }

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

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

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

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

    public function renderSection(array $current_data): void
    {
        $to   = $current_data['to'] ?? 'no_one';
        $rows = $current_data['emails'] ?? [];

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

        // Normalize rows: ensure we have at least one blank row
        if (empty($rows)) {
            $rows = [['email' => '', 'message_id' => 0]];
        }

        $next_row_id = count($rows) + 1;

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

        // Radio: no_one / specific_emails
        echo '<div class="row mb-3"><div class="col-md-12">';
        echo Factory::create('radio', 'alerts-to', $to, 'notif', [
            'show_label' => false,
            'name'       => 'gf_notif_alerts_to',
            'options'    => [
                'no_one'         => __('No one', 'griffinforms-form-builder'),
                'specific_emails' => __('Specific addresses', 'griffinforms-form-builder'),
            ],
        ])->render();
        echo '</div></div>';

        // Row editor (shown when specific_emails is selected)
        $row_display = ($to === 'specific_emails') ? '' : ' style="display:none;"';
        echo '<div id="gf-notif-alerts-emails-wrap"' . $row_display . '>';
        echo '<div id="gf-notif-alerts-container"';
        echo ' data-next-row-id="' . esc_attr($next_row_id) . '"';
        echo ' data-max-emails="5">';

        $default_label = __('No message', 'griffinforms-form-builder');

        foreach ($rows as $i => $row) {
            $row_id    = $i + 1;
            $email     = isset($row['email']) ? (string) $row['email'] : '';
            $msg_id    = isset($row['message_id']) ? absint($row['message_id']) : 0;
            $msg_name  = $default_label;
            $msg_heading = '';

            if ($msg_id > 0) {
                foreach ($messages as $msg) {
                    if ((int) $msg->id === $msg_id) {
                        $msg_name    = $msg->name ?: sprintf(__('Message #%d', 'griffinforms-form-builder'), $msg->id);
                        $msg_heading = $msg->heading ?? '';
                        break;
                    }
                }
            }

            $this->renderAlertEmailRow($row_id, $email, $msg_id, $msg_name, $msg_heading, $messages, $default_label);
        }

        echo '</div>';

        // Add row button
        echo '<div class="row mt-2"><div class="col-md-7">';
        echo '<button type="button" id="gf-notif-alerts-add" class="gf-btn-light btn griffinforms-app-fe-btn">';
        echo esc_html__('Add', 'griffinforms-form-builder');
        echo '</button>';
        echo '</div></div>';

        echo '</div>'; // #gf-notif-alerts-emails-wrap

        // Pass messages JSON to JS for dynamic row template
        echo '<script id="gf-notif-alerts-messages-data" type="application/json">';
        $messages_for_js = [];
        foreach ($messages as $msg) {
            $messages_for_js[] = [
                'id'      => (int) $msg->id,
                'name'    => $msg->name ?: sprintf(__('Message #%d', 'griffinforms-form-builder'), $msg->id),
                'heading' => $msg->heading ?? '',
            ];
        }
        echo wp_json_encode($messages_for_js);
        echo '</script>';

        echo '</div>'; // .gf-notif-alerts-panel
    }

    protected function renderAlertEmailRow(int $row_id, string $email, int $msg_id, string $msg_name, string $msg_heading, array $messages, string $default_label): void
    {
        $has_message = $msg_id > 0;

        echo '<div class="gf-notif-alerts-row row align-items-center mb-2" data-alert-row-id="' . esc_attr($row_id) . '">';

        // Email input
        echo '<div class="col-md-4">';
        echo '<input type="email" class="form-control gf-app-control-input gf-notif-alerts-email-input"';
        echo ' placeholder="' . esc_attr__('Email address', 'griffinforms-form-builder') . '"';
        echo ' value="' . esc_attr($email) . '">';
        echo '</div>';

        // Message select
        echo '<div class="col-md-5">';
        echo '<select class="form-select gf-app-control-input gf-notif-alerts-message-select">';
        echo '<option value="0">' . esc_html($default_label) . '</option>';
        foreach ($messages as $msg) {
            $selected = ((int) $msg->id === $msg_id) ? ' selected' : '';
            echo '<option value="' . esc_attr($msg->id) . '"' . $selected . '>' . esc_html($msg->name ?: sprintf(__('Message #%d', 'griffinforms-form-builder'), $msg->id)) . '</option>';
        }
        echo '</select>';
        echo '</div>';

        // Remove row button
        echo '<div class="col-md-1 text-end">';
        echo '<button type="button" class="gf-btn-light btn griffinforms-app-fe-btn gf-text-danger gf-notif-alerts-remove-row">';
        echo esc_html__('Delete', 'griffinforms-form-builder');
        echo '</button>';
        echo '</div>';

        echo '</div>';
    }

    public function secureData(array $raw): array
    {
        $to = isset($raw['to']) && $raw['to'] === 'specific_emails' ? 'specific_emails' : 'no_one';

        $secured_emails = [];

        if ($to === 'specific_emails' && isset($raw['emails']) && is_array($raw['emails'])) {
            foreach ($raw['emails'] as $row) {
                if (!is_array($row)) {
                    continue;
                }
                $email = isset($row['email']) ? sanitize_email((string) $row['email']) : '';
                if (empty($email)) {
                    continue;
                }
                $secured_emails[] = [
                    'email'      => $email,
                    'message_id' => isset($row['message_id']) ? absint($row['message_id']) : 0,
                ];
            }
        }

        return [
            'to'     => $to,
            'emails' => $secured_emails,
        ];
    }
}
