<?php

namespace GriffinForms\Admin\App\Html\Modals\FormNotifications;

use GriffinForms\Includes\Notifications\NotificationChannelRegistry;
use GriffinForms\Includes\Notifications\NotificationEventRegistry;

trait Responses
{

    public function saveFormNotifications(\WP_REST_Request $request): \WP_REST_Response|\WP_Error
    {
        $form_id = absint($request->get_param('form_id'));

        $sql = \GriffinForms\Admin\Sql\App::getInstance();
        if (!$sql->itemExists('form', $form_id)) {
            return new \WP_Error('not_found', __('Form not found.', 'griffinforms-form-builder'), ['status' => 404]);
        }

        $raw_data = $request->get_param('item_data');
        $data     = json_decode($raw_data, true);

        if (!is_array($data)) {
            return new \WP_Error('invalid_data', __('Invalid item data.', 'griffinforms-form-builder'), ['status' => 400]);
        }

        $channel_registry = NotificationChannelRegistry::getInstance();
        $event_registry   = NotificationEventRegistry::getInstance();
        $secured          = [];

        foreach ($event_registry->getAll() as $event) {
            $event_id   = $event->getEventId();
            $sub_events = $event->getSubEvents();
            $secured[$event_id] = [];

            foreach (array_keys($sub_events) as $sub_event_id) {
                $raw_actions = $data[$event_id][$sub_event_id] ?? [];
                if (!is_array($raw_actions)) {
                    $secured[$event_id][$sub_event_id] = [];
                    continue;
                }

                $secured_actions = [];
                $order           = 1;

                foreach ($raw_actions as $raw_action) {
                    if (!is_array($raw_action)) {
                        continue;
                    }

                    $channel_id = sanitize_key($raw_action['channel'] ?? '');
                    $channel    = $channel_registry->get($channel_id);

                    if (!$channel) {
                        continue; // Skip unknown or unregistered (inactive) channels.
                    }

                    $message_id = absint($raw_action['message_id'] ?? 0);
                    $enabled    = !empty($raw_action['enabled']);
                    $id         = sanitize_text_field($raw_action['id'] ?? wp_generate_uuid4());

                    $raw_recipients = isset($raw_action['recipients']) && is_array($raw_action['recipients'])
                        ? $raw_action['recipients']
                        : [];

                    $secured_actions[] = [
                        'id'         => $id,
                        'order'      => $order++,
                        'enabled'    => $enabled,
                        'channel'    => $channel_id,
                        'message_id' => $message_id,
                        'recipients' => $channel->secureRecipients($raw_recipients),
                    ];
                }

                $secured[$event_id][$sub_event_id] = $secured_actions;
            }
        }

        $form_sql = \GriffinForms\Admin\Sql\Form::getInstance();
        $where    = ['id' => $form_id];

        $saved = $form_sql->updateData(['notifications' => wp_json_encode($secured)], $where);

        if ($saved === false) {
            return new \WP_Error('save_failed', __('Failed to save form notifications.', 'griffinforms-form-builder'), ['status' => 500]);
        }

        $form_sql->updateData([
            'last_editor' => get_current_user_id(),
            'last_edited' => current_time('mysql', true),
        ], $where);

        return new \WP_REST_Response(['success' => true, 'data' => [], 'meta' => []], 200);
    }

    public function getNotificationsHtml(): void
    {
        check_ajax_referer('wp_rest', 'nonce');

        $form_id = absint($_POST['form_id'] ?? 0);
        $sql = \GriffinForms\Admin\Sql\App::getInstance();
        if ($form_id <= 0 || !$sql->itemExists('form', $form_id)) {
            wp_send_json_error(['message' => __('Form not found.', 'griffinforms-form-builder')]);
            wp_die();
        }

        \GriffinForms\Admin\App\Utility::getInstance()->setFormContext($form_id);

        $html = \GriffinForms\Admin\App\Html\Modals\FormNotifications::getInstance()->getBodyHtml();

        wp_send_json_success(['html' => $html]);
        wp_die();
    }
}
