<?php
/**
 * Customizer Sanitize functions.
 *
 * @package Azure News
 */

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

if ( ! function_exists( 'azure_news_sanitize_title' ) ) :

    /**
     * Sanitize textarea value.
     *
     * @param string $input     The string prior to being sanitized.
     * @return string           Sanitize string with wp_kses_post.
     *
     * @since 1.0.0
     *
     */
    function azure_news_sanitize_title( $input ) {

        $input = wp_kses_post( $input );

        return $input;

    }

endif;

if ( ! function_exists( 'azure_news_sanitize_textarea' ) ) :

    /**
     * Sanitize textarea value.
     *
     * @param string $input     The string prior to being sanitized.
     * @return string           Sanitize string with wp_kses_post.
     *
     * @since 1.0.0
     *
     */
    function azure_news_sanitize_textarea( $input ) {

        $input = wp_kses_post( $input );

        return $input;

    }

endif;

if ( ! function_exists( 'azure_news_sanitize_checkbox' ) ) :

    /**
     * Sanitize checkbox.
     *
     * @param bool $checked Whether the checkbox is checked.
     * @return bool Whether the checkbox is checked.
     *
     * @since 1.0.0
     */
    function azure_news_sanitize_checkbox( $checked ) {

        return ( ( isset( $checked ) && true === $checked ) ? true : false );

    }

endif;

if ( ! function_exists( 'azure_news_sanitize_select' ) ) :
    
    /**
     * Sanitize select.
     *
     * @param mixed                $input The value to sanitize.
     * @param WP_Customize_Setting $setting WP_Customize_Setting instance.
     * @return mixed Sanitized value.
     *
     * @since 1.0.0
     */
    function azure_news_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;

if ( ! function_exists( 'azure_news_sanitize_number' ) ) :

    /**
     * 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 azure_news_sanitize_number( $input ) {

        return is_numeric( $input ) ? $input : 0;

    }

endif;

if ( ! function_exists( 'azure_news_sanitize_image' ) ) :

    /**
     * Sanitize image control value.
     *
     * Validates that the provided URL points to an allowed image file type
     * and that the attachment exists in the WordPress media library.
     *
     * @since 1.0.0
     * @since 1.1.0 Added media library validation, WebP/AVIF support, and improved security.
     *
     * @param string               $image   Image URL.
     * @param WP_Customize_Setting $setting Setting instance.
     * @return string Sanitized image URL or default setting value.
     */
    function azure_news_sanitize_image( $image, $setting ) {

        // Return default immediately if no image URL is provided.
        if ( empty( $image ) ) {
            return $setting->default;
        }

        /*
         * Allowed image mime types.
         * Mirrors wp_get_mime_types() image entries and adds modern formats.
         */
        $mimes = array(
            'jpg|jpeg|jpe' => 'image/jpeg',
            'gif'          => 'image/gif',
            'png'          => 'image/png',
            'bmp'          => 'image/bmp',
            'tif|tiff'     => 'image/tiff',
            'ico'          => 'image/x-icon',
            'webp'         => 'image/webp',
            'avif'         => 'image/avif',
            'svg'          => 'image/svg+xml',
        );

        /**
         * Filters the allowed mime types for image sanitization.
         *
         * @since 1.1.0
         *
         * @param array $mimes Allowed mime types keyed by file extension regex.
         */
        $mimes = apply_filters( 'azure_news_sanitize_image_mimes', $mimes );

        // Sanitize the raw URL before any processing.
        $image = esc_url_raw( trim( $image ) );

        if ( empty( $image ) ) {
            return $setting->default;
        }

        // Validate file extension and mime type.
        $file = wp_check_filetype( $image, $mimes );

        if ( empty( $file['ext'] ) || empty( $file['mime'] ) ) {
            return $setting->default;
        }

        /*
         * Verify the image belongs to this site's media library.
         * This prevents referencing external or unauthorized image URLs.
         */
        $attachment_id = attachment_url_to_postid( $image );

        if ( 0 === $attachment_id ) {

            /*
             * Fallback: allow the URL only if it's hosted on the same domain.
             * Useful for images outside the media library (e.g. theme bundled assets).
             */
            $upload_dir = wp_get_upload_dir();
            $site_url   = trailingslashit( get_site_url() );

            $is_local_upload = isset( $upload_dir['baseurl'] ) && str_starts_with( $image, $upload_dir['baseurl'] );

            $is_site_asset   = str_starts_with( $image, $site_url );

            if ( ! $is_local_upload && ! $is_site_asset ) {
                return $setting->default;
            }

        }

        return $image;
        
    }

endif;

if ( ! function_exists( 'azure_news_sanitize_repeater' ) ) :

    /**
     * Sanitize repeater value
     *
     * @param  json $input Customizer setting input repeater json.
     * @param  object       $setting Setting Object.
     * @return array        Return array.
     *
     * @since 1.0.0
     */
    function azure_news_sanitize_repeater( $input, $setting ) {
        $input_decoded = json_decode( $input, true );
            
        if ( !empty( $input_decoded ) ) {
            foreach ( $input_decoded as $boxes => $box ) {
                foreach ( $box as $key => $value ) {
                    if ( $key == 'url' ) {
                        $input_decoded[$boxes][$key] = esc_url_raw( $value );
                    } else {
                        $input_decoded[$boxes][$key] = wp_kses_post( $value );
                    }
                }
            }
            return json_encode( $input_decoded );
        }
        
        return $input;
    }

endif;

if ( ! function_exists( 'azure_news_sanitize_sortable' ) ) {

    /**
     * Sanitize the sortable value set within customizer controls.
     *
     * @param number $input   Customizer setting input sortable arguments.
     * @param object $setting Setting object.
     *
     * @return mixed
     * @since 1.0.0
     */
    function azure_news_sanitize_sortable( $input, $setting ) {

        // Get list of choices from the control associated with the setting.
        $choices    = $setting->manager->get_control( $setting->id )->choices;
        $input_keys = $input;

        foreach ( (array) $input_keys as $key => $value ) {
            if ( ! array_key_exists( $value, $choices ) ) {
                unset( $input[ $key ] );
            }
        }

        // If the input is a valid key, return it, otherwise, return the default.
        return ( is_array( $input ) ? $input : $setting->default );

    }
    
}