<?php

namespace MovieEngine\Admin;

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

use MovieEngine\Api\TmdbClient;
use MovieEngine\Api\OmdbClient;

class TmdbImport {

    private $tmdb;

    public function __construct() {
        $this->tmdb = new TmdbClient();

        add_action('wp_ajax_movie_engine_search_tmdb', [$this, 'ajax_search']);
        add_action('wp_ajax_movie_engine_import_movie', [$this, 'ajax_import_movie']);
        add_action('wp_ajax_movie_engine_import_tv', [$this, 'ajax_import_tv']);
        add_action('wp_ajax_movie_engine_import_person', [$this, 'ajax_import_person']);
        add_action('wp_ajax_movie_engine_get_series_data', [$this, 'ajax_get_series_data']);
        add_action('wp_ajax_movie_engine_import_se_unit', [$this, 'ajax_import_se_unit']);
        add_action('wp_ajax_movie_engine_search_persons', [$this, 'ajax_search_persons']);
    }

    /**
     * AJAX: Search TMDb
     */
    public function ajax_search() {
        check_ajax_referer('movie_engine_tmdb_search', 'nonce');

        if (! current_user_can('edit_posts')) {
            wp_send_json_error(['message' => 'Unauthorized']);
        }

        $query = isset($_POST['query']) ? sanitize_text_field(wp_unslash($_POST['query'])) : '';
        $type  = isset($_POST['type']) ? sanitize_text_field(wp_unslash($_POST['type'])) : 'movie';

        if ($query === 'test_debug') {
            wp_send_json_success([
                'results' => [
                    [
                        'id' => 123,
                        'title' => 'Debug Movie',
                        'release_date' => '2024-01-01',
                        'overview' => 'This is a debug movie.',
                        'poster_path' => null
                    ]
                ]
            ]);
        }

        if (empty($query)) {
            wp_send_json_error(['message' => 'Query is empty']);
        }

        if ($type === 'tv') {
            $results = $this->tmdb->search_tv($query);
        } elseif ($type === 'person') {
            $results = $this->tmdb->search_person($query);
        } else {
            $results = $this->tmdb->search_movie($query);
        }

        if (is_wp_error($results)) {
            wp_send_json_error(['message' => $results->get_error_message()]);
        }

        wp_send_json_success($results);
    }

    /**
     * AJAX: Import Movie from TMDb
     */
    public function ajax_import_movie() {
        // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged
        set_time_limit(300);
        check_ajax_referer('movie_engine_tmdb_import', 'nonce');

        if (! current_user_can('edit_posts')) {
            wp_send_json_error(['message' => 'Unauthorized']);
        }

        $tmdb_id = isset($_POST['tmdb_id']) ? absint($_POST['tmdb_id']) : 0;
        $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;

        if (! $tmdb_id || ! $post_id) {
            wp_send_json_error(['message' => 'Invalid parameters']);
        }

        $movie = $this->tmdb->get_movie_details($tmdb_id);

        if (is_wp_error($movie)) {
            wp_send_json_error(['message' => $movie->get_error_message()]);
        }

        try {
            $this->import_movie_data($post_id, $movie);
        } catch (\Exception $e) {
            wp_send_json_error(['message' => 'Import Exception: ' . $e->getMessage()]);
        }

        wp_send_json_success([
            'message' => 'Movie imported successfully!',
            'data'    => $movie,
        ]);
    }

    /**
     * AJAX: Import TV Series from TMDb
     */
    public function ajax_import_tv() {
        // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged
        set_time_limit(300);
        check_ajax_referer('movie_engine_tmdb_import', 'nonce');

        if (! current_user_can('edit_posts')) {
            wp_send_json_error(['message' => 'Unauthorized']);
        }

        $tmdb_id = isset($_POST['tmdb_id']) ? absint($_POST['tmdb_id']) : 0;
        $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;

        if (! $tmdb_id || ! $post_id) {
            wp_send_json_error(['message' => 'Invalid parameters']);
        }

        $tv = $this->tmdb->get_tv_details($tmdb_id);

        if (is_wp_error($tv)) {
            wp_send_json_error(['message' => $tv->get_error_message()]);
        }

        try {
            $this->import_tv_data($post_id, $tv);
        } catch (\Exception $e) {
            wp_send_json_error(['message' => 'Import Exception: ' . $e->getMessage()]);
        }

        wp_send_json_success([
            'message' => 'TV Series imported successfully!',
            'data'    => $tv,
        ]);
    }

