<?php
/**
 * Helper functions for PDF Search plugin
 *
 * @package WebEquipe\PDFSearch
 * @since 1.0.0
 */

namespace WebEquipe\PDFSearch;

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

// Prevent multiple includes.
if ( defined( 'WEBEQUIPE_PDF_SEARCH_FUNCTIONS_LOADED' ) ) {
	return;
}

/**
 * Extend max execution time for indexing (Processing Timeout setting; PHP default is often 30s).
 *
 * @since 1.0.2
 * @param int $seconds Seconds allowed from this call; values above 7200 are capped.
 * @return void
 */
function webequipe_pdf_search_set_indexing_time_limit( $seconds ) {
	$seconds = (int) $seconds;
	if ( $seconds < 1 ) {
		return;
	}

	$seconds = min( 7200, $seconds );

	if ( function_exists( 'set_time_limit' ) ) {
		// phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- PDF indexing needs extended runtime on shared hosts.
		@set_time_limit( $seconds );
	}
}

/**
 * Logging function
 *
 * @since 1.0.0
 * @param string $message Log message.
 * @param string $level Log level (ERROR, WARNING, INFO, DEBUG).
 * @return void
 */
function webequipe_pdf_search_log( $message, $level = 'INFO' ) {
	// Get settings, but handle case where Database class might not be fully loaded.
	$settings = array();
	if ( class_exists( __NAMESPACE__ . '\Database' ) ) {
		$settings = Database::get_settings();
	}

	$debug_enabled = isset( $settings['enable_debug'] ) && $settings['enable_debug'];

	if ( 'DEBUG' === $level && ! $debug_enabled ) {
		return;
	}

	$timestamp = current_time( 'mysql' );
	$formatted = sprintf( '[%s] [%s] %s', $timestamp, $level, $message );

	// Fire action for external logging integrations.
	do_action( 'webequipe_pdf_search_log', $message, $level, $timestamp );

	// Keep logs inside WordPress-managed storage/hooks to avoid direct filesystem writes.
	// This preserves compatibility on hosts using FTP/SSH filesystem methods.

	// Store errors and warnings (and debug info when enabled) in database.
	$stored_levels = array( 'ERROR', 'WARNING' );
	if ( $debug_enabled ) {
		$stored_levels[] = 'DEBUG';
		$stored_levels[] = 'INFO';
	}

	if ( in_array( $level, $stored_levels, true ) ) {
		$logs   = get_option( 'webequipe_pdf_search_logs', array() );
		$logs[] = array(
			'timestamp' => $timestamp,
			'level'     => $level,
			'message'   => $message,
		);
		// Keep only last 100 logs.
		$logs = array_slice( $logs, -100 );
		update_option( 'webequipe_pdf_search_logs', $logs );
	}
}

/**
 * Get a display-friendly title for a PDF (replace underscores, strip .pdf).
 *
 * @since 1.0.1
 * @param string $title Raw title (e.g. attachment title or filename).
 * @return string
 */
function webequipe_pdf_search_get_display_title( $title ) {
	$title = trim( (string) $title );
	if ( '' === $title ) {
		return $title;
	}
	if ( preg_match( '/\.pdf$/i', $title ) ) {
		$title = preg_replace( '/\.pdf$/i', '', $title );
	}
	$title = str_replace( '_', ' ', $title );
	$title = trim( $title );
	return apply_filters( 'webequipe_pdf_search_display_title', $title );
}

/**
 * Get a usable preview image URL for a PDF attachment.
 * Tries multiple sizes and skips transparent/data-URI placeholders.
 *
 * @since 1.0.1
 * @param int $attachment_id Attachment post ID.
 * @return string Preview URL or empty string when unavailable.
 */
function webequipe_pdf_search_get_preview_image_url( $attachment_id ) {
	$attachment_id = (int) $attachment_id;
	if ( $attachment_id <= 0 ) {
		return '';
	}

	$sizes = array( 'large', 'medium_large', 'medium', 'thumbnail', 'full' );
	foreach ( $sizes as $size ) {
		$url = wp_get_attachment_image_url( $attachment_id, $size );
		if ( empty( $url ) || ! is_string( $url ) ) {
			continue;
		}
		// Data URIs (e.g. transparent SVG placeholders) are not real thumbnails.
		if ( strpos( $url, 'data:image/' ) === 0 ) {
			continue;
		}
		return $url;
	}

	return '';
}

