<?php
/**
 * Main Plugin Class
 *
 * @package HDSofT\AISummary
 */

namespace HDSofT\AISummary;

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

/**
 * Main Plugin Class
 */
class Plugin {

    /**
     * Plugin instance
     *
     * @var Plugin
     */
    private static $instance = null;

    /**
     * OpenRouter API handler
     *
     * @var OpenRouter
     */
    public $openrouter;

    /**
     * Admin functionality
     *
     * @var Admin
     */
    public $admin;

    /**
     * Meta box functionality
     *
     * @var Metabox
     */
    public $metabox;

    /**
     * Frontend functionality
     *
     * @var Frontend
     */
    public $frontend;

    /**
     * REST API functionality
     *
     * @var RestAPI
     */
    public $rest_api;

    /**
     * Get plugin instance
     *
     * @return Plugin
     */
    public static function get_instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     */
    private function __construct() {
        $this->init();
    }

    /**
     * Initialize plugin
     */
    private function init() {
        // Load dependencies
        $this->load_dependencies();

        // Initialize components
        $this->init_components();

        // Setup hooks
        $this->setup_hooks();
    }

    /**
     * Load required files
     */
    private function load_dependencies() {
        require_once HDSOFT_AI_SUMMARY_PLUGIN_DIR . 'includes/class-openrouter.php';
        require_once HDSOFT_AI_SUMMARY_PLUGIN_DIR . 'includes/class-admin.php';
        require_once HDSOFT_AI_SUMMARY_PLUGIN_DIR . 'includes/class-metabox.php';
        require_once HDSOFT_AI_SUMMARY_PLUGIN_DIR . 'includes/class-frontend.php';
        require_once HDSOFT_AI_SUMMARY_PLUGIN_DIR . 'includes/class-rest-api.php';
    }

    /**
     * Initialize components
     */
    private function init_components() {
        $this->openrouter = new OpenRouter();
        $this->admin      = new Admin();
        $this->metabox    = new Metabox();
        $this->frontend   = new Frontend();
        $this->rest_api   = new RestAPI();
    }

    /**
     * Setup WordPress hooks
     */
    private function setup_hooks() {
        // Pro features are loaded via pro/bootstrap.php

        // Add shortcode
        add_shortcode( 'hdsoft_ai_summary', array( $this->frontend, 'shortcode' ) );

        // Content filter for auto-append
        add_filter( 'the_content', array( $this->frontend, 'maybe_append_summary' ), 15 );
    }

    /**
     * Handle post save for auto-generation
     *
     * @param int     $post_id Post ID.
     * @param WP_Post $post    Post object.
     */
    public function handle_post_save( $post_id, $post ) {
        // Skip if this is an autosave
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }

