<?php
/**
 * BW Schema Author Box
 *
 * Handles the display of author boxes on the frontend
 *
 * @package BW_AI_Schema_Pro
 * @since 1.0.0
 */

class BW_Schema_Author_Box {
    
    /**
     * Constructor
     */
    public function __construct() {
        // Hook into the content to add author box
        add_filter( 'the_content', array( $this, 'maybe_add_author_box' ), 20 );
        
        // Add shortcode support
        add_shortcode( 'bw_author_box', array( $this, 'render_author_box_shortcode' ) );
        
        // Enqueue frontend styles
        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_frontend_assets' ) );
    }
    
    /**
     * Maybe add author box to post content
     */
    public function maybe_add_author_box( $content ) {
        // Prevent infinite recursion (get_the_excerpt can trigger the_content filter)
        static $is_rendering = false;
        if ( $is_rendering ) {
            return $content;
        }

        // Only on single posts/pages
        if ( ! is_singular() ) {
            return $content;
        }

        global $post;

        // Check if author box is globally enabled
        $author_box_enabled = get_option( 'bw_schema_author_box_enabled', 'yes' );

        // Check if manual placement is selected
        $author_box_position = get_option( 'bw_schema_author_box_position', 'after_content' );
        if ( $author_box_position === 'manual' ) {
            return $content;
        }

        // Check if this post type should show author box by default
        $enabled_post_types = get_option( 'bw_schema_author_box_post_types', array( 'post' ) );
        $show_by_default = ( $author_box_enabled === 'yes' && in_array( $post->post_type, $enabled_post_types, true ) );

        // Get per-post setting (v2.0: 'default', 'show', 'hide' or legacy 'yes', 'no')
        $show_author_box = get_post_meta( $post->ID, '_bw_schema_show_author_box', true );

        // Determine if we should show the author box
        $should_show = false;

        if ( $show_author_box === '' || $show_author_box === 'default' ) {
            // Use default behavior based on global settings
            $should_show = $show_by_default;
        } elseif ( $show_author_box === 'show' || $show_author_box === 'yes' ) {
            // Force show (need global to be enabled)
            $should_show = ( $author_box_enabled === 'yes' );
        } elseif ( $show_author_box === 'hide' || $show_author_box === 'no' ) {
            // Force hide
            $should_show = false;
        }

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

        // Set recursion flag before rendering
        $is_rendering = true;

        // Get the author box HTML
        $author_box = $this->get_author_box_html( $post->ID );

        // Reset recursion flag
        $is_rendering = false;

        // Add based on position setting
        if ( $author_box_position === 'before_content' ) {
            return $author_box . $content;
        } else {
            return $content . $author_box;
        }
    }
    
    /**
     * Get author box HTML
     */
    public function get_author_box_html( $post_id ) {
        $authors = $this->get_post_authors( $post_id );
        
        if ( empty( $authors ) ) {
            return '';
        }
        
        $multiple_class = count( $authors ) > 1 ? ' has-multiple-authors' : '';
        $html = '<div class="bw-author-box-wrapper' . $multiple_class . '">';
        
        foreach ( $authors as $author ) {
            $html .= $this->render_single_author_box( $author );
        }
        
        $html .= '</div>';
        
        return $html;
    }
    