/**
 * Check if an attachment has a real (non-placeholder) preview image for display.
 * Returns false when WordPress only provides a data URI (e.g. transparent SVG placeholder).
 *
 * @since 1.0.1
 * @param int $attachment_id Attachment post ID.
 * @return bool True if a usable preview image URL exists.
 */
function webequipe_pdf_search_has_preview_image( $attachment_id ) {
	return '' !== webequipe_pdf_search_get_preview_image_url( $attachment_id );
}

/**
 * Template tag: Get PDF icon
 *
 * @since 1.0.0
 * @return string HTML string with PDF icon
 */
function webequipe_pdf_search_get_icon() {
	$settings = array();
	if ( class_exists( __NAMESPACE__ . '\Database' ) ) {
		$settings = Database::get_settings();
	}
	$icon_type = isset( $settings['pdf_icon_type'] ) ? $settings['pdf_icon_type'] : 'svg';

	$icon = apply_filters( 'webequipe_pdf_search_icon', '', $icon_type );

	if ( empty( $icon ) ) {
		if ( 'svg' !== $icon_type ) {
			return '';
		}

		$svg_url = trailingslashit( plugin_dir_url( __DIR__ ) ) . 'assets/icon-pdf.svg';
		$icon    = '<img class="webequipe-pdf-icon-img" src="' . esc_url( $svg_url ) . '" alt="' . esc_attr__( 'PDF', 'webequipe-pdf-search' ) . '" />';
	}

	$allowed = array(
		'span' => array(
			'class' => true,
		),
		'img'  => array(
			'class' => true,
			'src'   => true,
			'alt'   => true,
		),
	);

	return wp_kses( $icon, $allowed );
}

/**
 * Template tag: Get file size
 *
 * @since 1.0.0
 * @param int $post_id WordPress attachment ID.
 * @return string Formatted file size or empty string
 */
function webequipe_pdf_search_get_file_size( $post_id ) {
	if ( ! class_exists( __NAMESPACE__ . '\Database' ) ) {
		return '';
	}
	$indexed = Database::get_indexed_pdf( $post_id );
	if ( ! $indexed || ! $indexed->pdf_filesize ) {
		return '';
	}
	return size_format( $indexed->pdf_filesize );
}

/**
 * Template tag: Get page count
 *
 * @since 1.0.0
 * @param int $post_id WordPress attachment ID.
 * @return int Page count or 0
 */
function webequipe_pdf_search_get_page_count( $post_id ) {
	if ( ! class_exists( __NAMESPACE__ . '\Database' ) ) {
		return 0;
	}
	$indexed = Database::get_indexed_pdf( $post_id );
	if ( ! $indexed ) {
		return 0;
	}
	return (int) $indexed->page_count;
}

/**
 * Template tag: Get excerpt
 *
 * @since 1.0.0
 * @param int $post_id WordPress attachment ID.
 * @param int $length Character length.
 * @return string Excerpt string
 */
function webequipe_pdf_search_get_excerpt( $post_id, $length = 200 ) {
	if ( ! class_exists( __NAMESPACE__ . '\Database' ) ) {
		return '';
	}
	$indexed = Database::get_indexed_pdf( $post_id );
	if ( ! $indexed || empty( $indexed->pdf_content ) ) {
		return '';
	}

	$content = wp_strip_all_tags( $indexed->pdf_content );
	$excerpt = wp_trim_words( $content, $length / 10, '...' );

	return $excerpt;
}

/**
 * Template tag: Check if post is PDF
 *
 * @since 1.0.0
 * @param int $post_id WordPress attachment ID.
 * @return bool True if PDF
 */
function webequipe_pdf_search_is_pdf( $post_id ) {
	$mime_type = get_post_mime_type( $post_id );
	return 'application/pdf' === $mime_type;
}

/**
 * Template tag: Get indexed data
 *
 * @since 1.0.0
 * @param int $post_id WordPress attachment ID.
 * @return object|null Indexed data object or null
 */
function webequipe_pdf_search_get_indexed_data( $post_id ) {
	if ( ! class_exists( __NAMESPACE__ . '\Database' ) ) {
		return null;
	}
	return Database::get_indexed_pdf( $post_id );
}

