<?php
namespace QuizPress;

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

class Helper {
	public static function sanitize_checkbox_field( $boolean ) {
		return filter_var( sanitize_text_field( $boolean ), FILTER_VALIDATE_BOOLEAN );
	}

	public static function get_settings( $key, $default = null ) {
		global $quizpress_settings;

		if ( isset( $quizpress_settings->{$key} ) ) {
			return $quizpress_settings->{$key};
		}

		return $default;
	}
	public static function is_valid_site_url( string $url ): bool {
		return str_starts_with( $url, get_option( 'siteurl' ) );
	}

	public static function get_addon_active_status( $addon_name, $is_pro = false ) {
		global $quizpress_addons;

		if ( isset( $quizpress_addons->{$addon_name} ) ) {
			return (bool) $quizpress_addons->{$addon_name};
		}

		return false;
	}

	public static function get_page_by_slug( $page_slug, $post_type = 'page' ) {
		global $wpdb;

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$page = $wpdb->get_var( $wpdb->prepare(
			"SELECT ID
			FROM $wpdb->posts
			WHERE post_name = %s
			AND post_type = %s",
			$page_slug,
			$post_type
		) );

		if ( $page ) {
			return get_post( $page, OBJECT );
		}

		return null;
	}

	public static function get_all_addons( $is_json = false ) {
		global $quizpress_addons;

		if ( $is_json ) {
			return wp_json_encode( $quizpress_addons );
		}

		return $quizpress_addons;
	}

	public static function get_client_ip_address() {
		$ip_address = '';
		if ( getenv( 'HTTP_CLIENT_IP' ) ) {
			$ip_address = getenv( 'HTTP_CLIENT_IP' );
		} elseif ( getenv( 'REMOTE_ADDR' ) ) {
			$ip_address = getenv( 'REMOTE_ADDR' );
		} elseif ( getenv( 'HTTP_FORWARDED_FOR' ) ) {
			$ip_address = getenv( 'HTTP_FORWARDED_FOR' );
		} elseif ( getenv( 'HTTP_FORWARDED' ) ) {
			$ip_address = getenv( 'HTTP_FORWARDED' );
		} elseif ( getenv( 'HTTP_X_FORWARDED_FOR' ) ) {
			$ip_address = getenv( 'HTTP_X_FORWARDED_FOR' );
		} elseif ( getenv( 'HTTP_X_FORWARDED' ) ) {
			$ip_address = getenv( 'HTTP_X_FORWARDED' );
		}

		return $ip_address;
	}

	public static function calculate_percentage( $total_count, $completed_count ) {
		if ( $total_count > 0 && $completed_count > 0 ) {
			return number_format( ( $completed_count * 100 ) / $total_count );
		}

		return 0;
	}

	public static function get_time() {
		return time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
	}

	/**
	 * List of admin menu
	 */
	public static function get_admin_menu_list() {
		$menu                                     = [];
		$menu[ QUIZPRESS_PLUGIN_SLUG ]              = [
			'parent_slug' => QUIZPRESS_PLUGIN_SLUG,
			'title'       => __( 'Dashboard', 'quizpress' ),
			'capability'  => 'manage_options',
		];
		$menu[ QUIZPRESS_PLUGIN_SLUG . '-quizzes' ] = [
			'parent_slug' => QUIZPRESS_PLUGIN_SLUG,
			'title'       => __( 'Quizzes', 'quizpress' ),
			'capability'  => 'manage_options',
		];
		$menu[ QUIZPRESS_PLUGIN_SLUG . '-questions' ] = [
			'parent_slug' => QUIZPRESS_PLUGIN_SLUG,
			'title'       => __( 'Questions', 'quizpress' ),
			'capability'  => 'manage_options',
			'sub_items'   => [
				[
					'slug'  => '',
					'title' => __( 'All Questions', 'quizpress' ),
				],
				[
					'slug'  => 'category',
					'title' => __( 'Category', 'quizpress' ),
				],
			],
		];
		$menu[ QUIZPRESS_PLUGIN_SLUG . '-quiz-insights' ] = [
			'parent_slug' => QUIZPRESS_PLUGIN_SLUG,
			'title'       => __( 'Quiz Insights', 'quizpress' ),
			'capability'  => 'manage_options',
		];
		if ( self::get_addon_active_status( 'certificates', true ) ) {
			$menu[ QUIZPRESS_PLUGIN_SLUG . '-certificates' ] = [
				'parent_slug' => QUIZPRESS_PLUGIN_SLUG,
				'title'       => __( 'Certificates', 'quizpress' ),
				'capability'  => 'manage_options',
			];
		}
		$menu[ QUIZPRESS_PLUGIN_SLUG . '-addons' ] = [
			'parent_slug' => QUIZPRESS_PLUGIN_SLUG,
			'title'       => __( 'Addons', 'quizpress' ),
			'capability'  => 'manage_options',
		];
		if ( self::get_addon_active_status( 'certificates' ) ) {
			$menu[ QUIZPRESS_PLUGIN_SLUG . '-certificates' ] = [
				'parent_slug' => QUIZPRESS_PLUGIN_SLUG,
				'title'       => __( 'Certificates', 'quizpress' ),
				'capability'  => 'manage_options',
			];
		}
		$menu[ QUIZPRESS_PLUGIN_SLUG . '-settings' ] = [
			'parent_slug' => QUIZPRESS_PLUGIN_SLUG,
			'title'       => __( 'Settings', 'quizpress' ),
			'capability'  => 'manage_options',
		];

		return apply_filters( 'quizpress/admin_menu_list', $menu );
	}