    /**
     * AJAX: Import Person from TMDb
     */
    public function ajax_import_person() {
        check_ajax_referer('movie_engine_tmdb_import', 'nonce');

        if (! current_user_can('edit_posts')) {
            wp_send_json_error(['message' => 'Unauthorized']);
        }

        $tmdb_id = isset($_POST['tmdb_id']) ? absint($_POST['tmdb_id']) : 0;
        $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;

        if (! $tmdb_id || ! $post_id) {
            wp_send_json_error(['message' => 'Invalid parameters']);
        }

        $person = $this->tmdb->get_person_details($tmdb_id);

        if (is_wp_error($person)) {
            wp_send_json_error(['message' => $person->get_error_message()]);
        }

        $this->update_person_meta_from_tmdb($post_id, $person);

        if (!empty($person['profile_path']) && !has_post_thumbnail($post_id)) {
            $this->tmdb->download_image($person['profile_path'], $post_id, 'profile');
        }

        wp_send_json_success([
            'message' => 'Person details imported successfully!',
            'data'    => $person,
        ]);
    }

    public function ajax_get_series_data() {
        check_ajax_referer('movie-engine-admin-nonce', 'nonce');

        if (! current_user_can('edit_posts')) {
            wp_send_json_error(esc_html__('Permission denied.', 'cine-movie-engine'));
        }

        $tmdb_id = isset($_POST['tmdb_id']) ? sanitize_text_field(wp_unslash($_POST['tmdb_id'])) : '';

        if (! $tmdb_id) {
            wp_send_json_error(esc_html__('Invalid TMDb ID.', 'cine-movie-engine'));
        }

        $series = $this->tmdb->get_tv_details($tmdb_id);

        if (is_wp_error($series)) {
            wp_send_json_error($series->get_error_message());
        }

        $data = [];
        if (! empty($series['seasons'])) {
            foreach ($series['seasons'] as $season) {
                $data[] = [
                    'season_number' => $season['season_number'],
                    'episode_count' => $season['episode_count'],
                    'name'          => $season['name']
                ];
            }
        }

        wp_send_json_success($data);
    }

