<?php

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

trait Responses
{
    public function saveFormOptions(\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]);
        }

        $secure = \GriffinForms\Admin\Secure\Form::getInstance();
        $secured = $secure->secureData($data);

        if (empty($secured)) {
            return new \WP_Error('no_data', __('No recognised fields to save.', 'griffinforms-form-builder'), ['status' => 400]);
        }

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

        $saved = $form_sql->updateData($secured, $where);

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

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

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

    public function getFormOptionsHtml(): 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\FormOptions::getInstance()->getBodyHtml();

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