    /**
     * Get authors for a post
     */
    private function get_post_authors( $post_id ) {
        $authors = array();

        // First check for multiple authors (new system)
        $multiple_authors = get_post_meta( $post_id, '_bw_schema_multiple_authors', true );

        if ( ! empty( $multiple_authors ) && is_array( $multiple_authors ) ) {
            $all_custom_authors = get_option( 'bw_schema_custom_authors', array() );
            $external_authors   = get_option( 'bw_schema_external_authors', array() );

            foreach ( $multiple_authors as $author ) {
                if ( empty( $author['type'] ) ) {
                    continue;
                }

                switch ( $author['type'] ) {
                    // v2.0: Team Member Author
                    case 'team_member':
                        if ( ! empty( $author['team_member_id'] ) ) {
                            $team_member = get_post( intval( $author['team_member_id'] ) );
                            if ( $team_member && $team_member->post_status === 'publish' ) {
                                // Get job title from team member
                                $job_title = '';
                                if ( class_exists( 'BW_Schema_Team_Member' ) ) {
                                    $job_title_data = BW_Schema_Team_Member::detect_job_title( $team_member->ID );
                                    $job_title = is_array( $job_title_data ) ? ( $job_title_data['value'] ?? '' ) : $job_title_data;
                                }

                                $authors[] = array(
                                    'type'      => 'team_member',
                                    'id'        => $team_member->ID,
                                    'name'      => $team_member->post_title,
                                    'image'     => get_the_post_thumbnail_url( $team_member, 'thumbnail' ) ?: '',
                                    'bio'       => get_the_excerpt( $team_member ),
                                    'url'       => get_permalink( $team_member ),
                                    'job_title' => $job_title,
                                );
                            }
                        }
                        break;

                    // v2.0: External Author (saved in settings)
                    case 'external_saved':
                        if ( ! empty( $author['external_author_id'] ) ) {
                            $ext_id = $author['external_author_id'];
                            if ( isset( $external_authors[ $ext_id ] ) ) {
                                $ext = $external_authors[ $ext_id ];
                                $authors[] = array(
                                    'type'      => 'external_saved',
                                    'id'        => $ext_id,
                                    'name'      => $ext['name'] ?? '',
                                    'image'     => $ext['image'] ?? '',
                                    'bio'       => $ext['description'] ?? '',
                                    'url'       => $ext['website'] ?? '',
                                    'job_title' => $ext['jobTitle'] ?? '',
                                );
                            }
                        }
                        break;

                    // Legacy: WordPress User
                    case 'wordpress':
                        if ( ! empty( $author['wordpress_user_id'] ) ) {
                            $author_data = get_userdata( $author['wordpress_user_id'] );
                            if ( $author_data ) {
                                // Check if this WP user has a linked team member
                                $linked_team_member = $this->get_team_member_for_user( $author['wordpress_user_id'] );
                                $author_url = $linked_team_member
                                    ? get_permalink( $linked_team_member )
                                    : get_author_posts_url( $author['wordpress_user_id'] );

                                $authors[] = array(
                                    'type'      => 'wordpress',
                                    'id'        => $author['wordpress_user_id'],
                                    'name'      => $author_data->display_name,
                                    'image'     => get_avatar_url( $author['wordpress_user_id'], array( 'size' => 150 ) ),
                                    'bio'       => get_the_author_meta( 'description', $author['wordpress_user_id'] ),
                                    'url'       => $author_url,
                                    'job_title' => '',
                                );
                            }
                        }
                        break;

                    // Legacy: Custom Author
                    case 'custom':
                        if ( ! empty( $author['custom_author_id'] ) ) {
                            // Find author by ID in the array
                            $author_data = null;
                            foreach ( $all_custom_authors as $custom_author ) {
                                if ( isset( $custom_author['id'] ) && $custom_author['id'] == $author['custom_author_id'] ) {
                                    $author_data = $custom_author;
                                    break;
                                }
                            }

                            if ( $author_data ) {
                                // Determine author URL
                                $author_url = '';
                                if ( ! empty( $author_data['teamPageUrl'] ) ) {
                                    $author_url = $author_data['teamPageUrl'];
                                } elseif ( ! empty( $author_data['teamPageId'] ) && $author_data['teamPageId'] !== 'custom' ) {
                                    $author_url = get_permalink( $author_data['teamPageId'] );
                                } elseif ( ! empty( $author_data['social']['website'] ) ) {
                                    $author_url = $author_data['social']['website'];
                                }

                                $authors[] = array(
                                    'type'      => 'custom',
                                    'id'        => $author['custom_author_id'],
                                    'name'      => $author_data['name'],
                                    'image'     => $author_data['image'] ?? '',
                                    'bio'       => $author_data['description'] ?? '',
                                    'url'       => $author_url,
                                    'job_title' => $author_data['jobTitle'] ?? '',
                                );
                            }
                        }
                        break;

                    // External (One-time)
                    case 'external':
                        if ( ! empty( $author['external']['name'] ) ) {
                            $authors[] = array(
                                'type'      => 'external',
                                'id'        => uniqid(),
                                'name'      => $author['external']['name'],
                                'image'     => $author['external']['image'] ?? '',
                                'bio'       => $author['external']['bio'] ?? '',
                                'url'       => $author['external']['website'] ?? '',
                                'job_title' => $author['external']['job_title'] ?? '',
                            );
                        }
                        break;
                }
            }
        }
        
        // Fallback to v2.0 plugin-wide default author
        if ( empty( $authors ) ) {
            $plugin_default = get_option( 'bw_schema_plugin_default_author', array() );
            if ( ! empty( $plugin_default['type'] ) && ! empty( $plugin_default['id'] ) ) {
                if ( $plugin_default['type'] === 'team_member' ) {
                    $team_member = get_post( intval( $plugin_default['id'] ) );
                    if ( $team_member && $team_member->post_status === 'publish' ) {
                        $job_title = '';
                        if ( class_exists( 'BW_Schema_Team_Member' ) ) {
                            $job_title_data = BW_Schema_Team_Member::detect_job_title( $team_member->ID );
                            $job_title = is_array( $job_title_data ) ? ( $job_title_data['value'] ?? '' ) : $job_title_data;
                        }
                        $authors[] = array(
                            'type'      => 'team_member',
                            'id'        => $team_member->ID,
                            'name'      => $team_member->post_title,
                            'image'     => get_the_post_thumbnail_url( $team_member, 'thumbnail' ) ?: '',
                            'bio'       => get_the_excerpt( $team_member ),
                            'url'       => get_permalink( $team_member ),
                            'job_title' => $job_title,
                        );
                    }
                } elseif ( $plugin_default['type'] === 'external' ) {
                    $external_authors = get_option( 'bw_schema_external_authors', array() );
                    $ext_id = $plugin_default['id'];
                    if ( isset( $external_authors[ $ext_id ] ) ) {
                        $ext = $external_authors[ $ext_id ];
                        $authors[] = array(
                            'type'      => 'external_saved',
                            'id'        => $ext_id,
                            'name'      => $ext['name'] ?? '',
                            'image'     => $ext['image'] ?? '',
                            'bio'       => $ext['description'] ?? '',
                            'url'       => $ext['website'] ?? '',
                            'job_title' => $ext['jobTitle'] ?? '',
                        );
                    }
                }
            }
        }

        // Legacy fallback: single custom author or default author
        if ( empty( $authors ) ) {
            $use_custom_authors = get_option( 'bw_schema_use_custom_authors', 'no' );
            $custom_author_id = get_post_meta( $post_id, '_bw_schema_custom_author', true );

            if ( $use_custom_authors === 'yes' ) {
                $all_custom_authors = get_option( 'bw_schema_custom_authors', array() );

                // If no specific author is set, find the default author
                if ( ! $custom_author_id ) {
                    foreach ( $all_custom_authors as $author ) {
                        if ( ! empty( $author['isDefault'] ) && $author['isDefault'] === true ) {
                            $custom_author_id = $author['id'];
                            break;
                        }
                    }
                }

                // Find author by ID in the array
                $author_data = null;
                if ( $custom_author_id ) {
                    foreach ( $all_custom_authors as $author ) {
                        if ( isset( $author['id'] ) && $author['id'] == $custom_author_id ) {
                            $author_data = $author;
                            break;
                        }
                    }
                }

                if ( $author_data ) {
                    // Determine author URL
                    $author_url = '';
                    if ( ! empty( $author_data['teamPageUrl'] ) ) {
                        $author_url = $author_data['teamPageUrl'];
                    } elseif ( ! empty( $author_data['teamPageId'] ) && $author_data['teamPageId'] !== 'custom' ) {
                        $author_url = get_permalink( $author_data['teamPageId'] );
                    } elseif ( ! empty( $author_data['social']['website'] ) ) {
                        $author_url = $author_data['social']['website'];
                    }

                    $authors[] = array(
                        'type'      => 'custom',
                        'id'        => $custom_author_id,
                        'name'      => $author_data['name'],
                        'image'     => $author_data['image'] ?? '',
                        'bio'       => $author_data['description'] ?? '',
                        'url'       => $author_url,
                        'job_title' => $author_data['jobTitle'] ?? '',
                    );
                }
            }
        }

        // Final fallback to WordPress post author (with team member link if available)
        if ( empty( $authors ) ) {
            $post = get_post( $post_id );
            $author_id = $post->post_author;
            $author_data = get_userdata( $author_id );

            if ( $author_data ) {
                // Check if this WP user has a linked team member
                $linked_team_member = $this->get_team_member_for_user( $author_id );
                $author_url = $linked_team_member
                    ? get_permalink( $linked_team_member )
                    : get_author_posts_url( $author_id );

                $authors[] = array(
                    'type'      => 'wordpress',
                    'id'        => $author_id,
                    'name'      => $author_data->display_name,
                    'image'     => get_avatar_url( $author_id, array( 'size' => 150 ) ),
                    'bio'       => get_the_author_meta( 'description', $author_id ),
                    'url'       => $author_url,
                    'job_title' => '',
                );
            }
        }

        return $authors;
    }

