<?php

namespace GriffinForms\Admin\Html\FormControls\Form;

class EntryAlerts extends \GriffinForms\Admin\Html\FormControls\Form\Format
{    
    public function html()
    {
        echo '<div class="row">';
        echo '<div class="col-md-12 mb-3" id="griffinforms-entryalertsto-wrap">';
        $this->entryAlertsTo();
        echo '</div>';        
        echo '<div class="griffinforms-hidden-option col-md-12 mb-3" id="griffinforms-entryalertsemails-wrap">';
        $this->entryAlertsEmails();
        echo '</div>';
        echo '</div>';
        
    }
    
    protected function entryAlertsTo()
    {
        if(is_array($this->value) and count($this->value) > 0) {
            $value = 'specific_emails';
        } else {
            $value = 'no_one';
        }
        
        $choices = $this->choices->getChoices('entry_alerts_to');
        $field = new \GriffinForms\Admin\Html\FormControls\InputRadio('entry_alerts_to', $value);
        $field->radioOptions($choices);
        $field->html();
    }
    
    protected function entryAlertsEmails()
    {
        $rows = $this->normalizeAlertEmailRows();
        $default_label = $this->lang->getText('default_message_label');

        echo '<div id="griffinforms-entryalertsemails-container" data-next-row-id="' . esc_attr($rows['next_row_id']) . '" data-max-emails="5">';
        foreach ($rows['rows'] as $row) {
            $this->renderAlertEmailRow($row['row_id'], $row['email'], $row['message_id'], $row['message_name'], $row['message_heading'], $default_label);
        }
        echo '</div>';

        echo '<div class="row"><div class="col-md-7 text-center mt-3">';
        echo '<button type="button" id="griffinforms-entryalertsemails-add" class="gf-entryalert-add-btn btn btn-sm btn-dark">';
        $this->mIcon('add');
        echo '</button></div></div>';
    }

    protected function normalizeAlertEmailRows(): array
    {
        $rows = [];
        $row_id = 0;

        if (is_array($this->value) && !empty($this->value)) {
            $is_assoc = array_keys($this->value) !== range(0, count($this->value) - 1);
            if ($is_assoc) {
                foreach ($this->value as $email => $message_id) {
                    $row_id++;
                    $rows[] = $this->buildAlertEmailRow($row_id, $email, $message_id);
                }
            } else {
                foreach ($this->value as $email) {
                    $row_id++;
                    $rows[] = $this->buildAlertEmailRow($row_id, $email, 0);
                }
            }
        }

        if (empty($rows)) {
            $row_id++;
            $rows[] = $this->buildAlertEmailRow($row_id, '', 0);
        }

        return [
            'rows' => $rows,
            'next_row_id' => $row_id + 1,
        ];
    }

    protected function buildAlertEmailRow(int $row_id, $email, $message_id): array
    {
        $email = is_string($email) ? $email : '';
        $message_id = absint($message_id);
        $message_name = '';
        $message_heading = '';

        if ($message_id > 0) {
            $message = $this->sql->itemValues($message_id, 'message', ['name', 'heading']);
            if ($message) {
                $message_name = !empty($message->name) ? $message->name : 'Message ID ' . $message_id;
                $message_heading = $message->heading ?? '';
            }
        }

        return [
            'row_id' => $row_id,
            'email' => $email,
            'message_id' => $message_id,
            'message_name' => $message_name,
            'message_heading' => $message_heading,
        ];
    }

    protected function truncateText(string $text, int $maxLength): string
    {
        if ($maxLength <= 0 || $text === '') {
            return $text;
        }
        if (mb_strlen($text) <= $maxLength) {
            return $text;
        }
        return mb_substr($text, 0, $maxLength - 3) . '...';
    }

