<?php
/**
 * Meta Box Functionality
 *
 * @package HDSofT\AISummary
 */

namespace HDSofT\AISummary;

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

/**
 * Metabox Class
 */
class Metabox {

    /**
     * Constructor
     */
    public function __construct() {
        add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
        add_action( 'save_post', array( $this, 'save_meta_box' ), 10, 2 );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_metabox_scripts' ) );
        add_action( 'wp_ajax_hdsoft_ai_summary_generate', array( $this, 'ajax_generate_summary' ) );
        add_action( 'wp_ajax_hdsoft_ai_summary_fetch', array( $this, 'ajax_fetch_summary' ) );
    }

    /**
     * Add meta boxes
     */
    public function add_meta_boxes() {
        $supported_post_types = array( 'post', 'page' );

        foreach ( $supported_post_types as $post_type ) {
            add_meta_box(
                'hdsoft-ai-summary-metabox',
                __( 'AI Summary', 'hd-soft-ai-summary' ),
                array( $this, 'render_meta_box' ),
                $post_type,
                'side',
                'default'
            );
        }
    }

    /**
     * Render meta box
     *
     * @param WP_Post $post Current post object.
     */
    public function render_meta_box( $post ) {
        // Add nonce field
        wp_nonce_field( 'hdsoft_ai_summary_metabox', 'hdsoft_ai_summary_metabox_nonce' );

        $plugin = Plugin::get_instance();
        $title = get_post_meta( $post->ID, '_hdsoft_ai_summary_title', true );
        $summary = get_post_meta( $post->ID, '_hdsoft_ai_summary_text', true );
        $is_manual = get_post_meta( $post->ID, '_hdsoft_ai_summary_manual', true );
        $hash = get_post_meta( $post->ID, '_hdsoft_ai_summary_hash', true );

        // Check if content has changed
        $current_hash = $plugin->generate_content_hash( $post );
        $content_changed = $hash !== $current_hash;

        // Get settings
        $settings = get_option( 'hdsoft_ai_summary_settings', array() );
        $api_key = get_option( 'hdsoft_ai_summary_openrouter_api_key' );
        $has_api_key = ! empty( $api_key );
        ?>

        <div class="hdsoft-ai-summary-metabox">
            <?php if ( ! $has_api_key ) : ?>
                <div class="hdsoft-notice notice-warning">
                    <p><?php esc_html_e( 'OpenRouter API key is not configured.', 'hd-soft-ai-summary' ); ?></p>
                    <p><a href="<?php echo esc_url( admin_url( 'options-general.php?page=hd-soft-ai-summary' ) ); ?>"><?php esc_html_e( 'Configure API key', 'hd-soft-ai-summary' ); ?></a></p>
                </div>
            <?php endif; ?>

            <div class="hdsoft-summary-field">
                <label for="hdsoft_ai_summary_title">
                    <?php esc_html_e( 'Title:', 'hd-soft-ai-summary' ); ?>
                </label>
                <input 
                    type="text" 
                    id="hdsoft_ai_summary_title" 
                    name="hdsoft_ai_summary_title" 
                    value="<?php echo esc_attr( $title ); ?>"
                    class="widefat"
                    placeholder="<?php esc_attr_e( 'Auto-generated title (e.g., Summary, Tiivistelmä)', 'hd-soft-ai-summary' ); ?>"
                />
                <p class="description">
                    <?php esc_html_e( 'Title for the summary section. Generated automatically based on content language.', 'hd-soft-ai-summary' ); ?>
                </p>
            </div>

            <div class="hdsoft-summary-field">
                <label for="hdsoft_ai_summary_text">
                    <?php esc_html_e( 'Summary:', 'hd-soft-ai-summary' ); ?>
                </label>
                <textarea 
                    id="hdsoft_ai_summary_text" 
                    name="hdsoft_ai_summary_text" 
                    rows="6" 
                    class="widefat"
                    placeholder="<?php esc_attr_e( 'AI-generated summary will appear here...', 'hd-soft-ai-summary' ); ?>"
                ><?php echo esc_textarea( $summary ); ?></textarea>
                
                <p class="description">
                    <?php esc_html_e( 'You can edit this summary manually. Manual edits will not be overwritten by auto-generation.', 'hd-soft-ai-summary' ); ?>
                </p>
            </div>

            <div class="hdsoft-summary-actions">
                <?php if ( $has_api_key ) : ?>
                    <button type="button" id="hdsoft-generate-summary" class="button button-secondary" <?php disabled( ! $has_api_key ); ?>>
                        <span class="dashicons dashicons-update"></span>
                        <?php esc_html_e( 'Generate Summary', 'hd-soft-ai-summary' ); ?>
                    </button>
                <?php endif; ?>

            </div>

            <div class="hdsoft-summary-status">
                <?php if ( $is_manual ) : ?>
                    <p class="hdsoft-status-manual">
                        <span class="dashicons dashicons-edit"></span>
                        <?php esc_html_e( 'Manually edited', 'hd-soft-ai-summary' ); ?>
                    </p>
                <?php elseif ( ! empty( $summary ) ) : ?>
                    <p class="hdsoft-status-auto">
                        <span class="dashicons dashicons-robot"></span>
                        <?php esc_html_e( 'Auto-generated', 'hd-soft-ai-summary' ); ?>
                        <?php if ( $content_changed ) : ?>
                            <br><small class="hdsoft-content-changed">
                                <?php esc_html_e( 'Content has changed since last generation', 'hd-soft-ai-summary' ); ?>
                            </small>
                        <?php endif; ?>
                    </p>
                <?php endif; ?>
            </div>

            <div id="hdsoft-summary-result" class="hdsoft-result" style="display: none;"></div>

            <!-- Hidden fields -->
            <input type="hidden" id="hdsoft_ai_summary_manual" name="hdsoft_ai_summary_manual" value="<?php echo esc_attr( $is_manual ? '1' : '0' ); ?>" />
            <input type="hidden" id="hdsoft_post_id" value="<?php echo esc_attr( $post->ID ); ?>" />
        </div>

        <style>
        .hdsoft-ai-summary-metabox {
            margin: -6px -12px -12px;
            padding: 12px;
        }

        .hdsoft-summary-field {
            margin-bottom: 15px;
        }

        .hdsoft-summary-field label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
        }

