<?php

namespace GriffinForms\Frontend\Ajax;

use GriffinForms\Frontend\Security\FormValidations\AccountRegistration;

class Validations
{       
    /**
     * AJAX handler to validate if a given value exists in a specified database table and column.
     *
     * Expects the following POST parameters:
     * - nonce  : Security nonce for validation.
     * - value  : The value to check in the database.
     * - table  : The database table name.
     * - column : The database column name.
     *
     * Returns a JSON response with the count of matching records.
     */
    public function dbValidate()
    {
        // Check if nonce is set
        if (isset($_POST['nonce'])) {
            // Verify the nonce
            $nonce_status = wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'db_validate');
            if ($nonce_status !== false) {
    
                // Check if required POST variables are set
                if (isset($_POST['value'], $_POST['table'], $_POST['column'])) {
                    // Sanitize input data
                    $value = sanitize_text_field(wp_unslash($_POST['value']));
                    $table = sanitize_text_field(wp_unslash($_POST['table']));
                    $column = sanitize_text_field(wp_unslash($_POST['column']));
                    
                    global $wpdb;
    
                    // Ensure the table and column names are safe
                    $table = esc_sql($table);
                    $column = esc_sql($column);
    
                    $result = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM %i WHERE %i = %s", $table, $column, $value));
    
                    // Return the result as JSON
                    echo wp_json_encode(["count" => $result]);
                    wp_die();
    
                } else {
                    esc_html_e('Missing required fields', 'griffinforms-form-builder');
                    wp_die();
                }
    
            } else {
                esc_html_e('Nonce verification failed', 'griffinforms-form-builder');
                wp_die();
            }
    
        } else {
            esc_html_e('Nonce not provided', 'griffinforms-form-builder');
            wp_die();
        }
    }

    public function validateAccountRegistrationEmail()
    {
        if (!isset($_POST['nonce'])) {
            wp_send_json(['valid' => false, 'message' => __('Nonce not provided.', 'griffinforms-form-builder')]);
        }

        $nonce_status = wp_verify_nonce(
            sanitize_text_field(wp_unslash($_POST['nonce'])),
            'validate_account_registration_email'
        );

        if ($nonce_status === false) {
            wp_send_json(['valid' => false, 'message' => __('Nonce verification failed.', 'griffinforms-form-builder')]);
        }

        $form_id = absint($_POST['form_id'] ?? 0);
        $field_id = absint($_POST['field_id'] ?? 0);
        $value = sanitize_text_field(wp_unslash($_POST['value'] ?? ''));
        $iteration_index = isset($_POST['iteration_index']) ? absint($_POST['iteration_index']) : null;

        if ($form_id <= 0 || $field_id <= 0) {
            wp_send_json([
                'valid' => true,
                'message' => '',
                'code' => '',
            ]);
        }

        $validator = new AccountRegistration();
        $result = $validator->validateSingleFieldValue($form_id, $field_id, $value, $iteration_index);
        wp_send_json($result);
    }
    
    public function __construct()
    {
        add_action('wp_ajax_nopriv_dbValidate', array($this, 'dbValidate'));
        add_action('wp_ajax_dbValidate', array($this, 'dbValidate'));
        add_action('wp_ajax_nopriv_validateAccountRegistrationEmail', array($this, 'validateAccountRegistrationEmail'));
        add_action('wp_ajax_validateAccountRegistrationEmail', array($this, 'validateAccountRegistrationEmail'));
    }
}