    /**
     * Get team member ID linked to a WordPress user
     *
     * @param int $user_id WordPress user ID
     * @return int|null Team member post ID or null if not found
     */
    private function get_team_member_for_user( $user_id ) {
        if ( ! class_exists( 'BW_Schema_Team_Member' ) ) {
            return null;
        }

        $team_post_type = BW_Schema_Team_Member::get_team_post_type();
        if ( ! $team_post_type ) {
            return null;
        }

        $team_members = get_posts( array(
            'post_type'      => $team_post_type,
            'posts_per_page' => 1,
            'meta_query'     => array(
                array(
                    'key'   => '_bw_schema_linked_user',
                    'value' => $user_id,
                ),
            ),
        ) );

        return ! empty( $team_members ) ? $team_members[0]->ID : null;
    }
    
    /**
     * Render single author box (simplified design v2.0)
     */
    private function render_single_author_box( $author ) {
        $html = '<div class="bw-author-box">';

        // Author image (smaller, cleaner)
        $html .= '<div class="bw-author-image">';
        if ( ! empty( $author['image'] ) ) {
            $html .= '<img src="' . esc_url( $author['image'] ) . '" alt="' . esc_attr( $author['name'] ) . '">';
        } else {
            // Default avatar placeholder
            $html .= '<div class="bw-author-avatar-placeholder">' . esc_html( strtoupper( substr( $author['name'], 0, 1 ) ) ) . '</div>';
        }
        $html .= '</div>';

        // Author info (simplified)
        $html .= '<div class="bw-author-info">';

        // Name with optional link + job title on same line
        $html .= '<div class="bw-author-name">';
        $name_html = esc_html( $author['name'] );
        if ( ! empty( $author['url'] ) ) {
            // For team members, link opens in same window; for external, new tab
            $is_internal = in_array( $author['type'] ?? '', array( 'team_member', 'wordpress', 'custom' ), true );
            $target = $is_internal ? '' : ' target="_blank" rel="noopener noreferrer"';
            $name_html = '<a href="' . esc_url( $author['url'] ) . '"' . $target . '>' . esc_html( $author['name'] ) . '</a>';
        }
        $html .= $name_html;
        if ( ! empty( $author['job_title'] ) ) {
            $html .= '<span class="bw-author-title">' . esc_html( $author['job_title'] ) . '</span>';
        }
        $html .= '</div>';

        $html .= '</div>'; // .bw-author-info
        $html .= '</div>'; // .bw-author-box

        return $html;
    }
    
