<?php

defined( 'ABSPATH' ) || exit;
/**
 * Gets a setting from the plugin's settings array.
 *
 * @param string $key Setting key.
 * @param string $default Default value if setting does not exist.
 *
 * @return string
 * @since 1.0.0
 */
function smp_get_setting(  $key, $default = ''  ) {
    $settings = smp_get_settings();
    if ( isset( $settings[$key] ) ) {
        return $settings[$key];
    }
    return $default;
}

/**
 * Retrieves the multimedia player settings.
 *
 * This function merges the default settings with any saved settings and returns
 * the resulting settings array. If no settings are saved, the default settings
 * will be returned.
 *
 * @return array The array of multimedia player settings.
 */
function smp_get_settings() {
    $default_settings = [
        'volume'                => 80,
        'customPopupSize'       => false,
        'popupWidth'            => 420,
        'popupHeight'           => 330,
        'enableStats'           => false,
        'ads_report_recipients' => get_bloginfo( 'admin_email' ),
    ];
    $saved_settings = get_option( 'smp_settings', [] );
    $settings = array_merge( $default_settings, $saved_settings );
    return ( !empty( $settings ) ? $settings : $default_settings );
}

/**
 * Retrieves the number of times a multimedia player has been played.
 *
 * This function will soon be deprecated in favor of a more robust analytics
 * system. It is currently only used to provide a play count for the player in
 * the WordPress admin area.
 *
 * @param int $post_id The ID of the post containing the multimedia player.
 *
 * @return int The number of times the multimedia player has been played.
 */
function smp_get_play_count(  $post_id  ) {
    //	global $wpdb;
    //
    //	$sql   = $wpdb->prepare("SELECT SUM(`count`)  FROM {$wpdb->prefix}multimedia_player_statistics WHERE player_id = %d;", $post_id);
    //	$count = $wpdb->get_var($sql);
    //
    //	return intval($count);
    return 0;
}

function smp_get_players(  $id = false  ) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'smp_players';
    if ( $id ) {
        $player = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table_name} WHERE id = %d", $id ), ARRAY_A );
        return smp_get_formatted_player( $player );
    }
    $players = $wpdb->get_results( "SELECT * FROM {$table_name}", ARRAY_A );
    $formatted_players = [];
    if ( !empty( $players ) ) {
        foreach ( $players as $player ) {
            $formatted_players[] = smp_get_formatted_player( $player );
        }
    }
    if ( $id === 0 ) {
        return $formatted_players[0];
    }
    return $formatted_players;
}

function smp_get_formatted_player(  $player  ) {
    if ( empty( $player ) ) {
        return [];
    }
    $player['id'] = intval( $player['id'] );
    $player['status'] = filter_var( $player['status'], FILTER_VALIDATE_BOOLEAN );
    $player['config'] = maybe_unserialize( $player['config'] );
    $player['locations'] = ( !empty( $player['locations'] ) ? array_values( maybe_unserialize( $player['locations'] ) ) : [] );
    return $player;
}

function smp_get_exclude_list() {
    $current_screen = get_current_screen();
    if ( $current_screen->base !== 'multimedia-player_page_soft-multimedia-player-settings' ) {
        return;
    }
    $front_page_id = null;
    if ( get_option( 'show_on_front' ) === 'page' ) {
        $front_page_id = get_option( 'page_on_front' );
    }
    $general_options = [];
    if ( empty( $front_page_id ) ) {
        $general_options['home'] = 'Homepage';
    }
    $general_options['search'] = 'Search page';
    $general_options['tag'] = 'Tag page';
    $general_options['category'] = 'Category page';
    $general_options['archive'] = 'Archive page';
    $general_options['author'] = 'Author page';
    $general_options['404'] = '404 error page';
    $general_options['login'] = 'Login page';
    $list = [
        'general' => [
            'label'   => 'General',
            'options' => $general_options,
        ],
    ];
    // get only visible post types
    $visible_post_types = get_post_types( array(
        "public" => true,
    ) );
    // Each post types
    foreach ( $visible_post_types as $post_type ) {
        $query = new WP_Query(array(
            'post_type'      => $post_type,
            'posts_per_page' => 999,
        ));
        if ( $query->have_posts() ) {
            $list[$post_type] = [
                'label' => ucfirst( $post_type ),
            ];
            $post_type_options = [];
            while ( $query->have_posts() ) {
                $query->the_post();
                $post_type_options[get_the_ID()] = get_the_title();
            }
            $list[$post_type]['options'] = $post_type_options;
        }
    }
    return $list;
}

/**
 * Sanitizes an array recursively.
 *
 * The function goes through each value in the array. If the value is an array, the function
 * calls itself with the array as the argument. If the value is a boolean string, it is
 * converted to a boolean value. If the value is a numeric string, it is converted to a
 * number, either an integer or a float. Otherwise, the value is sanitized with wp_kses_post.
 *
 * @param array $array The array to sanitize.
 *
 * @return array The sanitized array.
 */
function smp_sanitize_array(  $array  ) {
    foreach ( $array as $key => &$value ) {
        if ( is_array( $value ) ) {
            $value = smp_sanitize_array( $value );
        } else {
            if ( in_array( $value, ['true', 'false'] ) ) {
                $value = filter_var( $value, FILTER_VALIDATE_BOOLEAN );
            } elseif ( is_numeric( $value ) ) {
                if ( strpos( $value, '.' ) !== false ) {
                    $value = floatval( $value );
                } elseif ( filter_var( $value, FILTER_VALIDATE_INT ) !== false && $value <= PHP_INT_MAX ) {
                    $value = intval( $value );
                } else {
                    // Keep large integers or non-integer values as string
                    $value = $value;
                }
            } else {
                $value = wp_kses_post( $value );
            }
        }
    }
    return $array;
}

function smp_get_player_types(  $type = null  ) {
    $types = [
        'audio-player'   => [
            'key'   => 'audio-player',
            'title' => __( 'Audio Player', 'soft-multimedia-player' ),
            'desc'  => __( 'Play a wide range of audio formats using the audio player.', 'soft-multimedia-player' ),
        ],
        'video-player'   => [
            'key'   => 'video-player',
            'title' => __( 'Video Player', 'soft-multimedia-player' ),
            'desc'  => __( 'Play a wide range of video formats with the video player.', 'soft-multimedia-player' ),
        ],
        'podcast-player' => [
            'key'   => 'podcast-player',
            'title' => __( 'Podcast Player', 'soft-multimedia-player' ),
            'desc'  => __( 'A customizable podcast player type with episode playlist support.', 'soft-multimedia-player' ),
        ],
    ];
    if ( $type ) {
        return ( isset( $types[$type] ) ? $types[$type] : [] );
    }
    return $types;
}

function smp_get_genres() {
    $default = [
        'None',
        'Alternative',
        'Blues',
        'Classical',
        'Country',
        'Electronic',
        'Folk',
        'Funk',
        'Hip-Hop',
        'Indie',
        'Instrumental',
        'Jazz',
        'Latin',
        'Metal',
        'Other',
        'Pop',
        'Punk',
        'Rap',
        'Reggae',
        'Rock',
        'Soul',
        'Soundtrack',
        'World'
    ];
    $created_genres = get_option( 'smp_genres', [] );
    if ( !empty( $created_genres ) && is_array( $created_genres ) ) {
        $default = array_merge( $default, $created_genres );
    }
    return apply_filters( 'smp_genres', $default );
}