    public function ajax_import_se_unit() {
        check_ajax_referer('movie-engine-admin-nonce', 'nonce');

        if (! current_user_can('edit_posts')) {
            wp_send_json_error(esc_html__('Permission denied.', 'cine-movie-engine'));
        }

        $tmdb_id       = isset($_POST['tmdb_id']) ? sanitize_text_field(wp_unslash($_POST['tmdb_id'])) : '';
        $parent_id     = isset($_POST['parent_id']) ? absint($_POST['parent_id']) : 0;
        $season_number = isset($_POST['season_number']) ? absint($_POST['season_number']) : 0;
        $episode_number = isset($_POST['episode_number']) ? absint($_POST['episode_number']) : null;

        if (! $tmdb_id || ! $parent_id) {
            wp_send_json_error(esc_html__('Missing required data.', 'cine-movie-engine'));
        }

        if ($episode_number !== null) {
            $episode = $this->tmdb->get_tv_episode_details($tmdb_id, $season_number, $episode_number);
            if (is_wp_error($episode)) {
                wp_send_json_error($episode->get_error_message());
            }

            // phpcs:ignore WordPress.DB.SlowDBQuery
            $existing = new \WP_Query([
                'post_type'  => 'movie_engine_episode',
                // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
                'meta_query' => [
                    ['key' => '_movie_engine_tmdb_id', 'value' => $tmdb_id],
                    ['key' => '_movie_engine_season_number', 'value' => $season_number],
                    ['key' => '_movie_engine_episode_number', 'value' => $episode_number],
                ],
                'posts_per_page' => 1,
                'no_found_rows' => true,
                'update_post_meta_cache' => false,
                'fields' => 'ids',
            ]);

            $post_data = [
                'post_title'   => $episode['name'],
                'post_content' => $episode['overview'],
                'post_status'  => 'publish',
                'post_type'    => 'movie_engine_episode',
            ];

            if ($existing->have_posts()) {
                $post_id = $existing->posts[0];
                $post_data['ID'] = $post_id;
                wp_update_post($post_data);
            } else {
                $post_id = wp_insert_post($post_data);
            }

            if (is_wp_error($post_id)) {
                wp_send_json_error($post_id->get_error_message());
            }

            update_post_meta($post_id, '_movie_engine_tmdb_id', $tmdb_id);
            update_post_meta($post_id, '_movie_engine_season_number', $season_number);
            update_post_meta($post_id, '_movie_engine_episode_number', $episode_number);
            update_post_meta($post_id, '_movie_engine_air_date', $episode['air_date']);
            update_post_meta($post_id, '_movie_engine_runtime', $episode['runtime']);
            update_post_meta($post_id, '_movie_engine_series_id', $parent_id);

            // phpcs:ignore WordPress.DB.SlowDBQuery
            $season_post = new \WP_Query([
                'post_type'  => 'movie_engine_season',
                // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
                'meta_query' => [
                    ['key' => '_movie_engine_series_id', 'value' => $parent_id],
                    ['key' => '_movie_engine_season_number', 'value' => $season_number],
                ],
                'posts_per_page' => 1,
                'no_found_rows' => true,
                'update_post_meta_cache' => false,
                'fields' => 'ids'
            ]);
            if ($season_post->have_posts()) {
                update_post_meta($post_id, '_movie_engine_season_id', $season_post->posts[0]);
            }

            if (!empty($episode['still_path'])) {
                update_post_meta($post_id, '_movie_engine_episode_still', $episode['still_path']);
                $still_id = $this->tmdb->download_image($episode['still_path'], $post_id, 'episode_still');
                if ($still_id && !is_wp_error($still_id)) {
                    set_post_thumbnail($post_id, $still_id);
                }
            }

            wp_set_object_terms($post_id, '1080p Full HD', 'movie_engine_tv_quality');

            $imdb_id = $episode['external_ids']['imdb_id'] ?? '';
            do_action('movie_engine_after_metadata_import', $post_id, $tmdb_id, $imdb_id, 'tv', $season_number, $episode_number);

            wp_send_json_success(['type' => 'episode', 'id' => $post_id, 'name' => $episode['name']]);
        } else {
            $season = $this->tmdb->get_tv_season_details($tmdb_id, $season_number);
            if (is_wp_error($season)) {
                wp_send_json_error($season->get_error_message());
            }

            // phpcs:ignore WordPress.DB.SlowDBQuery
            $existing = new \WP_Query([
                'post_type'  => 'movie_engine_season',
                // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
                'meta_query' => [
                    ['key' => '_movie_engine_tmdb_id', 'value' => $tmdb_id],
                    ['key' => '_movie_engine_season_number', 'value' => $season_number],
                ],
                'posts_per_page' => 1,
                'no_found_rows' => true,
                'update_post_meta_cache' => false,
                'fields' => 'ids'
            ]);

            $season_displayName = $season['name'] ? $season['name'] : 'Season ' . $season_number;
            if (!empty($season['air_date'])) {
                $season_year = gmdate('Y', strtotime($season['air_date']));
                $season_displayName .= " ($season_year)";
            }

            $post_data = [
                'post_title'   => $season_displayName,
                'post_content' => $season['overview'],
                'post_status'  => 'publish',
                'post_type'    => 'movie_engine_season',
            ];

            if ($existing->have_posts()) {
                $post_id = $existing->posts[0];
                $post_data['ID'] = $post_id;
                wp_update_post($post_data);
            } else {
                $post_id = wp_insert_post($post_data);
            }

            update_post_meta($post_id, '_movie_engine_tmdb_id', $tmdb_id);
            update_post_meta($post_id, '_movie_engine_season_number', $season_number);
            update_post_meta($post_id, '_movie_engine_series_id', $parent_id);
            update_post_meta($post_id, '_movie_engine_air_date', $season['air_date']);
            if (!empty($season['air_date'])) {
                $season_year = gmdate('Y', strtotime($season['air_date']));
                update_post_meta($post_id, '_movie_engine_season_year', $season_year);
            }
            if (isset($season['episode_count'])) {
                update_post_meta($post_id, '_movie_engine_episode_count', $season['episode_count']);
            }

            if (! empty($season['poster_path'])) {
                $poster_id = $this->tmdb->download_image($season['poster_path'], $post_id, 'poster');
                if ($poster_id && !is_wp_error($poster_id)) {
                    set_post_thumbnail($post_id, $poster_id);
                }
            }

            wp_send_json_success(['type' => 'season', 'id' => $post_id, 'name' => $season['name']]);
        }
    }
    /**
     * Import movie data to post
     */
    public function import_movie_data($post_id, $movie) {
        $updated = wp_update_post([
            'ID'           => $post_id,
            'post_title'   => $movie['title'],
            'post_name'    => '',
            'post_content' => $movie['overview'],
            'post_status'  => 'publish',
        ]);

        if (is_wp_error($updated)) {
            return;
        }

        update_post_meta($post_id, '_movie_engine_runtime', $movie['runtime']);
        update_post_meta($post_id, '_movie_engine_rating', $movie['vote_average']);
        update_post_meta($post_id, '_movie_engine_release_date', $movie['release_date']);
        update_post_meta($post_id, '_movie_engine_imdb_id', $movie['imdb_id']);
        update_post_meta($post_id, '_movie_engine_tmdb_id', $movie['id']);

        if (!empty($movie['release_date'])) {
            $year = gmdate('Y', strtotime($movie['release_date']));
            update_post_meta($post_id, '_movie_engine_year', $year);
        }

        update_post_meta($post_id, '_movie_engine_imdb_rating', $movie['vote_average']);

        do_action('movie_engine_after_metadata_import', $post_id, $movie['id'], $movie['imdb_id'] ?? '', 'movie');

        if (! empty($movie['backdrop_path'])) {
            $backdrop_url = 'https://image.tmdb.org/t/p/original' . $movie['backdrop_path'];
            update_post_meta($post_id, '_movie_engine_backdrop_url', $backdrop_url);
        }

        if (! empty($movie['poster_path'])) {
            $poster_result = $this->tmdb->download_image($movie['poster_path'], $post_id, 'poster');
            if ($poster_result && !is_wp_error($poster_result) && is_numeric($poster_result)) {
                set_post_thumbnail($post_id, (int) $poster_result);
            }
        }

        if (! empty($movie['videos']['results'])) {
            foreach ($movie['videos']['results'] as $video) {
                if ($video['type'] === 'Trailer' && $video['site'] === 'YouTube') {
                    $trailer_url = 'https://www.youtube.com/watch?v=' . $video['key'];
                    update_post_meta($post_id, '_movie_engine_trailer', $trailer_url);
                    break;
                }
            }
        }

        if (! empty($movie['credits']['cast'])) {
            delete_post_meta($post_id, '_movie_engine_person_id');
            $cast_data = [];
            $cast_names = [];
            foreach (array_slice($movie['credits']['cast'], 0, 10) as $actor) {
                $person_id = $this->get_or_create_person($actor);
                add_post_meta($post_id, '_movie_engine_person_id', $person_id);

                $photo = ! empty($actor['profile_path']) ? 'https://image.tmdb.org/t/p/w185' . $actor['profile_path'] : '';

                $cast_data[] = [
                    'id'        => $person_id,
                    'name'      => $actor['name'],
                    'character' => $actor['character'],
                    'photo'     => $photo,
                ];
                $cast_names[] = $actor['name'];
            }
            update_post_meta($post_id, '_movie_engine_cast', $cast_data);
            wp_set_object_terms($post_id, $cast_names, 'movie_engine_actor');
        }

        if (! empty($movie['credits']['crew'])) {
            delete_post_meta($post_id, '_movie_engine_person_id');
            if (!empty($cast_data)) {
                foreach ($cast_data as $c) add_post_meta($post_id, '_movie_engine_person_id', $c['id']);
            }

            $directors = [];
            $directors_data = [];
            foreach ($movie['credits']['crew'] as $crew) {
                if ($crew['job'] === 'Director') {
                    $person_id = $this->get_or_create_person($crew);
                    add_post_meta($post_id, '_movie_engine_person_id', $person_id);

                    $directors[] = $crew['name'];
                    $directors_data[] = [
                        'id'   => $person_id,
                        'name' => $crew['name']
                    ];
                }
            }
            wp_set_object_terms($post_id, $directors, 'movie_engine_director');
            update_post_meta($post_id, '_movie_engine_directors_data', $directors_data);
        }

        if (! empty($movie['production_countries'])) {
            $countries = [];
            foreach ($movie['production_countries'] as $country) {
                $countries[] = $country['name'];
            }
            wp_set_object_terms($post_id, $countries, 'movie_engine_country');
        }

        if (! empty($movie['spoken_languages'])) {
            $languages = [];
            foreach ($movie['spoken_languages'] as $lang) {
                $languages[] = $lang['english_name'];
            }
            wp_set_object_terms($post_id, $languages, 'movie_engine_language');
        }

        if (! empty($movie['genres'])) {
            $genre_names = array_column($movie['genres'], 'name');
            wp_set_object_terms($post_id, $genre_names, 'movie_engine_genre');
        }

        $imdb_id = $movie['imdb_id'] ?? ($movie['external_ids']['imdb_id'] ?? '');
        update_post_meta($post_id, '_movie_engine_imdb_id', $imdb_id);
        update_post_meta($post_id, '_movie_engine_tmdb_id', $movie['id']);

        $this->fetch_omdb_ratings($post_id, $imdb_id);

        if (! empty($movie['release_date'])) {
            $year = gmdate('Y', strtotime($movie['release_date']));
            wp_set_object_terms($post_id, $year, 'movie_engine_year');
        }

        wp_set_object_terms($post_id, '1080p Full HD', 'movie_engine_quality');
    }

