<?php
/**
 * File for sanitizing customizer fields.
 * 
 * Contains functions to ensure that Customizer field inputs are safe and valid.
 *
 * @package Yaatra
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

if ( ! function_exists( 'yaatra_sanitize_checkbox' ) ) :

    /**
     * Sanitize checkbox value.
     * 
     * @since 1.0.0
     * 
     * @param mixed $checked Value to sanitize.
     * @return bool
     */
    function yaatra_sanitize_checkbox( $checked ) {
        return ( ( isset( $checked ) && true === $checked ) ? true : false );
    }

endif;

if ( ! function_exists( 'yaatra_sanitize_repeater' ) ) :

    /**
     * Sanitize repeater field value.
     *
     * @since 1.0.0
     * @param string                $input   Repeater JSON value.
     * @param WP_Customize_Setting  $setting Customizer setting.
     * @return string
     */
    function yaatra_sanitize_repeater( $input, $setting ) {
        $input_decoded = json_decode( $input, true );

        if ( ! is_array( $input_decoded ) ) {
            return $setting->default;
        }   
        
        foreach ( $input_decoded as $index => $item ) {

            if ( ! is_array( $item ) ) {
                continue;
            }

            foreach ( $item as $key => $value ) {
                if ( 'cv_url_field' === $key ) {
                    $input_decoded[$index][$key] = esc_url_raw( $value );
                } else {
                    $input_decoded[$index][$key] = wp_kses_post( $value );
                }
            }
        }
        return json_encode( $input_decoded );
    }

endif;

if ( ! function_exists( 'yaatra_sanitize_select' ) ) :

    /**
     * Sanitize select field.
     *
     * @since 1.0.0
     *
     * @param string                $input   Selected value.
     * @param WP_Customize_Setting  $setting Customizer setting instance.
     * @return string Sanitized value.
     */
    function yaatra_sanitize_select( $input, $setting ) {
        $input = sanitize_key( $input );
        $control = $setting->manager->get_control( $setting->id );

        if ( ! $control || empty( $control->choices ) ) {
            return $setting->default;
        }

        return array_key_exists( $input, $control->choices ) ? $input : $setting->default;
    }

endif;