        // Skip if user doesn't have permission to edit this post
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }

        // Skip if this is a revision
        if ( wp_is_post_revision( $post_id ) ) {
            return;
        }

        // Only process published posts
        if ( 'publish' !== $post->post_status ) {
            return;
        }

        // Only process supported post types (posts and pages)
        $supported_post_types = array( 'post', 'page' );
        if ( ! in_array( $post->post_type, $supported_post_types, true ) ) {
            return;
        }

        // Get plugin settings
        $settings = get_option( 'hdsoft_ai_summary_settings', array() );
        
        // Skip if auto-generation is disabled
        if ( empty( $settings['auto_generate'] ) ) {
            return;
        }

        // Check if summary was manually edited
        $is_manual = get_post_meta( $post_id, '_hdsoft_ai_summary_manual', true );
        if ( $is_manual ) {
            return;
        }

        // Generate content hash
        $content_hash = $this->generate_content_hash( $post );
        $stored_hash  = get_post_meta( $post_id, '_hdsoft_ai_summary_hash', true );

        // Skip if content hasn't changed
        if ( $content_hash === $stored_hash ) {
            return;
        }

        // Generate summary
        $this->generate_summary( $post_id, $post, $content_hash );
    }

    /**
     * Generate content hash
     *
     * @param WP_Post $post Post object.
     * @return string
     */
    public function generate_content_hash( $post ) {
        $content = $post->post_title . ' ' . $post->post_content;
        return hash( 'sha256', $content );
    }

    /**
     * Generate summary for a post
     *
     * @param int     $post_id      Post ID.
     * @param WP_Post $post         Post object.
     * @param string  $content_hash Content hash.
     * @return bool|string
     */
    public function generate_summary( $post_id, $post, $content_hash = null ) {
        // Generate hash if not provided
        if ( null === $content_hash ) {
            $content_hash = $this->generate_content_hash( $post );
        }

        // Prepare content for API
        $content = $this->prepare_content_for_api( $post );
        
        if ( empty( $content ) ) {
            return false;
        }

        // Generate summary via OpenRouter
        $result = $this->openrouter->generate_summary( $content );

        if ( is_wp_error( $result ) ) {
            // Log error using WordPress debugging functions
            if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
                error_log( 'HD SofT AI Summary: Failed to generate summary for post ' . $post_id . ': ' . $result->get_error_message() );
            }
            return false;
        }

        // Extract title and summary from result
        $summary_title = isset( $result['title'] ) ? sanitize_text_field( $result['title'] ) : __( 'Summary', 'hd-soft-ai-summary' );
        $summary_text = isset( $result['summary'] ) ? wp_kses_post( $result['summary'] ) : '';

        if ( empty( $summary_text ) ) {
            return false;
        }

        // Store title, summary and hash
        update_post_meta( $post_id, '_hdsoft_ai_summary_title', $summary_title );
        update_post_meta( $post_id, '_hdsoft_ai_summary_text', $summary_text );
        update_post_meta( $post_id, '_hdsoft_ai_summary_hash', $content_hash );
        
        // Reset manual flag since this is auto-generated
        delete_post_meta( $post_id, '_hdsoft_ai_summary_manual' );

        return $summary_text;
    }

    /**
     * Prepare post content for API
     *
     * @param WP_Post $post Post object.
     * @return string
     */
    public function prepare_content_for_api( $post ) {
        // Combine title and content
        $content = $post->post_title . "\n\n" . $post->post_content;

        // Strip HTML tags
        $content = wp_strip_all_tags( $content );

        // Remove extra whitespace
        $content = preg_replace( '/\s+/', ' ', $content );
        $content = trim( $content );

        // Limit content length (OpenRouter has token limits)
        $max_length = 4000;
        if ( strlen( $content ) > $max_length ) {
            $content = substr( $content, 0, $max_length ) . '...';
        }

        return $content;
    }

    /**
     * Get summary for a post
     *
     * @param int|WP_Post $post Post ID or object.
     * @return string|false
     */
    public function get_summary( $post ) {
        $post = get_post( $post );
        if ( ! $post ) {
            return false;
        }

        $summary = get_post_meta( $post->ID, '_hdsoft_ai_summary_text', true );
        
        if ( empty( $summary ) ) {
            return false;
        }

        return $summary;
    }

    /**
     * Get summary title for a post
     *
     * @param int|WP_Post $post Post ID or object.
     * @return string
     */
    public function get_summary_title( $post ) {
        $post = get_post( $post );
        if ( ! $post ) {
            return __( 'Summary', 'hd-soft-ai-summary' );
        }

        $title = get_post_meta( $post->ID, '_hdsoft_ai_summary_title', true );
        
        if ( empty( $title ) ) {
            return __( 'Summary', 'hd-soft-ai-summary' );
        }

        return $title;
    }

    /**
     * Check if post has summary
     *
     * @param int|WP_Post $post Post ID or object.
     * @return bool
     */
    public function has_summary( $post ) {
        $summary = $this->get_summary( $post );
        return ! empty( $summary );
    }

    /**
     * Delete summary for a post
     *
     * @param int $post_id Post ID.
     */
    public function delete_summary( $post_id ) {
        delete_post_meta( $post_id, '_hdsoft_ai_summary_title' );
        delete_post_meta( $post_id, '_hdsoft_ai_summary_text' );
        delete_post_meta( $post_id, '_hdsoft_ai_summary_hash' );
        delete_post_meta( $post_id, '_hdsoft_ai_summary_manual' );
    }

    /**
     * Mark summary as manually edited
     *
     * @param int $post_id Post ID.
     */
    public function mark_as_manual( $post_id ) {
        update_post_meta( $post_id, '_hdsoft_ai_summary_manual', true );
    }

    /**
     * Check if summary was manually edited
     *
     * @param int $post_id Post ID.
     * @return bool
     */
    public function is_manual( $post_id ) {
        return (bool) get_post_meta( $post_id, '_hdsoft_ai_summary_manual', true );
    }
}
