<?php

/**
 * Serve-time HTML head metadata injection for static exports.
 *
 * @package Parkstatic
 */
declare (strict_types = 1);
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
/**
 * Injects WordPress-managed metadata into served static HTML.
 */
final class Parkstatic_Meta_Injector {
    /** @deprecated Legacy global toggle kept only as migration fallback; use per-field flags below. */
    public const OPTION_INJECT_ENABLED = 'parkstatic_meta_inject_enabled';

    public const OPTION_OG_TITLE = 'parkstatic_og_title';

    public const OPTION_OG_DESCRIPTION = 'parkstatic_og_description';

    public const OPTION_OG_IMAGE_ID = 'parkstatic_og_image_id';

    public const OPTION_TITLE_ENABLED = 'parkstatic_meta_title_enabled';

    public const OPTION_DESCRIPTION_ENABLED = 'parkstatic_meta_description_enabled';

    public const OPTION_FAVICON_ENABLED = 'parkstatic_meta_favicon_enabled';

    // Premium OG per-field enabled flags; only used inside can_use_premium_code__premium_only() guards.
    public const OPTION_OG_TITLE_ENABLED = 'parkstatic_og_title_enabled';

    public const OPTION_OG_DESCRIPTION_ENABLED = 'parkstatic_og_description_enabled';

    public const OPTION_OG_IMAGE_ENABLED = 'parkstatic_og_image_enabled';

    /**
     * Returns whether an individual field override is active.
     *
     * When the per-field flag has never been written to the database (i.e. the
     * user has not yet saved settings since upgrading to per-field overrides),
     * the legacy global inject flag is used as a migration fallback so existing
     * configurations continue to work without any manual action.
     */
    public static function is_field_enabled( string $option_key ) : bool {
        $value = get_option( $option_key, null );
        if ( null !== $value ) {
            return (bool) $value;
        }
        // Migration: no per-field flag written yet → fall back to the old global flag.
        return (bool) get_option( self::OPTION_INJECT_ENABLED, false );
    }

    public static function is_enabled() : bool {
        if ( self::is_field_enabled( self::OPTION_TITLE_ENABLED ) ) {
            return true;
        }
        if ( self::is_field_enabled( self::OPTION_DESCRIPTION_ENABLED ) ) {
            return true;
        }
        if ( self::is_field_enabled( self::OPTION_FAVICON_ENABLED ) ) {
            return true;
        }
        return false;
    }

    public static function needs_html_processing() : bool {
        return self::is_enabled();
    }

    public static function meta_signature() : string {
        $parts = array(
            (string) get_option( 'blogname', '' ),
            (string) get_option( 'blogdescription', '' ),
            (string) get_option( 'site_icon', 0 ),
            (string) (int) self::is_field_enabled( self::OPTION_TITLE_ENABLED ),
            (string) (int) self::is_field_enabled( self::OPTION_DESCRIPTION_ENABLED ),
            (string) (int) self::is_field_enabled( self::OPTION_FAVICON_ENABLED )
        );
        return substr( md5( implode( '|', $parts ) ), 0, 8 );
    }

    public static function process_html( string $html ) : string {
        if ( self::is_enabled() ) {
            $html = self::inject( $html );
        }
        return $html;
    }

    public static function inject( string $html ) : string {
        $title_enabled = self::is_field_enabled( self::OPTION_TITLE_ENABLED );
        $description_enabled = self::is_field_enabled( self::OPTION_DESCRIPTION_ENABLED );
        $favicon_enabled = self::is_field_enabled( self::OPTION_FAVICON_ENABLED );
        $title = ( $title_enabled ? self::get_site_title() : '' );
        $description = ( $description_enabled ? self::get_site_description() : '' );
        $favicon_url = ( $favicon_enabled ? self::get_favicon_url() : '' );
        $has_title = '' !== $title;
        $has_description = '' !== $description;
        $has_favicon = '' !== $favicon_url;
        $has_og = false;
        $og_title = '';
        $og_desc = '';
        $og_image = '';
        $og_url = '';
        if ( !$has_title && !$has_description && !$has_favicon && !$has_og ) {
            return $html;
        }
        if ( $has_title ) {
            $html = self::strip_title( $html );
        }
        if ( $has_description ) {
            $html = self::strip_meta_name( $html, 'description' );
        }
        if ( $has_favicon ) {
            $html = self::strip_favicon_links( $html );
        }
        $block = self::build_injection_block(
            $title,
            $description,
            $favicon_url,
            $og_title,
            $og_desc,
            $og_image,
            $og_url,
            $has_title,
            $has_description,
            $has_favicon,
            $has_og
        );
        if ( '' === $block ) {
            return $html;
        }
        return self::insert_before_head_close( $html, $block );
    }

    private static function get_site_title() : string {
        $title = get_bloginfo( 'name' );
        return ( is_string( $title ) ? trim( $title ) : '' );
    }

    private static function get_site_description() : string {
        $description = get_bloginfo( 'description' );
        return ( is_string( $description ) ? trim( $description ) : '' );
    }

    private static function get_favicon_url() : string {
        if ( !function_exists( 'get_site_icon_url' ) ) {
            return '';
        }
        $url = get_site_icon_url( 512 );
        return ( is_string( $url ) ? trim( $url ) : '' );
    }

    /**
     * @return string HTML fragment inserted before </head>.
     */
    private static function build_injection_block(
        string $title,
        string $description,
        string $favicon_url,
        string $og_title,
        string $og_description,
        string $og_image,
        string $og_url,
        bool $has_title,
        bool $has_description,
        bool $has_favicon,
        bool $has_og
    ) : string {
        $lines = array('<!-- parkstatic-meta -->');
        if ( $has_title ) {
            $lines[] = '<title>' . esc_html( $title ) . '</title>';
        }
        if ( $has_description ) {
            $lines[] = '<meta name="description" content="' . esc_attr( $description ) . '">';
        }
        if ( $has_favicon ) {
            $lines[] = '<link rel="icon" href="' . esc_url( $favicon_url ) . '">';
            $lines[] = '<link rel="shortcut icon" href="' . esc_url( $favicon_url ) . '">';
            $lines[] = '<link rel="apple-touch-icon" href="' . esc_url( $favicon_url ) . '">';
        }
        return implode( "\n", $lines ) . "\n";
    }

    private static function strip_title( string $html ) : string {
        return (string) preg_replace( '#<title\\b[^>]*>.*?</title>#is', '', $html );
    }

    private static function strip_meta_name( string $html, string $name ) : string {
        $pattern = '#<meta\\b[^>]*\\bname=(["\'])' . preg_quote( $name, '#' ) . '\\1[^>]*>#i';
        return (string) preg_replace( $pattern, '', $html );
    }

    private static function strip_favicon_links( string $html ) : string {
        $pattern = '#<link\\b[^>]*\\brel=(["\'])(?:icon|shortcut icon|apple-touch-icon)\\1[^>]*>#i';
        return (string) preg_replace( $pattern, '', $html );
    }

    private static function insert_before_head_close( string $html, string $block ) : string {
        $pos = stripos( $html, '</head>' );
        if ( false === $pos ) {
            return $html . "\n" . $block;
        }
        return substr( $html, 0, $pos ) . $block . substr( $html, $pos );
    }

}
