<?php

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

/**
 * Validate date in dd/mm/yyyy format.
 *
 * @param string $gridpress_date Input date string.
 * @return string Valid date or empty string.
 */
if( ! function_exists( 'gridpress_validate_date_input' ) ) :
	function gridpress_validate_date_input( $gridpress_date ) {

		$gridpress_date = sanitize_text_field( $gridpress_date );
		$gridpress_pattern = '/^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[0-2])\/(19|20)\d\d$/';

		if ( empty( $gridpress_date ) || ! preg_match( $gridpress_pattern, $gridpress_date ) ) {
			return '';
		}

		list( $gridpress_day, $gridpress_month, $gridpress_year ) = explode( '/', $gridpress_date );

		return checkdate( (int) $gridpress_month, (int) $gridpress_day, (int) $gridpress_year )
			? $gridpress_date
			: '';
	}
endif;

/**
 * Convert date string to timestamp.
 *
 * @param string  $gridpress_date Date string.
 * @param boolean $gridpress_add_time Whether to add current time.
 * @return int Timestamp.
 */
if( ! function_exists( 'gridpress_date_strtotime' ) ) :
	function gridpress_date_strtotime( $gridpress_date, $gridpress_add_time = false ) {

		$gridpress_date = str_replace( '/', '-', sanitize_text_field( $gridpress_date ) );

		if ( $gridpress_add_time ) {
			$gridpress_date .= ' ' . current_time( 'H:i:s' );
		}

		return strtotime( $gridpress_date );
	}
endif;

/**
 * Check if user has editor-level permission.
 *
 * @return bool
 */
if( ! function_exists( 'gridpress_user_normal_permission' ) ) :
	function gridpress_user_normal_permission() {
		return current_user_can( 'edit_posts' );
	}
endif;

/**
 * Check if user has admin-level permission.
 *
 * @return bool
 */
if( ! function_exists( 'gridpress_user_admin_permission' ) ) :
	function gridpress_user_admin_permission() {
		return current_user_can( 'manage_options' );
	}
endif;

/**
 * Remove slashes from string safely.
 *
 * @param string $gridpress_content Input string.
 * @return string Unslashed string.
 */
if( ! function_exists( 'gridpress_strip_slashes' ) ) :
	function gridpress_strip_slashes( $gridpress_content = '' ) {
		return ! empty( $gridpress_content ) ? wp_unslash( $gridpress_content ) : '';
	}
endif;

/**
 * Unserialize data safely.
 *
 * @param mixed $gridpress_data Serialized data.
 * @return mixed Unserialized data.
 */
if( ! function_exists( 'gridpress_unserialize_data' ) ) :
	function gridpress_unserialize_data( $gridpress_data ) {
		return maybe_unserialize( $gridpress_data );
	}
endif;

/**
 * Convert title to SEO-friendly slug.
 *
 * @param string $gridpress_title Title string.
 * @return string Slug.
*/
if( ! function_exists( 'gridpress_make_title_slug' ) ) :
	function gridpress_make_title_slug( $gridpress_title ) {
		return sanitize_title( $gridpress_title );
	}
endif;

/**
 * URL encode a string safely.
 *
 * @param string $gridpress_slug Input string.
 * @return string Encoded string.
*/
if( ! function_exists( 'gridpress_get_url_encode_val' ) ) :
	function gridpress_get_url_encode_val( $gridpress_slug ) {
		return strtolower( rawurlencode( sanitize_text_field( $gridpress_slug ) ) );
	}
endif;

/**
 * Get current timestamp.
 *
 * @return int Current timestamp.
 */
if( ! function_exists( 'gridpress_current_time_str' ) ) :
	function gridpress_current_time_str() {
		return (int) current_time( 'U' );
	}
endif;

/**
 * Build upload directory path and URL.
 *
 * @param array $gridpress_dir Upload directory array.
 * @return array Modified directory array.
 */
if( ! function_exists( 'gridpress_public_upload_files_path' ) ) :
	function gridpress_public_upload_files_path( $gridpress_dir ) {

		global $gridpress_upload_files_extpath, $gridpress_upload_subdir_extpath;

		$gridpress_ext_subdir = ! empty( $gridpress_upload_subdir_extpath ) ? '/' . $gridpress_upload_subdir_extpath : '';
		$gridpress_custom_dir = 'wp-gridpress' . ( ! empty( $gridpress_upload_files_extpath ) ? '/' . $gridpress_upload_files_extpath : '' );

		$gridpress_sub_dir = ! empty( $gridpress_dir['subdir'] ) ? $gridpress_dir['subdir'] : '';

		$gridpress_dir['path']   = $gridpress_dir['basedir'] . '/' . $gridpress_custom_dir . $gridpress_sub_dir . $gridpress_ext_subdir;
		$gridpress_dir['url']    = $gridpress_dir['baseurl'] . '/' . $gridpress_custom_dir . $gridpress_sub_dir . $gridpress_ext_subdir;
		$gridpress_dir['subdir'] = $gridpress_sub_dir . $gridpress_ext_subdir;

		return $gridpress_dir;
	}