    /**
     * Import TV series data to post
     */
    public function import_tv_data($post_id, $tv) {
        wp_update_post([
            'ID'           => $post_id,
            'post_title'   => $tv['name'],
            'post_name'    => '',
            'post_content' => $tv['overview'],
            'post_status'  => 'publish',
        ]);

        update_post_meta($post_id, '_movie_engine_rating', $tv['vote_average']);
        update_post_meta($post_id, '_movie_engine_release_date', $tv['first_air_date']);
        update_post_meta($post_id, '_movie_engine_tmdb_id', $tv['id']);

        update_post_meta($post_id, '_movie_engine_status', $tv['status'] ?? '');
        update_post_meta($post_id, '_movie_engine_number_of_seasons', $tv['number_of_seasons'] ?? 0);
        update_post_meta($post_id, '_movie_engine_number_of_episodes', $tv['number_of_episodes'] ?? 0);

        if (!empty($tv['first_air_date'])) {
            $year = gmdate('Y', strtotime($tv['first_air_date']));
            update_post_meta($post_id, '_movie_engine_year', $year);
        }

        if (!empty($tv['external_ids']['imdb_id'])) {
            update_post_meta($post_id, '_movie_engine_imdb_id', $tv['external_ids']['imdb_id']);
        }

        if (!empty($tv['content_ratings']['results'])) {
            foreach ($tv['content_ratings']['results'] as $rating) {
                if ($rating['iso_3166_1'] === 'US') {
                    update_post_meta($post_id, '_movie_engine_mpaa', $rating['rating']);
                    break;
                }
            }
        }
        update_post_meta($post_id, '_movie_engine_imdb_rating', $tv['vote_average']);

        if (! empty($tv['backdrop_path'])) {
            $backdrop_url = 'https://image.tmdb.org/t/p/original' . $tv['backdrop_path'];
            update_post_meta($post_id, '_movie_engine_backdrop_url', $backdrop_url);
        }

        if (! empty($tv['poster_path'])) {
            $poster_id = $this->tmdb->download_image($tv['poster_path'], $post_id, 'poster');
            if ($poster_id && !is_wp_error($poster_id)) {
                set_post_thumbnail($post_id, $poster_id);
            }
        }

        if (! empty($tv['videos']['results'])) {
            foreach ($tv['videos']['results'] as $video) {
                if ($video['type'] === 'Trailer' && $video['site'] === 'YouTube') {
                    $trailer_url = 'https://www.youtube.com/watch?v=' . $video['key'];
                    update_post_meta($post_id, '_movie_engine_trailer', $trailer_url);
                    break;
                }
            }
        }

        if (! empty($tv['credits']['cast'])) {
            $cast_data = [];
            $cast_names = [];
            foreach (array_slice($tv['credits']['cast'], 0, 10) as $actor) {
                $person_id = $this->get_or_create_person($actor);
                add_post_meta($post_id, '_movie_engine_person_id', $person_id);

                $photo = ! empty($actor['profile_path']) ? 'https://image.tmdb.org/t/p/w185' . $actor['profile_path'] : '';

                $cast_data[] = [
                    'id'        => $person_id,
                    'name'      => $actor['name'],
                    'character' => $actor['character'],
                    'photo'     => $photo,
                ];
                $cast_names[] = $actor['name'];
            }
            update_post_meta($post_id, '_movie_engine_cast', $cast_data);
            wp_set_object_terms($post_id, $cast_names, 'movie_engine_actor');
        }

        if (!empty($tv['created_by'])) {
            delete_post_meta($post_id, '_movie_engine_person_id');
            if (!empty($cast_data)) {
                foreach ($cast_data as $c) add_post_meta($post_id, '_movie_engine_person_id', $c['id']);
            }

            $creators = [];
            $creators_data = [];
            foreach ($tv['created_by'] as $creator) {
                $person_id = $this->get_or_create_person($creator);
                add_post_meta($post_id, '_movie_engine_person_id', $person_id);

                $creators[] = $creator['name'];
                $creators_data[] = [
                    'id'   => $person_id,
                    'name' => $creator['name']
                ];
            }
            wp_set_object_terms($post_id, $creators, 'movie_engine_creator');
            update_post_meta($post_id, '_movie_engine_creators_data', $creators_data);
        }

        if (! empty($tv['origin_country'])) {
            wp_set_object_terms($post_id, $tv['origin_country'], 'movie_engine_country');
        }

        if (! empty($tv['original_language'])) {
            if (!empty($tv['spoken_languages'])) {
                $languages = [];
                foreach ($tv['spoken_languages'] as $lang) {
                    $languages[] = $lang['english_name'];
                }
                wp_set_object_terms($post_id, $languages, 'movie_engine_language');
            } else {
                wp_set_object_terms($post_id, $tv['original_language'], 'movie_engine_language');
            }
        }

        if (! empty($tv['networks'])) {
            $networks = [];
            foreach ($tv['networks'] as $network) {
                $networks[] = $network['name'];
            }
            wp_set_object_terms($post_id, $networks, 'movie_engine_network');
        }

        if (! empty($tv['genres'])) {
            $genre_names = [];
            foreach ($tv['genres'] as $genre) {
                $genre_names[] = $genre['name'];
            }
            wp_set_object_terms($post_id, $genre_names, 'movie_engine_genre');
        }

        if (! empty($tv['first_air_date'])) {
            $year = gmdate('Y', strtotime($tv['first_air_date']));
            wp_set_object_terms($post_id, $year, 'movie_engine_year');
        }

        $imdb_id = $tv['imdb_id'] ?? ($tv['external_ids']['imdb_id'] ?? '');
        update_post_meta($post_id, '_movie_engine_imdb_id', $imdb_id);

        $this->fetch_omdb_ratings($post_id, $imdb_id);

        wp_set_object_terms($post_id, '1080p Full HD', 'movie_engine_tv_quality');
    }