    protected function renderAlertEmailRow(int $row_id, string $email, int $message_id, string $message_name, string $message_heading, string $default_label): void
    {
        $select_label = $this->lang->getText('select_message_label');
        $change_label = $this->lang->getText('change_message_label');
        $remove_label = $this->lang->getText('remove_message_label');
        $placeholder = $this->lang->getText('admin_email_placeholder');

        $button_label = $message_id > 0 ? $change_label : $select_label;
        $show_remove = $message_id > 0 ? '' : ' style="display: none;"';
        $message_name = $message_id > 0 ? $message_name : $default_label;
        $message_heading = $message_id > 0 ? $message_heading : '';
        $message_name = $this->truncateText($message_name, 40);
        $message_heading = $this->truncateText($message_heading, 48);

        echo '<div class="gf-entryalert-row row align-items-center mb-2" data-alert-row-id="' . esc_attr($row_id) . '">';
        echo '<div class="col-md-3">';
        echo '<input type="email" class="form-control griffinforms-entryalertsemails-input" placeholder="' . esc_attr($placeholder) . '" value="' . esc_attr($email) . '">';
        echo '</div>';
        echo '<div class="col-md-3">';
        echo '<button type="button" class="button small btn-sm gf-entryalert-select-message me-2" data-alert-row-id="' . esc_attr($row_id) . '">' . esc_html($button_label) . '</button>';
        echo '<button type="button" class="button small btn-sm gf-entryalert-remove-message" data-alert-row-id="' . esc_attr($row_id) . '"' . $show_remove . '>' . esc_html($remove_label) . '</button>';
        echo '</div>';
        echo '<div class="col-md-4">';
        echo '<div class="gf-entryalert-message-preview">';
        echo '<span class="gf-entryalert-message-name">' . esc_html($message_name) . '</span>';
        if (!empty($message_heading)) {
            echo '<br><span class="text-muted small gf-entryalert-message-heading">' . esc_html($message_heading) . '</span>';
        } else {
            echo '<br><span class="text-muted small gf-entryalert-message-heading"></span>';
        }
        echo '</div>';
        echo '</div>';
        echo '<div class="col-md-1 text-end">';
        echo '<button type="button" class="gf-entryalert-remove-row btn btn-sm btn-dark">';
        $this->mIcon('delete');
        echo '</button>';
        echo '</div>';
        echo '<input type="hidden" class="gf-entryalert-message-id" value="' . esc_attr($message_id) . '">';
        echo '</div>';
    }

