<?php
/**
 * Utility helper functions for the plugin.
 * 
 * @package WPStaticHTMLPages
 */

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

class WPSH_Helper {

	/**
	 * Get the directory where static files are stored.
	 */
	public static function get_dir() {
		$dir = WP_CONTENT_DIR . '/static-html';
		if ( is_multisite() && function_exists( 'get_current_blog_id' ) ) {
			$dir .= '/site-' . get_current_blog_id();
		}
		if ( ! file_exists( $dir ) ) {
			wp_mkdir_p( $dir );
		}
		return wp_normalize_path( $dir );
	}

	/**
	 * Get the URL to the static HTML directory.
	 */
	public static function get_url() {
		$url = content_url( '/static-html' );
		if ( is_multisite() && function_exists( 'get_current_blog_id' ) ) {
			$url .= '/site-' . get_current_blog_id();
		}
		return $url;
	}

	/**
	 * Check if a post is excluded from static generation.
	 */
	public static function is_excluded( $post_id ) {
		if ( get_post_meta( $post_id, '_wpsh_exclude', true ) === '1' ) {
			return true;
		}
		
		$type           = get_post_type( $post_id );
		$excluded_types = (array) get_option( 'wpsh_excluded_post_types', array() );
		if ( in_array( $type, $excluded_types, true ) ) {
			return true;
		}
		
		return false;
	}

	/**
	 * Check if a taxonomy is excluded.
	 */
	public static function is_taxonomy_excluded( $taxonomy ) {
		$excluded_tax = (array) get_option( 'wpsh_excluded_taxonomies', array() );
		return in_array( $taxonomy, $excluded_tax, true );
	}

	/**
	 * Clean a redirection source URL/path to a relative slug.
	 */
	public static function clean_redir_source( $source ) {
		if ( empty( $source ) ) {
			return '';
		}
		$source = trim( $source );
		
		$path = wp_parse_url( $source, PHP_URL_PATH );
		if ( null === $path ) {
			$path = $source;
		}

		$home_url  = home_url( '/' );
		$home_path = wp_parse_url( $home_url, PHP_URL_PATH );
		
		if ( ! empty( $home_path ) && '/' !== $home_path ) {
			$home_path  = trim( $home_path, '/' );
			$clean_path = trim( $path, '/' );
			if ( 0 === strpos( $clean_path, $home_path ) ) {
				$path = substr( $clean_path, strlen( $home_path ) );
			}
		}
		
		return trim( $path, '/' );
	}
}