    private function get_or_create_person($actor) {
        $tmdb_id = $actor['id'] ?? 0;
        if (!$tmdb_id) return 0;

        // phpcs:ignore WordPress.DB.SlowDBQuery
        $existing = get_posts([
            'post_type'      => 'movie_engine_person',
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
            'meta_key'       => '_movie_engine_tmdb_id',
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
            'meta_value'     => $tmdb_id,
            'posts_per_page' => 1,
            'no_found_rows'  => true,
            'update_post_meta_cache' => false,
            'fields'         => 'ids',
            'post_status'    => ['publish', 'draft', 'pending', 'private'],
        ]);

        if (!empty($existing)) {
            return $existing[0];
        }

        $person_details = $this->tmdb->get_person_details($tmdb_id);
        $bio = '';
        if (!is_wp_error($person_details)) {
            $bio = $person_details['biography'] ?? '';
        }

        $person_id = wp_insert_post([
            'post_title'   => $actor['name'],
            'post_content' => $bio,
            'post_type'    => 'movie_engine_person',
            'post_status'  => 'publish',
        ]);

        if (!is_wp_error($person_id)) {
            update_post_meta($person_id, '_movie_engine_tmdb_id', $tmdb_id);

            $this->update_person_meta_from_tmdb($person_id, $person_details);

            if (!empty($actor['profile_path'])) {
                $photo_result = $this->tmdb->download_image($actor['profile_path'], $person_id, 'profile');
                if ($photo_result && !is_wp_error($photo_result) && is_numeric($photo_result)) {
                    set_post_thumbnail($person_id, (int) $photo_result);
                }
            }
        }

        return !is_wp_error($person_id) ? $person_id : 0;
    }

