<?php
namespace KaliForms\Inc\Backend;

if (!defined('ABSPATH')) {
    exit;
}

class Sanitizers_Helper
{
    /**
     * Sanitize the conditional logic
     *
     * @param [type] $input
     * @return void
     */
    public static function sanitize_conditional_logic($input)
    {
        $input = json_decode(stripslashes($input));
        if ($input === null) {
            return;
        }

        $sanitized = [];
        foreach ($input as $item) {
            $item = self::_sanitize_conditional_item($item);
            $sanitized[] = $item;
        }

        return wp_slash(wp_json_encode($sanitized, JSON_HEX_QUOT));
    }

	/**
	 * Sanitizes a conditional thank you message
	 *
	 * @param [type] $input
	 * @return void
	 */
    public static function sanitize_conditional_thank_you($input)
    {
        $input = json_decode(stripslashes($input));
        if ($input === null) {
            return;
        }

        $sanitized = [];
        foreach ($input as $item) {
            $item = self::_sanitize_conditional_ty_item($item);
            $sanitized[] = $item;
        }

        return wp_slash(wp_json_encode($sanitized, JSON_HEX_QUOT));
    }
    /**
     * Sanitize a single ty item
     *
     * @param [type] $item
     * @return void
     */
    public static function _sanitize_conditional_ty_item($item)
    {
        $props = new \stdClass();

        $props->message = wp_kses_post($item->message);
        $props->name = sanitize_text_field($item->name);
        $props->condition = new \stdClass();

        foreach ($item->condition as $condition => $value) {
            $props->condition->{$condition} = sanitize_text_field($value);
        }

        return $props;
    }

    /**
     * Sanitize a single conditional item
     *
     * @param [type] $item
     * @return void
     */
    public static function _sanitize_conditional_item($item)
    {
        $props = new \stdClass();

        $props->field = sanitize_text_field($item->field);
        $props->conditioner = sanitize_text_field($item->conditioner);
        $props->operator = in_array($item->operator, ['or', 'equal', 'different']) ? $item->operator : 'equal';
        $props->state = in_array($item->state, ['show', 'hide']) ? $item->state : 'equal';
        $props->value = sanitize_text_field($item->value);
        $props->name = !empty($item->name) ? sanitize_text_field($item->name) : '';

        return $props;
    }
    /**
     * Save code to database
     *
     * @param [type] $input
     * @return void
     */
    public static function sanitize_code($input)
    {
        return $input;
    }
    /**
     * Sanitize php code to database
     *
     * @param [type] $input
     * @return void
     */
    public static function sanitize_code_php($input)
    {
        $input = str_replace('<?php', '', $input);
        $input = str_replace('?>', '', $input);
        return $input;
    }
}