        .hdsoft-summary-field textarea {
            resize: vertical;
            min-height: 100px;
        }

        .hdsoft-summary-actions {
            margin-bottom: 15px;
        }

        .hdsoft-summary-actions .button {
            margin-right: 10px;
        }

        .hdsoft-summary-actions .dashicons {
            margin-right: 5px;
            vertical-align: middle;
        }

        .hdsoft-summary-status p {
            margin: 0;
            padding: 8px;
            border-radius: 4px;
            font-size: 13px;
        }

        .hdsoft-status-manual {
            background: #e7f3ff;
            border: 1px solid #72aee6;
            color: #0073aa;
        }

        .hdsoft-status-auto {
            background: #f0f6fc;
            border: 1px solid #8c8f94;
            color: #50575e;
        }

        .hdsoft-content-changed {
            color: #d63638;
            font-style: italic;
        }

        .hdsoft-result {
            margin-top: 10px;
            padding: 8px 12px;
            border-radius: 4px;
            font-weight: 600;
        }

        .hdsoft-result.success {
            background: #d1e7dd;
            border: 1px solid #badbcc;
            color: #0f5132;
        }

        .hdsoft-result.error {
            background: #f8d7da;
            border: 1px solid #f5c2c7;
            color: #842029;
        }

        .hdsoft-notice {
            padding: 8px 12px;
            margin-bottom: 15px;
            border-radius: 4px;
            border-left: 4px solid;
        }

        .hdsoft-notice.notice-warning {
            background: #fff3cd;
            border-left-color: #856404;
            color: #856404;
        }

        .hdsoft-notice p {
            margin: 5px 0;
        }