	public static function is_active_quizpress_pro() {
		$quizpress_pro = 'quizpress/includes/premium/premium.php';

		return self::is_plugin_active( $quizpress_pro );
	}

	public static function is_plugin_active( $basename ) {
		if ( ! function_exists( 'get_plugins' ) ) {
			include_once ABSPATH . '/wp-admin/includes/plugin.php';
		}

		return is_plugin_active( $basename );
	}

	public static function get_template_part( $slug, $name = '', $args = [] ) {
		$template = '';

		// Try with -name.php
		if ( $name ) {
			$template = locate_template( [ "{$slug}-{$name}.php" ] );
			if ( ! $template ) {
				$fallback = trailingslashit( QUIZPRESS_ROOT_DIR_PATH ) . "templates/{$slug}-{$name}.php";
				$template = file_exists( $fallback ) ? $fallback : '';
			}
		}

		// Try without -name.php
		if ( ! $template ) {
			$template = locate_template( [ "{$slug}.php" ] );
			if ( ! $template ) {
				$fallback = trailingslashit( QUIZPRESS_ROOT_DIR_PATH ) . "templates/{$slug}.php";
				$template = file_exists( $fallback ) ? $fallback : '';
			}
		}

		if ( ! empty( $args ) && is_array( $args ) ) {
			extract( $args, EXTR_SKIP );
		}

		if ( $template && file_exists( $template ) ) {
			include $template;
		} else {
			error_log( 'QuizPress template not found: ' . $slug );
		}
	}

	public static function locate_template( $template_name, $template_path = '', $default_path = '' ) {
		if ( ! $template_path ) {
			$template_path = 'quizpress/';
		}

		if ( ! $default_path ) {
			$default_path = trailingslashit( QUIZPRESS_ROOT_DIR_PATH ) . 'templates/';
		}

		$template = locate_template( [ trailingslashit( $template_path ) . $template_name ] );

		if ( ! $template ) {
			$template = $default_path . $template_name;
		}

		return apply_filters( 'quizpress_locate_template', $template, $template_name, $template_path, $default_path );
	}

		/**
		 * Get other templates (e.g. course attributes) passing attributes and including the file.
		 *
		 * @param string $template_name Template name.
		 * @param array  $args Arguments. (default: array).
		 * @param string $template_path Template path. (default: '').
		 * @param string $default_path Default path. (default: '').
		 */
	public static function get_template( $template_name, $args = array(), $template_path = '', $default_path = '' ) {
		$template = false;

		if ( ! $template ) {
			$template = self::locate_template( $template_name, $template_path, $default_path );
		}

		// Allow 3rd party plugin filter template file from their plugin.
		$filter_template = apply_filters( 'quizpress/get_template', $template, $template_name, $args, $template_path, $default_path );

		if ( $filter_template !== $template ) {
			if ( ! file_exists( $filter_template ) ) {
				/* translators: %s template */
				wc_doing_it_wrong( __FUNCTION__, sprintf( __( '%s does not exist.', 'quizpress' ), '<code>' . $filter_template . '</code>' ), '1.0.0' );

				return;
			}
			$template = $filter_template;
		}

		$action_args = array(
			'template_name' => $template_name,
			'template_path' => $template_path,
			'located'       => $template,
			'args'          => $args,
		);

		if ( ! empty( $args ) && is_array( $args ) ) {
			if ( isset( $args['action_args'] ) ) {
				wc_doing_it_wrong(
					__FUNCTION__,
					__( 'action_args should not be overwritten when calling quizpress/get_template.', 'quizpress' ),
					'1.0.0'
				);
				unset( $args['action_args'] );
			}
			extract( $args ); // @codingStandardsIgnoreLine
		}

		do_action( 'quizpress/before_template_part', $action_args['template_name'], $action_args['template_path'], $action_args['located'], $action_args['args'] );
		include $action_args['located'];

		do_action( 'quizpress/after_template_part', $action_args['template_name'], $action_args['template_path'], $action_args['located'], $action_args['args'] );
	}