    private function update_person_meta_from_tmdb($post_id, $person) {
        if (empty($person) || is_wp_error($person)) return;
        if (!empty($person['biography'])) {
            wp_update_post([
                'ID'           => $post_id,
                'post_content' => $person['biography'],
            ]);
        }

        update_post_meta($post_id, '_movie_engine_tmdb_id', $person['id'] ?? 0);
        update_post_meta($post_id, '_movie_engine_birthday', $person['birthday'] ?? '');
        update_post_meta($post_id, '_movie_engine_place_of_birth', $person['place_of_birth'] ?? '');
        update_post_meta($post_id, '_movie_engine_known_for', $person['known_for_department'] ?? '');
        update_post_meta($post_id, '_movie_engine_gender', $person['gender'] ?? 0);
        update_post_meta($post_id, '_movie_engine_also_known_as', $person['also_known_as'] ?? []);

        $social_links = [];
        $ext = $person['external_ids'] ?? [];

        $platforms = [
            'twitter_id'   => 'twitter',
            'instagram_id' => 'instagram',
            'facebook_id'  => 'facebook',
            'youtube_id'   => 'youtube',
            'tiktok_id'    => 'tiktok'
        ];

        foreach ($platforms as $tmdb_key => $platform_key) {
            if (!empty($ext[$tmdb_key])) {
                $social_links[] = [
                    'platform' => $platform_key,
                    'url'      => $ext[$tmdb_key]
                ];
            }
        }

        update_post_meta($post_id, '_movie_engine_social_links', $social_links);
    }