        .hdsoft-loading {
            opacity: 0.6;
            pointer-events: none;
        }
        </style>
        <?php
    }

    /**
     * Save meta box data
     *
     * @param int     $post_id Post ID.
     * @param WP_Post $post    Post object.
     */
    public function save_meta_box( $post_id, $post ) {
        // Verify nonce
        if ( ! isset( $_POST['hdsoft_ai_summary_metabox_nonce'] ) || 
             ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['hdsoft_ai_summary_metabox_nonce'] ) ), 'hdsoft_ai_summary_metabox' ) ) {
            return;
        }

        // Check if user has permission to edit this post
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }

        // Skip if this is an autosave
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }

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

        $plugin = Plugin::get_instance();

        // Check if this is a manual edit or auto-generated
        $is_manual = isset( $_POST['hdsoft_ai_summary_manual'] ) && (bool) sanitize_text_field( wp_unslash( $_POST['hdsoft_ai_summary_manual'] ) );

        // Only save title and summary from POST if this is a manual edit
        if ( $is_manual ) {
            // Handle title field
            if ( isset( $_POST['hdsoft_ai_summary_title'] ) ) {
                $title = sanitize_text_field( wp_unslash( $_POST['hdsoft_ai_summary_title'] ) );
                if ( ! empty( $title ) ) {
                    update_post_meta( $post_id, '_hdsoft_ai_summary_title', $title );
                } else {
                    delete_post_meta( $post_id, '_hdsoft_ai_summary_title' );
                }
            }

            // Handle summary text - use wp_kses_post to allow light HTML like AI generates
            if ( isset( $_POST['hdsoft_ai_summary_text'] ) ) {
                $summary = wp_kses_post( wp_unslash( $_POST['hdsoft_ai_summary_text'] ) );
                
                if ( ! empty( $summary ) ) {
                    update_post_meta( $post_id, '_hdsoft_ai_summary_text', $summary );
                } else {
                    // If summary is empty, delete all related meta
                    $plugin->delete_summary( $post_id );
                }
            }
        }

        // Always handle manual flag
        if ( isset( $_POST['hdsoft_ai_summary_manual'] ) ) {
            if ( $is_manual ) {
                update_post_meta( $post_id, '_hdsoft_ai_summary_manual', true );
            } else {
                delete_post_meta( $post_id, '_hdsoft_ai_summary_manual' );
            }
        }
    }

    /**
     * Enqueue metabox scripts
     *
     * @param string $hook Current admin page hook.
     */
    public function enqueue_metabox_scripts( $hook ) {
        if ( ! in_array( $hook, array( 'post.php', 'post-new.php' ), true ) ) {
            return;
        }

        $screen = get_current_screen();
        $supported_post_types = array( 'post', 'page' );

        if ( ! $screen || ! in_array( $screen->post_type, $supported_post_types, true ) ) {
            return;
        }

        wp_enqueue_script(
            'hdsoft-ai-summary-metabox',
            HDSOFT_AI_SUMMARY_PLUGIN_URL . 'admin/js/metabox.js',
            array( 'jquery' ),
            HDSOFT_AI_SUMMARY_VERSION,
            true
        );

        wp_localize_script(
            'hdsoft-ai-summary-metabox',
            'hdsoft_ai_summary_metabox',
            array(
                'ajax_url' => admin_url( 'admin-ajax.php' ),
                'nonce'    => wp_create_nonce( 'hdsoft_ai_summary_metabox_nonce' ),
                'strings'  => array(
                    'generating'     => __( 'Generating...', 'hd-soft-ai-summary' ),
                    'generate'       => __( 'Generate Summary', 'hd-soft-ai-summary' ),
                    'success'        => __( 'Summary generated successfully!', 'hd-soft-ai-summary' ),
                    'error'          => __( 'Error:', 'hd-soft-ai-summary' ),
                    'confirm_clear'  => __( 'Are you sure you want to clear the summary?', 'hd-soft-ai-summary' ),
                    'confirm_regenerate' => __( 'This will replace the current summary. Continue?', 'hd-soft-ai-summary' ),
                ),
            )
        );
    }

    /**
     * AJAX generate summary
     */
    public function ajax_generate_summary() {
        check_ajax_referer( 'hdsoft_ai_summary_metabox_nonce', 'nonce' );

        $post_id = intval( $_POST['post_id'] ?? 0 );
        
        if ( ! $post_id || ! current_user_can( 'edit_post', $post_id ) ) {
            wp_send_json_error( array(
                'message' => __( 'Invalid post ID or insufficient permissions.', 'hd-soft-ai-summary' ),
            ) );
        }

        $post = get_post( $post_id );
        if ( ! $post ) {
            wp_send_json_error( array(
                'message' => __( 'Post not found.', 'hd-soft-ai-summary' ),
            ) );
        }

        $plugin = Plugin::get_instance();

        // Prepare content for API
        $content = $plugin->prepare_content_for_api( $post );
        
        if ( empty( $content ) ) {
            wp_send_json_error( array(
                'message' => __( 'No content to summarize.', 'hd-soft-ai-summary' ),
            ) );
        }

        // Generate summary via OpenRouter directly to get structured response
        $result = $plugin->openrouter->generate_summary( $content );

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array(
                'message' => $result->get_error_message(),
            ) );
        }

        // 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 ) ) {
            wp_send_json_error( array(
                'message' => __( 'Generated summary is empty.', 'hd-soft-ai-summary' ),
            ) );
        }

        // Store both title and summary
        $content_hash = $plugin->generate_content_hash( $post );
        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 );
        
        // Mark as not manual since this was generated via button
        delete_post_meta( $post_id, '_hdsoft_ai_summary_manual' );

        wp_send_json_success( array(
            'title'   => $summary_title,
            'summary' => $summary_text,
            'hash'    => $content_hash,
        ) );
    }

    /**
     * AJAX fetch summary data
     */
    public function ajax_fetch_summary() {
        check_ajax_referer( 'hdsoft_ai_summary_metabox_nonce', 'nonce' );

        $post_id = intval( $_POST['post_id'] ?? 0 );
        
        if ( ! $post_id || ! current_user_can( 'edit_post', $post_id ) ) {
            wp_send_json_error( array(
                'message' => __( 'Invalid post ID or insufficient permissions.', 'hd-soft-ai-summary' ),
            ) );
        }

        $post = get_post( $post_id );
        if ( ! $post ) {
            wp_send_json_error( array(
                'message' => __( 'Post not found.', 'hd-soft-ai-summary' ),
            ) );
        }

        // Get current meta values
        $title = get_post_meta( $post_id, '_hdsoft_ai_summary_title', true );
        $summary = get_post_meta( $post_id, '_hdsoft_ai_summary_text', true );
        $is_manual = get_post_meta( $post_id, '_hdsoft_ai_summary_manual', true );
        $hash = get_post_meta( $post_id, '_hdsoft_ai_summary_hash', true );

        wp_send_json_success( array(
            'title'     => $title ?: '',
            'summary'   => $summary ?: '',
            'is_manual' => (bool) $is_manual,
            'hash'      => $hash ?: '',
        ) );
    }
}