endif;

/**
 * Safely get query var from URL or WordPress query
 *
 * @since 1.0.0
 * @param string $gridpress_var The query variable name to retrieve
 * @return string Sanitized query variable value
 */
if( ! function_exists( 'gridpress_get_query_var' ) ) :
	function gridpress_get_query_var( $gridpress_var ) {

		$gridpress_value = get_query_var( $gridpress_var );

		if ( empty( $gridpress_value ) && isset( $_GET[ $gridpress_var ] ) ) {

			$gridpress_nonce = isset( $_GET['gridpress_nonce'] )
				? sanitize_text_field( wp_unslash( $_GET['gridpress_nonce'] ) )
				: '';

			if ( wp_verify_nonce( $gridpress_nonce, 'gridpress_front_action' ) ) {

				$gridpress_value = sanitize_text_field(
					wp_unslash( $_GET[ $gridpress_var ] )
				);
			}
		}
		return $gridpress_value;
	}
endif;

/**
 * Register custom query variables.
 *
 * @param array $gridpress_vars Existing query vars.
 * @return array Modified query vars.
 */
if( ! function_exists( 'gridpress_custom_query_vars_list' ) ) :
	function gridpress_custom_query_vars_list( $gridpress_vars ) {

		$gridpress_vars[] = 'tab';
		$gridpress_vars[] = 'section';
		$gridpress_vars[] = 'page';
		$gridpress_vars[] = 'page_num';
		$gridpress_vars[] = 'orderby';
		$gridpress_vars[] = 'order';
		$gridpress_vars[] = 's';
		$gridpress_vars[] = 'id';

		return $gridpress_vars;
	}
	add_filter( 'query_vars', 'gridpress_custom_query_vars_list' );
endif;

/**
 * Convert multiline string into key-value options array.
 *
 * @param string $gridpress_options Input options string.
 * @return array Parsed options array.
 */
if( ! function_exists( 'gridpress_get_split_options_list' ) ) :
	function gridpress_get_split_options_list( $gridpress_options ) {

		$gridpress_final = [];

		if ( empty( $gridpress_options ) ) {
			return $gridpress_final;
		}

		$gridpress_lines = preg_split( '/\r\n|\r|\n/', $gridpress_options );

		foreach ( (array) $gridpress_lines as $gridpress_line ) {

			if ( empty( $gridpress_line ) ) {
				continue;
			}

			$gridpress_parts = array_map( 'trim', explode( '|', $gridpress_line ) );

			if ( isset( $gridpress_parts[1] ) ) {
				$gridpress_final[ $gridpress_parts[1] ] = $gridpress_parts[0];
			} else {
				$gridpress_final[ $gridpress_parts[0] ] = $gridpress_parts[0];
			}
		}

		return $gridpress_final;
	}
endif;

/**
 * Get list of public post types (excluding attachments).
 *
 * @return array Post type list.
 */
if( ! function_exists( 'gridpress_cpt_list' ) ) :
	function gridpress_cpt_list() {

		$gridpress_post_types = get_post_types( [ 'public' => true ], 'objects' );
		$gridpress_list = [];

		foreach ( $gridpress_post_types as $gridpress_post_type ) {

			if ( 'attachment' === $gridpress_post_type->name ) {
				continue;
			}

			$gridpress_list[ $gridpress_post_type->name ] = $gridpress_post_type->label;
		}

		return $gridpress_list;
	}
endif;

/**
 * Load template part from theme or plugin.
 *
 * @param string $gridpress_slug Template slug.
 * @param string $gridpress_name Template name.
 * @param string $gridpress_ext Optional subfolder.
 * @return void
 */
if( ! function_exists( 'gridpress_get_template_part' ) ) :
	function gridpress_get_template_part( $gridpress_slug = '', $gridpress_name = '', $gridpress_ext = '' ) {

		$gridpress_template = '';

		if ( ! empty( $gridpress_ext ) ) {
			$gridpress_ext = trailingslashit( sanitize_text_field( $gridpress_ext ) );
		}

		if ( $gridpress_name ) {
			$gridpress_template = locate_template( [
				"{$gridpress_slug}-{$gridpress_name}.php",
				"gridpress/{$gridpress_ext}{$gridpress_slug}-{$gridpress_name}.php",
			] );
		}

		if ( ! $gridpress_template && $gridpress_name ) {

			$gridpress_fallback = GRIDPRESS_ABSPATH . "templates/{$gridpress_ext}{$gridpress_slug}-{$gridpress_name}.php";

			if ( file_exists( $gridpress_fallback ) ) {
				$gridpress_template = $gridpress_fallback;
			}
		}

		if ( ! $gridpress_template ) {
			$gridpress_template = locate_template( [
				"{$gridpress_slug}.php",
				"gridpress/{$gridpress_ext}{$gridpress_slug}.php",
			] );
		}

		if ( $gridpress_template ) {
			load_template( $gridpress_template, false );
		}
	}
endif;
