<?php

namespace GriffinForms\Admin\Ajax;

class Form extends \GriffinForms\Admin\Ajax\Format
{   
    public function sendItemsToModal()
    {
        // Check required data using checkPostData
        $this->checkPostData(['nonce', 'name', 'item_type']);
        $this->checkPostData('offset', 0);

        // Nonce check
        $nonce_status = wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'items_data');
        if ($nonce_status != false) {
            $name = $this->secure->data('name', sanitize_text_field(wp_unslash($_POST['name'])));
            $item_type = $this->secure->data('item_type', sanitize_text_field(wp_unslash($_POST['item_type'])));
            $offset = absint(wp_unslash($_POST['offset']));

            $items = $this->sql->getItemsForModal($item_type, 10, $offset);

            $items_html_class = new \GriffinForms\Admin\Html\Elements\ModalItemsList($items, $item_type, $name);
            $items_html_class->html();

            wp_die();
        } else {
            echo 'nonce_error';
            wp_die();
        }

        wp_die();
    }
    
    public function sendItemCount()
    {

        $this->checkNonce('item_count');
        $this->checkPostData('item_type');

        $data = $this->secure->secureData(wp_unslash($_POST), false);
        $data['item_type'] = sanitize_text_field($data['item_type']);
        $count = $this->sql->getItemCount($data['item_type']);
        echo absint($count);
        wp_die();
    }
    
    public function sendFoundItems()
    {
        // Check required data using checkPostData
        $this->checkPostData('nonce', 0);
        $this->checkPostData('name');
        $this->checkPostData('item_type');
        $this->checkPostData('search_value', '');

        // Nonce check
        $nonce_status = wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'item_search');
        if ($nonce_status != false) {
            $name = $this->secure->data('name', sanitize_text_field(wp_unslash($_POST['name'])));
            $item_type = $this->secure->data('item_type', sanitize_text_field(wp_unslash($_POST['item_type'])));
            $search_value = sanitize_text_field(wp_unslash($_POST['search_value']));

            $items = $this->sql->getSearchedItems($item_type, $search_value);

            $items_html = new \GriffinForms\Admin\Html\Elements\ModalItemsList($items, $item_type, $name, $search_value);
            $items_html->html();

            wp_die();
        } else {
            echo 'nonce_error';
        }

        wp_die();
    }

    public function checkEmailField()
    {
        $this->checkNonce('check_email_field');
        $this->checkPostData('form_id', 0);

        $form_id = absint((wp_unslash($_POST['form_id'])));

        if (!$this->sql->itemExists('form', $form_id)) {
            return $this->returnError(__('Form not found.', 'griffinforms-form-builder'));
        }

        $fields = $this->sql->fieldsInForm($form_id);
        if (!is_array($fields)) {
            return $this->returnError(__('Unable to fetch form fields.', 'griffinforms-form-builder'));
        }

        $email_fields = [];

        foreach ($fields as $field) {
            if (!empty($field->field_type) && $field->field_type === 'inputemail' && !empty($field->id)) {
                $email_fields[] = [
                    'id'          => $field->id,
                    'name'        => $field->name ?? '',
                    'heading'     => $field->heading ?? '',
                    'description' => $field->description ?? '',
                ];
            }
        }

        return $this->returnSuccess(['email_fields' => $email_fields]);
    }

    public function checkFormFields()
    {
        $this->checkNonce('check_form_fields');
        $this->checkPostData('form_id', 0);

        $form_id    = absint(wp_unslash($_POST['form_id']));
        $field_type = sanitize_key(wp_unslash($_POST['field_type'] ?? ''));

        $allowed_types = ['inputemail', 'inputphone', 'inputtext', 'inputnumber'];
        if (!in_array($field_type, $allowed_types, true)) {
            return $this->returnError(__('Invalid field type.', 'griffinforms-form-builder'));
        }

        if (!$this->sql->itemExists('form', $form_id)) {
            return $this->returnError(__('Form not found.', 'griffinforms-form-builder'));
        }

        $fields       = $this->sql->fieldsInForm($form_id);
        $found_fields = [];

        if (is_array($fields)) {
            foreach ($fields as $field) {
                if (!empty($field->field_type) && $field->field_type === $field_type && !empty($field->id)) {
                    $found_fields[] = [
                        'id'          => $field->id,
                        'name'        => $field->name ?? '',
                        'heading'     => $field->heading ?? '',
                        'description' => $field->description ?? '',
                    ];
                }
            }
        }

        return $this->returnSuccess(['fields' => $found_fields]);
    }

    public function getFormFields()
    {
        check_ajax_referer('get_form_fields', 'nonce');
        $this->checkPostData('form_id', 0);

        $form_id = absint(wp_unslash($_POST['form_id']));
        if (!$form_id || !$this->sql->itemExists('form', $form_id)) {
            return $this->returnError(__('Form not found.', 'griffinforms-form-builder'));
        }

        $fields = $this->sql->fieldsInForm($form_id);
        if (!is_array($fields)) {
            return $this->returnError(__('Unable to fetch form fields.', 'griffinforms-form-builder'));
        }

        $output = [];
        foreach ($fields as $field) {
            if (empty($field->id)) {
                continue;
            }
            $output[] = [
                'id'          => (int) $field->id,
                'name'        => isset($field->name) ? (string) $field->name : '',
                'heading'     => isset($field->heading) ? (string) $field->heading : '',
                'field_type'  => isset($field->field_type) ? (string) $field->field_type : '',
                'description' => isset($field->description) ? (string) $field->description : '',
            ];
        }

        return $this->returnSuccess(['fields' => $output]);
    }

    /**
     * Handles AJAX request for fetching the number of rules for a given form.
     */
    public function getRulesCount()
    {
        check_ajax_referer('update_rules_badge_count', 'nonce');
        $form_id = isset($_POST['form_id']) ? absint(wp_unslash($_POST['form_id'])) : 0;
        
        if (!$form_id) {
            wp_send_json_error(['message' => __('Invalid form ID.', 'griffinforms')]);
        }

        $form = new \GriffinForms\Items\Form();
        $form->loadItem($form_id);
        $count = method_exists($form, 'getRulesCount') ? (int) $form->getRulesCount() : 0;

        wp_send_json_success(['count' => $count]);
    }

    public function __construct()
    {
        $this->setAll();
        add_action('wp_ajax_sendItemsToModal', array($this, 'sendItemsToModal'));
        add_action('wp_ajax_sendItemCount', array($this, 'sendItemCount'));
        add_action('wp_ajax_sendFoundItems', array($this, 'sendFoundItems'));
        add_action('wp_ajax_checkEmailField', array($this, 'checkEmailField'));
        add_action('wp_ajax_checkFormFields', [$this, 'checkFormFields']);
        add_action('wp_ajax_griffinformsGetRulesCount', [$this, 'getRulesCount']);
        add_action('wp_ajax_griffinforms_get_form_fields', [$this, 'getFormFields']);
    }
}