    /**
     * Render author box shortcode
     */
    public function render_author_box_shortcode( $atts ) {
        $atts = shortcode_atts( array(
            'post_id' => get_the_ID(),
            'author_ids' => '' // Comma-separated custom author IDs
        ), $atts );
        
        if ( ! empty( $atts['author_ids'] ) ) {
            // Override authors for this specific shortcode
            $author_ids = array_map( 'trim', explode( ',', $atts['author_ids'] ) );
            $authors = array();
            $all_custom_authors = get_option( 'bw_schema_custom_authors', array() );
            
            foreach ( $author_ids as $author_id ) {
                // Find author by ID in the array
                $author_data = null;
                foreach ( $all_custom_authors as $custom_author ) {
                    if ( isset( $custom_author['id'] ) && $custom_author['id'] == $author_id ) {
                        $author_data = $custom_author;
                        break;
                    }
                }
                
                if ( $author_data ) {
                    // Determine author URL
                    $author_url = '';
                    if ( ! empty( $author_data['teamPageUrl'] ) ) {
                        $author_url = $author_data['teamPageUrl'];
                    } elseif ( ! empty( $author_data['teamPageId'] ) && $author_data['teamPageId'] !== 'custom' ) {
                        $author_url = get_permalink( $author_data['teamPageId'] );
                    } elseif ( ! empty( $author_data['social']['website'] ) ) {
                        $author_url = $author_data['social']['website'];
                    }
                    
                    $authors[] = array(
                        'type' => 'custom',
                        'id' => $author_id,
                        'name' => $author_data['name'],
                        'image' => $author_data['image'] ?? '',
                        'bio' => $author_data['description'] ?? '',
                        'url' => $author_url,
                        'job_title' => $author_data['jobTitle'] ?? ''
                    );
                }
            }
            
            if ( ! empty( $authors ) ) {
                $html = '<div class="bw-author-box-wrapper bw-author-box-shortcode">';
                foreach ( $authors as $author ) {
                    $html .= $this->render_single_author_box( $author );
                }
                $html .= '</div>';
                return $html;
            }
        }
        
        return $this->get_author_box_html( $atts['post_id'] );
    }
    
    /**
     * Enqueue frontend assets
     */
    public function enqueue_frontend_assets() {
        if ( is_singular() ) {
            wp_enqueue_style( 
                'bw-schema-author-box', 
                plugin_dir_url( dirname( __FILE__ ) ) . 'assets/css/author-box.css',
                array(),
                '1.0.0'
            );
        }
    }
}

// Initialize
new BW_Schema_Author_Box();