/**
 * Template tag: Get admin display status for a PDF attachment.
 *
 * @since 1.2.0
 * @param int $post_id WordPress attachment ID.
 * @return string error|excluded|indexed|processing|scheduled|not_indexed
 */
function webequipe_pdf_search_get_display_status( $post_id ) {
	if ( ! class_exists( __NAMESPACE__ . '\Database' ) ) {
		return 'not_indexed';
	}
	return Database::get_pdf_display_status( $post_id );
}

/**
 * Apply script loading strategy for plugin scripts.
 *
 * @since 1.0.0
 * @param string $handle Script handle.
 * @param string $context Context string (admin|public).
 * @return void
 */
function webequipe_pdf_search_add_script_strategy( $handle, $context = '' ) {
	$strategy = apply_filters( 'webequipe_pdf_search_script_strategy', 'defer', $handle, $context );
	if ( empty( $strategy ) ) {
		return;
	}

	if ( function_exists( 'wp_script_add_data' ) ) {
		if ( version_compare( get_bloginfo( 'version' ), '6.3', '>=' ) ) {
			wp_script_add_data( $handle, 'strategy', $strategy );
		} elseif ( in_array( $strategy, array( 'async', 'defer' ), true ) ) {
			wp_script_add_data( $handle, $strategy, true );
		}
	}
}

/**
 * Filter script tag to add custom attributes to plugin scripts.
 *
 * @since 1.0.0
 * @param string $tag Script tag.
 * @param string $handle Script handle.
 * @param string $src Script src.
 * @return string Modified script tag
 */
function webequipe_pdf_search_filter_script_tag( $tag, $handle, $src ) {
	$plugin_handles = array( 'webequipe-pdf-search-admin', 'webequipe-pdf-search-public' );
	if ( ! in_array( $handle, $plugin_handles, true ) ) {
		return $tag;
	}

	$attrs = apply_filters( 'webequipe_pdf_search_script_attributes', array(), $handle, $src );
	if ( empty( $attrs ) || ! is_array( $attrs ) ) {
		return $tag;
	}

	$attr_html = '';
	foreach ( $attrs as $name => $value ) {
		if ( is_bool( $value ) ) {
			if ( $value ) {
				$attr_html .= ' ' . esc_attr( $name );
			}
			continue;
		}
		$attr_html .= ' ' . esc_attr( $name ) . '="' . esc_attr( $value ) . '"';
	}

	if ( '' === $attr_html ) {
		return $tag;
	}

	return str_replace( ' src=', $attr_html . ' src=', $tag );
}
add_filter( 'script_loader_tag', __NAMESPACE__ . '\webequipe_pdf_search_filter_script_tag', 10, 3 );

/**
 * Filter style tag to add custom attributes to plugin styles.
 *
 * @since 1.0.0
 * @param string $tag Style tag.
 * @param string $handle Style handle.
 * @param string $href Style href.
 * @param string $media Media attribute.
 * @return string Modified style tag
 */
function webequipe_pdf_search_filter_style_tag( $tag, $handle, $href, $media ) {
	$plugin_handles = array( 'webequipe-pdf-search-admin', 'webequipe-pdf-search-public' );
	if ( ! in_array( $handle, $plugin_handles, true ) ) {
		return $tag;
	}

	$attrs = apply_filters( 'webequipe_pdf_search_style_attributes', array(), $handle, $href, $media );
	if ( empty( $attrs ) || ! is_array( $attrs ) ) {
		return $tag;
	}

	$attr_html = '';
	foreach ( $attrs as $name => $value ) {
		if ( is_bool( $value ) ) {
			if ( $value ) {
				$attr_html .= ' ' . esc_attr( $name );
			}
			continue;
		}
		$attr_html .= ' ' . esc_attr( $name ) . '="' . esc_attr( $value ) . '"';
	}

	if ( '' === $attr_html ) {
		return $tag;
	}

	return str_replace( ' rel=', $attr_html . ' rel=', $tag );
}
add_filter( 'style_loader_tag', __NAMESPACE__ . '\webequipe_pdf_search_filter_style_tag', 10, 4 );

// Mark as loaded - must be at end after all function declarations.
define( 'WEBEQUIPE_PDF_SEARCH_FUNCTIONS_LOADED', true );
