<?php
/**
 * Frontend Functionality
 *
 * @package HDSofT\AISummary
 */

namespace HDSofT\AISummary;

// Prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Frontend Class
 */
class Frontend {

    /**
     * Constructor
     */
    public function __construct() {
        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_frontend_scripts' ) );
    }

    /**
     * Shortcode handler
     *
     * @param array $atts Shortcode attributes.
     * @return string
     */
    public function shortcode( $atts ) {
        $atts = shortcode_atts(
            array(
                'post_id' => get_the_ID(),
                'class'   => 'hdsoft-ai-summary',
                'wrapper' => 'div',
            ),
            $atts,
            'hdsoft_ai_summary'
        );

        $post_id = intval( $atts['post_id'] );
        if ( ! $post_id ) {
            return '';
        }

        $plugin = Plugin::get_instance();
        $summary = $plugin->get_summary( $post_id );

        if ( ! $summary ) {
            return '';
        }

        // Build summary HTML with dynamic title
        $summary_html = $this->build_summary_html( $summary, $post_id );
        
        // Sanitize attributes
        $class = sanitize_html_class( $atts['class'] );
        $wrapper = in_array( $atts['wrapper'], array( 'div', 'section', 'aside', 'p' ), true ) ? $atts['wrapper'] : 'div';

        // Build output
        $output = sprintf(
            '<%1$s class="%2$s">%3$s</%1$s>',
            esc_html( $wrapper ),
            esc_attr( $class ),
            $summary_html
        );

        return $output;
    }

    /**
     * Maybe append summary to content
     *
     * @param string $content Post content.
     * @return string
     */
    public function maybe_append_summary( $content ) {
        // Only process on single posts and pages
        if ( ! is_singular() ) {
            return $content;
        }

        // Skip if we're in the admin, RSS feed, or REST API
        if ( is_admin() || is_feed() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) {
            return $content;
        }

        // Skip if this is not the main query
        if ( ! in_the_loop() || ! is_main_query() ) {
            return $content;
        }

        $post_id = get_the_ID();
        if ( ! $post_id ) {
            return $content;
        }

        // Check if post type is supported
        $supported_post_types = array( 'post', 'page' );
        if ( ! in_array( get_post_type( $post_id ), $supported_post_types, true ) ) {
            return $content;
        }

        // Get settings
        $settings = get_option( 'hdsoft_ai_summary_settings', array() );
        $append_position = isset( $settings['append_position'] ) ? $settings['append_position'] : 'after';

        // Skip if manual only
        if ( 'manual' === $append_position ) {
            return $content;
        }

        $plugin = Plugin::get_instance();
        $summary = $plugin->get_summary( $post_id );

        if ( ! $summary ) {
            return $content;
        }

        // Build summary HTML with dynamic title
        $summary_html = $this->build_summary_html( $summary, $post_id );

        // Append or prepend based on settings
        if ( 'before' === $append_position ) {
            return $summary_html . $content;
        } else {
            return $content . $summary_html;
        }
    }


    /**
     * Build summary HTML
     *
     * @param string $summary Summary text.
     * @param int    $post_id Post ID to get title for.
     * @return string
     */
    private function build_summary_html( $summary, $post_id = null ) {
        if ( ! $post_id ) {
            $post_id = get_the_ID();
        }
        
        $plugin = Plugin::get_instance();
        $title = $plugin->get_summary_title( $post_id );
        
        $html = '<div class="hdsoft-ai-summary-container">';
        
        if ( ! empty( $title ) ) {
            $html .= '<h3 class="hdsoft-ai-summary-title">' . esc_html( $title ) . '</h3>';
        }
        
        $html .= '<div class="hdsoft-ai-summary-content">' . wp_kses_post( $summary ) . '</div>';
        $html .= '</div>';

        return $html;
    }


    /**
     * Enqueue frontend scripts and styles
     */
    public function enqueue_frontend_scripts() {
        // Only enqueue on pages that might have summaries
        if ( ! is_singular() ) {
            return;
        }

        $post_id = get_the_ID();
        if ( ! $post_id ) {
            return;
        }

        // Check if post has summary or if auto-append is enabled
        $plugin = Plugin::get_instance();
        $has_summary = $plugin->has_summary( $post_id );
        
        $settings = get_option( 'hdsoft_ai_summary_settings', array() );
        $append_position = isset( $settings['append_position'] ) ? $settings['append_position'] : 'after';
        
        // Only enqueue if there's a summary or auto-append is enabled
        if ( ! $has_summary && 'manual' === $append_position ) {
            return;
        }

        wp_enqueue_style(
            'hdsoft-ai-summary-frontend',
            HDSOFT_AI_SUMMARY_PLUGIN_URL . 'public/css/public.css',
            array(),
            HDSOFT_AI_SUMMARY_VERSION
        );

        // Enqueue JavaScript if needed (for future interactive features)
        wp_enqueue_script(
            'hdsoft-ai-summary-frontend',
            HDSOFT_AI_SUMMARY_PLUGIN_URL . 'public/js/public.js',
            array( 'jquery' ),
            HDSOFT_AI_SUMMARY_VERSION,
            true
        );

        // Localize script for potential AJAX features
        wp_localize_script(
            'hdsoft-ai-summary-frontend',
            'hdsoft_ai_summary_frontend',
            array(
                'ajax_url' => admin_url( 'admin-ajax.php' ),
                'post_id'  => $post_id,
                'nonce'    => wp_create_nonce( 'hdsoft_ai_summary_frontend_nonce' ),
            )
        );
    }

    /**
     * Get summary for template use
     *
     * @param int|WP_Post $post Post ID or object.
     * @param bool        $echo Whether to echo or return.
     * @return string|void
     */
    public static function get_summary( $post = null, $echo = true ) {
        if ( null === $post ) {
            $post = get_the_ID();
        }

        $plugin = Plugin::get_instance();
        $summary = $plugin->get_summary( $post );

        if ( ! $summary ) {
            if ( $echo ) {
                return;
            }
            return '';
        }

        $frontend = new self();
        $output = $frontend->build_summary_html( $summary, is_object( $post ) ? $post->ID : $post );

        if ( $echo ) {
            echo $output; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        } else {
            return $output;
        }
    }

    /**
     * Check if post has summary for template use
     *
     * @param int|WP_Post $post Post ID or object.
     * @return bool
     */
    public static function has_summary( $post = null ) {
        if ( null === $post ) {
            $post = get_the_ID();
        }

        $plugin = Plugin::get_instance();
        return $plugin->has_summary( $post );
    }

    /**
     * Get raw summary text for template use
     *
     * @param int|WP_Post $post Post ID or object.
     * @return string|false
     */
    public static function get_summary_text( $post = null ) {
        if ( null === $post ) {
            $post = get_the_ID();
        }

        $plugin = Plugin::get_instance();
        return $plugin->get_summary( $post );
    }
}
