<?php

namespace GriffinForms\Admin\Ajax;

class Format extends \GriffinForms\Admin\Format
{
    protected $meta;
    protected $config;
    protected $secure;
    protected $sql;
    protected $response;

    /**
     * Verifies the nonce for the given action.
     *
     * Logs and returns a standardized JSON error response if nonce verification fails.
     *
     * @param string $action The action name used for nonce generation and verification.
     *
     * @return void Terminates execution on failure.
     */
    protected function checkNonce($action)
    {
        $nonce_status = isset($_POST['nonce']) ? wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), $action) : false;
        
        if ($nonce_status === false) {
            if (isset($this->log)) {
                $this->log->add('error', 'nonce', 0, get_current_user_id(), 'Nonce verification failed for action: ' . $action, 'security');
            }

            $this->response['success'] = false;
            $this->response['msg'] = __('Nonce error', 'griffinforms-form-builder');
            $this->response['time'] = wp_date(get_option('date_format') . ' ' . get_option('time_format'));
            echo wp_json_encode($this->response);
            wp_die();
        }
    }
    

    /**
     * Check if a specific key (or multiple keys) exist in $_POST. 
     * If not, set a default value or return an error response.
     *
     * @param string|array $key The key or list of keys to check in $_POST.
     * @param mixed $default_value The default value to set if the key is not set. Only applies for single key usage.
     */
    protected function checkPostData($key, $default_value = null)
    {
        if (empty($key)) {
            return;
        }

        if (is_array($key)) {
            // Loop over multiple keys
            foreach ($key as $single_key) {
                if (!isset($_POST[$single_key])) {

                    if (isset($this->log)) {
                        $this->log->add('error', 'postdata', 0, get_current_user_id(), 'Missing required post data key: ' . $single_key, 'input');
                    }
                    
                    // translators: %s is the key of the missing POST data
                    $this->returnError(sprintf(__('Missing required data: %s', 'griffinforms-form-builder'), $single_key));
                }
            }
        } else {
            // Single key case (original behavior)
            if (!isset($_POST[$key])) {
                if ($default_value !== null) {
                    $_POST[$key] = $default_value;
                    return;
                }

                if (isset($this->log)) {
                    $this->log->add('error', 'postdata', 0, get_current_user_id(), 'Missing required post data key: ' . $key, 'input');
                }

                // translators: %s is the key of the missing POST data
                $this->returnError(sprintf(__('Missing required data: %s', 'griffinforms-form-builder'), $key));
            }
        }
    }

    /**
     * Return a standardized error response and terminate execution.
     *
     * @param string $msg Error message to return.
     */
    protected function returnError($msg)
    {
        $this->response['success'] = false;
        $this->response['msg'] = $msg;
        $this->response['time'] = wp_date(get_option('date_format') . ' ' . get_option('time_format'));
        echo wp_json_encode($this->response);
        wp_die();
    }
    
    protected function addCreateMeta()
    {
        $meta = array(
            'author' => get_current_user_id(),
            'created' => current_time('mysql', true)
        );
        
        return $meta;
    }    
    
    protected function addUpdateMeta()
    {
        $meta = array(
            'last_editor' => get_current_user_id(),
            'last_edited' => current_time('mysql', true)
        );
        
        return $meta;
    }
    
    protected function setSecure()
    {
        $security_class = '\GriffinForms\Admin\Secure\\' . $this->meta;
        $this->secure = $security_class::getInstance();
    }    
    
    protected function setSql()
    {
        $sql_class = '\GriffinForms\Admin\Sql\\' . $this->meta;
        $this->sql = $sql_class::getInstance();
    }
    /**
     * Return a standardized success response and terminate execution.
     *
     * @param array $data Additional data to return in the response.
     */
    protected function returnSuccess($data = array())
    {
        $response = array_merge(array(
            'success' => true,
            'time'    => wp_date(get_option('date_format') . ' ' . get_option('time_format')),
        ), $data);

        echo wp_json_encode($response);
        wp_die();
    }
}