    private function fetch_omdb_ratings($post_id, $imdb_id) {
        if (empty($imdb_id)) return;

        $omdb = new OmdbClient();
        $ratings = $omdb->get_ratings($imdb_id);

        if ($ratings) {
            update_post_meta($post_id, '_movie_engine_imdb_rating', $ratings['imdb']);
            update_post_meta($post_id, '_movie_engine_tomatoes_rating', $ratings['tomatoes']);
            update_post_meta($post_id, '_movie_engine_metacritic_rating', $ratings['metacritic']);
            update_post_meta($post_id, '_movie_engine_imdb_votes', $ratings['votes']);
        }
    }

    public function ajax_search_persons() {
        check_ajax_referer('movie-engine-admin-nonce', 'nonce');

        if (!current_user_can('edit_posts')) {
            wp_send_json_error('Unauthorized');
        }

        $query = isset($_GET['q']) ? sanitize_text_field(wp_unslash($_GET['q'])) : '';
        if (empty($query)) {
            wp_send_json_success([]);
        }

        $args = [
            'post_type'      => 'movie_engine_person',
            's'              => $query,
            'posts_per_page' => 10,
            'post_status'    => 'publish',
        ];

        $persons = get_posts($args);
        $results = [];

        foreach ($persons as $person) {
            $photo_url = get_the_post_thumbnail_url($person->ID, 'thumbnail');
            $results[] = [
                'id'    => $person->ID,
                'name'  => $person->post_title,
                'photo' => $photo_url
            ];
        }

        wp_send_json_success($results);
    }
}