    public function fieldJs()
    {
        $select_label = $this->lang->getText('select_message_label');
        $change_label = $this->lang->getText('change_message_label');
        $remove_label = $this->lang->getText('remove_message_label');
        $default_label = $this->lang->getText('default_message_label');
        $placeholder = $this->lang->getText('admin_email_placeholder');

        $row_template = '<div class="gf-entryalert-row row align-items-center mb-2" data-alert-row-id="__ROW_ID__">' .
            '<div class="col-md-3">' .
            '<input type="email" class="form-control griffinforms-entryalertsemails-input" placeholder="' . esc_attr($placeholder) . '" value="">' .
            '</div>' .
            '<div class="col-md-3">' .
            '<button type="button" class="button small btn-sm gf-entryalert-select-message me-2" data-alert-row-id="__ROW_ID__">' . esc_html($select_label) . '</button>' .
            '<button type="button" class="button small btn-sm gf-entryalert-remove-message" data-alert-row-id="__ROW_ID__" style="display: none;">' . esc_html($remove_label) . '</button>' .
            '</div>' .
            '<div class="col-md-4">' .
            '<div class="gf-entryalert-message-preview">' .
            '<span class="gf-entryalert-message-name">' . esc_html($default_label) . '</span>' .
            '<br><span class="text-muted small gf-entryalert-message-heading"></span>' .
            '</div>' .
            '</div>' .
            '<div class="col-md-1 text-end">' .
            '<button type="button" class="gf-entryalert-remove-row btn btn-sm btn-dark">' . wp_kses_post($this->mIcon('delete', 'rounded', 'return')) . '</button>' .
            '</div>' .
            '<input type="hidden" class="gf-entryalert-message-id" value="0">' .
            '</div>';

        $js = '
        jQuery(document).ready(function($) {
            var container = $("#griffinforms-entryalertsemails-container");
            var addBtn = $("#griffinforms-entryalertsemails-add");
            var rowTemplate = ' . json_encode($row_template) . ';
            var selectLabel = ' . json_encode($select_label) . ';
            var changeLabel = ' . json_encode($change_label) . ';
            var defaultLabel = ' . json_encode($default_label) . ';
            function truncateText(text, maxLength) {
                if (!text) { return ""; }
                return text.length > maxLength ? text.substring(0, maxLength - 3) + "..." : text;
            }
            var maxEmails = parseInt(container.attr("data-max-emails"), 10) || 5;

            var selectModal = $("#griffinforms-selectmessage-modal");
            if (selectModal.length) {
                selectModal.appendTo("body");
            }
            var createModal = $("#griffinforms-createmessage-modal");
            if (createModal.length) {
                createModal.appendTo("body");
            }

            function nextRowId() {
                var current = parseInt(container.attr("data-next-row-id"), 10) || 1;
                container.attr("data-next-row-id", current + 1);
                return current;
            }

            function ensureAtLeastOneRow() {
                if (container.find(".gf-entryalert-row").length === 0) {
                    addRow();
                }
            }

            function updateRemoveRowVisibility() {
                var rows = container.find(".gf-entryalert-row");
                if (rows.length <= 1) {
                    rows.find(".gf-entryalert-remove-row").hide();
                } else {
                    rows.find(".gf-entryalert-remove-row").show();
                }

                if (rows.length >= maxEmails) {
                    addBtn.hide();
                } else {
                    addBtn.show();
                }
            }

            function addRow() {
                var rowId = nextRowId();
                var html = rowTemplate.replace(/__ROW_ID__/g, rowId);
                container.append(html);
                updateRemoveRowVisibility();
            }

            function resetMessageSelection(row) {
                row.find(".gf-entryalert-message-id").val("0");
                row.find(".gf-entryalert-message-name").text(defaultLabel);
                row.find(".gf-entryalert-message-heading").text("");
                row.find(".gf-entryalert-select-message").text(selectLabel);
                row.find(".gf-entryalert-remove-message").hide();
            }

            addBtn.on("click", function() {
                if (container.find(".gf-entryalert-row").length >= maxEmails) {
                    return;
                }
                addRow();
            });

            container.on("click", ".gf-entryalert-remove-row", function() {
                $(this).closest(".gf-entryalert-row").remove();
                ensureAtLeastOneRow();
                updateRemoveRowVisibility();
            });

            container.on("click", ".gf-entryalert-remove-message", function() {
                var row = $(this).closest(".gf-entryalert-row");
                resetMessageSelection(row);
            });

            container.on("click", ".gf-entryalert-select-message", function() {
                var row = $(this).closest(".gf-entryalert-row");
                var rowId = row.attr("data-alert-row-id");
                var modal = $("#griffinforms-selectmessage-modal");
                modal.data("gf-trigger", "map_alert_email_message");
                modal.data("gf-alert-row-id", rowId);
                modal.modal("show");
            });

            window.griffinformsSaveAlertEmailMapping = function(rowId, itemId, itemName, itemHeading) {
                var row = container.find(".gf-entryalert-row[data-alert-row-id=\'" + rowId + "\']");
                if (!row.length) { return; }
                row.find(".gf-entryalert-message-id").val(itemId);
                row.find(".gf-entryalert-message-name").text(truncateText(itemName || defaultLabel, 30));
                row.find(".gf-entryalert-message-heading").text(truncateText(itemHeading || "", 38));
                row.find(".gf-entryalert-select-message").text(changeLabel);
                row.find(".gf-entryalert-remove-message").show();
            };

            updateRemoveRowVisibility();
        });';

        wp_add_inline_script('griffinforms-global-js', $js);
    }
}
