<?php

/**
 * The template for displaying single person (Cast & Crew) pages
 *
 * This template can be overridden by copying it to yourtheme/movie-engine/single-person.php.
 *
 * HOWEVER, on occasion MovieEngine will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 * @note Please do not delete our CSS classes when you customize, as it may break functionality.
 * @package Movie_Engine
 * @subpackage Movie_Engine/templates
 * @version 1.0.0
 */

if (! defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

get_header();

$movie_engine_design_settings = get_option('movie_engine_design_settings', []);
$movie_engine_container_type = $movie_engine_design_settings['movie_container_type'] ?? 'container';
$movie_engine_container_class = 'movie-engine-container-fluid';

$movie_engine_person_id = get_the_ID();
$movie_engine_name = get_the_title();
$movie_engine_photo_url = get_the_post_thumbnail_url($movie_engine_person_id, 'large');
$movie_engine_birthday = get_post_meta($movie_engine_person_id, '_movie_engine_birthday', true);
$movie_engine_place_of_birth = get_post_meta($movie_engine_person_id, '_movie_engine_place_of_birth', true);
$movie_engine_known_for = get_post_meta($movie_engine_person_id, '_movie_engine_known_for', true);
$movie_engine_gender_id = get_post_meta($movie_engine_person_id, '_movie_engine_gender', true);
$movie_engine_social_links = get_post_meta($movie_engine_person_id, '_movie_engine_social_links', true);
if (!is_array($movie_engine_social_links)) $movie_engine_social_links = [];
$movie_engine_aka = get_post_meta($movie_engine_person_id, '_movie_engine_also_known_as', true);

$movie_engine_gender = '';
if ($movie_engine_gender_id == 1) $movie_engine_gender = esc_html__('Female', 'cine-movie-engine');
elseif ($movie_engine_gender_id == 2) $movie_engine_gender = esc_html__('Male', 'cine-movie-engine');
elseif ($movie_engine_gender_id == 3) $movie_engine_gender = esc_html__('Non-binary', 'cine-movie-engine');

$movie_engine_social_icons = [
    'twitter'   => 'fa-brands fa-twitter',
    'instagram' => 'fa-brands fa-instagram',
    'facebook'  => 'fa-brands fa-facebook',
    'tiktok'    => 'fa-brands fa-tiktok',
    'youtube'   => 'fa-brands fa-youtube',
    'link'      => 'fa-solid fa-link',
];

$movie_engine_social_bases = [
    'twitter'   => 'https://twitter.com/',
    'instagram' => 'https://instagram.com/',
    'facebook'  => 'https://facebook.com/',
    'tiktok'    => 'https://tiktok.com/@',
    'youtube'   => 'https://youtube.com/',
];

$movie_engine_age_text = '';
if ($movie_engine_birthday) {
    try {
        $movie_engine_birthDate = new DateTime($movie_engine_birthday);
        $movie_engine_today = new DateTime('today');
        $movie_engine_age = $movie_engine_birthDate->diff($movie_engine_today)->y;
        $movie_engine_age_text = sprintf(' (%d years old)', $movie_engine_age);
        $movie_engine_formatted_birthday = date_i18n(get_option('date_format'), strtotime($movie_engine_birthday));
    } catch (Exception $e) {
        $movie_engine_formatted_birthday = $movie_engine_birthday;
    }
}

$movie_engine_args = [
    'post_type'      => ['movie_engine_movie', 'movie_engine_series'],
    'posts_per_page' => -1,
    'no_found_rows'  => true,
    // phpcs:ignore WordPress.DB.SlowDBQuery
    'meta_query'     => [
        [
            'key'     => '_movie_engine_cast',
            'value'   => '"id";i:' . $movie_engine_person_id . ';',
            'compare' => 'LIKE',
        ],
    ],
];

$movie_engine_related_query = new WP_Query($movie_engine_args);

if (!$movie_engine_related_query->have_posts()) {
    $movie_engine_args_crew = [
        'post_type'      => ['movie_engine_movie', 'movie_engine_series'],
        'posts_per_page' => -1,
        'no_found_rows'  => true,
        // phpcs:ignore WordPress.DB.SlowDBQuery
        'meta_query' => [
            [
                'key'     => '_movie_engine_crew',
                'value'   => '"id";i:' . $movie_engine_person_id . ';',
                'compare' => 'LIKE',
            ],
        ],
    ];
    $movie_engine_related_query = new WP_Query($movie_engine_args_crew);
}

if (!$movie_engine_related_query->have_posts()) {
    $movie_engine_args_fallback = [
        'post_type'      => ['movie_engine_movie', 'movie_engine_series'],
        'no_found_rows'  => true,
        'posts_per_page' => 24,
        // phpcs:ignore WordPress.DB.SlowDBQuery
        'tax_query' => [
            'relation' => 'OR',
            [
                'taxonomy' => 'movie_engine_actor',
                'field'    => 'name',
                'terms'    => $movie_engine_name,
            ],
            [
                'taxonomy' => 'movie_engine_director',
                'field'    => 'name',
                'terms'    => $movie_engine_name,
            ],
            [
                'taxonomy' => 'movie_engine_creator',
                'field'    => 'name',
                'terms'    => $movie_engine_name,
            ],
        ],
    ];
    $movie_engine_related_query = new WP_Query($movie_engine_args_fallback);
}

?>

<div class="movie-engine-single-person-wrapper movie-engine-plugin">
    <div class="<?php echo esc_attr($movie_engine_container_class); ?> me-py-10">

        <div class="me-person-main-grid">
            <div class="me-person-sidebar">
                <div class="me-person-photo-card">
                    <?php if ($movie_engine_photo_url) : ?>
                        <img src="<?php echo esc_url($movie_engine_photo_url); ?>" alt="<?php echo esc_attr($movie_engine_name); ?>">
                    <?php else : ?>
                        <div class="me-no-photo-placeholder">
                            <span class="dashicons dashicons-admin-users"></span>
                        </div>
                    <?php endif; ?>
                </div>
                <div class="me-person-socials me-mt-3">
                    <?php
                    foreach ($movie_engine_social_links as $movie_engine_link) :
                        $movie_engine_platform = $movie_engine_link['platform'];
                        $movie_engine_url = $movie_engine_link['url'];
                        $movie_engine_icon = $movie_engine_social_icons[$movie_engine_platform] ?? 'fa-solid fa-link';

                        if (!preg_match('~^(?:f|ht)tps?://~i', $movie_engine_url) && isset($movie_engine_social_bases[$movie_engine_platform])) {
                            $movie_engine_url = $movie_engine_social_bases[$movie_engine_platform] . ltrim($movie_engine_url, '@');
                        }
                    ?>
                        <a href="<?php echo esc_url($movie_engine_url); ?>" target="_blank" class="me-social-link"><span class="<?php echo esc_attr($movie_engine_icon); ?>"></span></a>
                    <?php endforeach; ?>
                </div>
                <div class="me-person-details-box me-mt-5">
                    <h3 class="me-details-title"><?php esc_html_e('Personal Info', 'cine-movie-engine'); ?></h3>

                    <div class="me-details-item me-mt-4">
                        <span class="me-details-label"><?php esc_html_e('Known For', 'cine-movie-engine'); ?></span>
                        <span class="me-details-value"><?php echo esc_html($movie_engine_known_for ?: 'Acting'); ?></span>
                    </div>

                    <?php if ($movie_engine_gender) : ?>
                        <div class="me-details-item me-mt-4">
                            <span class="me-details-label"><?php esc_html_e('Gender', 'cine-movie-engine'); ?></span>
                            <span class="me-details-value"><?php echo esc_html($movie_engine_gender); ?></span>
                        </div>
                    <?php endif; ?>

                    <?php if ($movie_engine_birthday) : ?>
                        <div class="me-details-item me-mt-4">
                            <span class="me-details-label"><?php esc_html_e('Birthday', 'cine-movie-engine'); ?></span>
                            <span class="me-details-value"><?php echo esc_html($movie_engine_formatted_birthday . $movie_engine_age_text); ?></span>
                        </div>
                    <?php endif; ?>

                    <?php if ($movie_engine_place_of_birth) : ?>
                        <div class="me-details-item me-mt-4">
                            <span class="me-details-label"><?php esc_html_e('Place of Birth', 'cine-movie-engine'); ?></span>
                            <span class="me-details-value"><?php echo esc_html($movie_engine_place_of_birth); ?></span>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($movie_engine_aka) && is_array($movie_engine_aka)) : ?>
                        <div class="me-details-item me-mt-4">
                            <span class="me-details-label"><?php esc_html_e('Also Known As', 'cine-movie-engine'); ?></span>
                            <div class="me-details-aka-list">
                                <?php foreach ($movie_engine_aka as $movie_engine_name_aka) : ?>
                                    <span class="me-details-value me-block"><?php echo esc_html($movie_engine_name_aka); ?></span>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <div class="me-person-content">
                <h1 class="me-person-name"><?php echo esc_html($movie_engine_name); ?></h1>

                <?php if ($movie_engine_known_for) : ?>
                    <div class="me-person-department"><?php echo esc_html($movie_engine_known_for); ?></div>
                <?php endif; ?>

                <div class="me-person-biography-wrapper me-mt-3">
                    <div class="me-person-biography" id="person-bio">
                        <?php if (get_the_content()) : ?>
                            <?php the_content(); ?>
                        <?php else : ?>
                            <p class="me-empty-bio">
                                <?php
                                /* translators: %s: person name */
                                echo sprintf(esc_html__('%s is a talented individual in the entertainment industry, contributing to various projects across film and television.', 'cine-movie-engine'), esc_html($movie_engine_name));
                                ?>
                            </p>
                        <?php endif; ?>
                    </div>
                    <button id="me-read-more-btn" class="me-read-more-btn" style="display: none;" data-read-more="<?php esc_attr_e('Read More', 'cine-movie-engine'); ?>" data-read-less="<?php esc_attr_e('Read Less', 'cine-movie-engine'); ?>"><?php esc_html_e('Read More', 'cine-movie-engine'); ?></button>
                </div>

                <div class="me-person-history-section me-mt-5">
                    <h2 class="me-title"><?php esc_html_e('Person History', 'cine-movie-engine'); ?></h2>

                    <div class="me-history-tabs me-mt-3">
                        <button class="me-tab-btn active" data-filter="all"><?php esc_html_e('All', 'cine-movie-engine'); ?></button>
                        <button class="me-tab-btn" data-filter="movie"><?php esc_html_e('Movies', 'cine-movie-engine'); ?></button>
                        <button class="me-tab-btn" data-filter="tv"><?php esc_html_e('TV Shows', 'cine-movie-engine'); ?></button>
                    </div>

                    <div class="me-person-filmography-grid me-mt-8">
                        <?php if ($movie_engine_related_query->have_posts()) : ?>
                            <?php while ($movie_engine_related_query->have_posts()) : $movie_engine_related_query->the_post();
                                $movie_engine_type = get_post_type();
                                $movie_engine_type_class = ($movie_engine_type === 'movie_engine_series') ? 'tv' : 'movie';
                                $movie_engine_item_poster = get_the_post_thumbnail_url(get_the_ID(), 'medium');
                                $movie_engine_release_date = get_post_meta(get_the_ID(), '_movie_engine_release_date', true);
                                $movie_engine_year = !empty($movie_engine_release_date) ? gmdate('Y', strtotime($movie_engine_release_date)) : '';
                            ?>
                                <div class="me-person-history-card" data-type="<?php echo esc_attr($movie_engine_type_class); ?>">
                                    <a href="<?php the_permalink(); ?>" class="me-history-card-link">
                                        <div class="me-history-card-poster">
                                            <?php if ($movie_engine_item_poster) : ?>
                                                <img src="<?php echo esc_url($movie_engine_item_poster); ?>" alt="<?php the_title_attribute(); ?>">
                                            <?php endif; ?>
                                        </div>
                                        <div class="me-history-card-info">
                                            <div class="me-info-inner">
                                                <h4 class="me-history-item-title"><?php the_title(); ?></h4>
                                                <?php if ($movie_engine_year) : ?>
                                                    <span class="me-history-item-year"><?php echo esc_html($movie_engine_year); ?></span>
                                                <?php endif; ?>
                                                <?php
                                                $movie_engine_movie_cast = get_post_meta(get_the_ID(), '_movie_engine_cast', true);
                                                $movie_engine_character = '';
                                                if (!empty($movie_engine_movie_cast) && is_array($movie_engine_movie_cast)) {
                                                    foreach ($movie_engine_movie_cast as $movie_engine_actor) {
                                                        if (isset($movie_engine_actor['id']) && $movie_engine_actor['id'] == $movie_engine_person_id) {
                                                            $movie_engine_character = $movie_engine_actor['character'] ?? '';
                                                            break;
                                                        }
                                                    }
                                                }
                                                if ($movie_engine_character) : ?>
                                                    <span class="me-history-item-character"><?php echo esc_html($movie_engine_character); ?></span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </a>
                                </div>
                            <?php endwhile;
                            wp_reset_postdata(); ?>
                        <?php else : ?>
                            <div class="me-no-results">
                                <p><?php esc_html_e('No history found for this person.', 'cine-movie-engine'); ?></p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php
get_footer();