	public static function sanitize_referer_url( $referer_url ) {
		$parse_url = wp_parse_url( $referer_url );
		if ( isset( $parse_url['query'] ) ) {
			// Parse query parameters
			parse_str( $parse_url['query'], $query_params );
			if ( isset( $query_params['redirect_to'] ) && ! empty( $query_params['redirect_to'] ) ) {
				$referer_url = $query_params['redirect_to'];
			}
			if ( isset( $query_params['redirect_url'] ) && ! empty( $query_params['redirect_url'] ) ) {
				$referer_url = $query_params['redirect_url'];
			}
		}
		// Sanitize the input URL
		$referer_url = esc_url_raw( $referer_url );
		if ( filter_var( $referer_url, FILTER_VALIDATE_URL ) !== false && wp_http_validate_url( $referer_url ) && strpos( $referer_url, home_url() ) === 0 ) {
			return esc_url( $referer_url );
		} elseif ( isset( $parse_url['path'] ) && ! empty( $parse_url['path'] ) ) {
			return esc_url( home_url( sanitize_text_field( $parse_url['path'] ) ) );
		}

		return esc_url( home_url( '/' ) );
	}

	public static function get_page_by_title( $page_title, $post_type = 'page' ) {
		global $wpdb;

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$page = $wpdb->get_var( $wpdb->prepare(
			"SELECT ID
			FROM $wpdb->posts
			WHERE post_title = %s
			AND post_type = %s",
			$page_title,
			$post_type
		) );

		if ( $page ) {
			return get_post( $page, OBJECT );
		}

		return null;
	}

	public static function quizpress_get_guest_token() {
		if ( is_user_logged_in() ) {
			return null;
		}

		global $wpdb;
		$table_name = $wpdb->prefix . 'quizpress_guest_tokens';
		if ( $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $table_name ) ) !== $table_name ) {
			return null;
		}
		// Check if cookie exists
		if ( isset( $_COOKIE['quizpress_guest_token'] ) ) {
			$token = sanitize_text_field( $_COOKIE['quizpress_guest_token'] );

			// Check token in database
			$row = $wpdb->get_row(
				$wpdb->prepare(
					"SELECT token, created_at FROM $table_name WHERE token = %s",
					$token
				)
			);

			if ( $row ) {
				// Token expiration: 24 hours
				if ( time() - strtotime( $row->created_at ) < DAY_IN_SECONDS ) {
					return $token;
				} else {
					// Token expired → delete from DB
					$wpdb->delete( $table_name, [ 'token' => $token ], [ '%s' ] );
				}
			}
		}//end if

		// Generate strong random token
		$token = bin2hex( random_bytes( 32 ) );

		// Store token server-side
		$wpdb->insert(
			$table_name,
			[
				'token'      => $token,
				'created_at' => current_time( 'mysql', 1 ),
			],
			[ '%s', '%s' ]
		);

		// Set secure cookie with SameSite
		setcookie(
			'quizpress_guest_token',
			$token,
			[
				'expires'  => time() + DAY_IN_SECONDS,
				'path'     => COOKIEPATH,
				'domain'   => COOKIE_DOMAIN,
				'secure'   => is_ssl(),
				'httponly' => true,
				'samesite' => 'Lax',
			]
		);

		return $token;
	}

	public static function get_guest_id_by_token( $token ) {
		global $wpdb;
		$table_name = $wpdb->prefix . 'quizpress_guest_tokens';
		$guest_id = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT id FROM {$table_name} WHERE token = %s",
				$token
			)
		);

		return $guest_id ? (int) $guest_id : 0;
	}


	/**
	 * Check current screen is academy admin page or not
	 *
	 * @return bool
	 */
	public static function is_quizpress_admin_page() {
		if ( is_admin() ) {
			$screen = get_current_screen();

			return self::plugin_page_hook_suffix( $screen->base );
		}

		return false;
	}

	/**
	 * Check Supported Post type for admin page and plugin main settings page
	 *
	 * @param string $hook
	 *
	 * @return bool
	 */
	public static function plugin_page_hook_suffix( $hook ) {
		if ( strpos( $hook, '_page_' . QUIZPRESS_PLUGIN_SLUG ) !== false ) {
			return true;
		}

		return false;
	}

	public static function maybe_define_constant( $name, $value ) {
		if ( ! defined( $name ) ) {
			define( $name, $value );
		}
	}

	/**
	 * Check if the current frontend request is for a singular post/page that
	 * renders the quiz shortcode, so cache plugins can be told not to cache it.
	 *
	 * @return bool
	 */
	public static function is_quizpress_quiz_page() {
		if ( is_admin() || ! is_singular() ) {
			return false;
		}

		$post = get_post();

		return $post && has_shortcode( $post->post_content, 'quizpress_quiz' );
	}
}
