<?php

namespace MovieEngine\Admin;

if (!defined('ABSPATH')) {
    exit;
}

class CustomColumns {

    public function __construct() {
        add_filter('manage_movie_engine_season_posts_columns', [$this, 'season_columns']);
        add_action('manage_movie_engine_season_posts_custom_column', [$this, 'season_column_data'], 10, 2);

        add_filter('manage_movie_engine_episode_posts_columns', [$this, 'episode_columns']);
        add_action('manage_movie_engine_episode_posts_custom_column', [$this, 'episode_column_data'], 10, 2);

        add_filter('manage_movie_engine_series_posts_columns', [$this, 'series_columns']);
        add_action('manage_movie_engine_series_posts_custom_column', [$this, 'series_column_data'], 10, 2);

        add_filter('manage_movie_engine_movie_posts_columns', [$this, 'movie_columns']);
        add_action('manage_movie_engine_movie_posts_custom_column', [$this, 'movie_column_data'], 10, 2);

        add_action('pre_get_posts', [$this, 'admin_filter_episodes']);

        add_filter('manage_edit-movie_engine_movie_sortable_columns', [$this, 'sortable_columns']);
        add_filter('manage_edit-movie_engine_series_sortable_columns', [$this, 'sortable_columns']);
    }

    public function sortable_columns($columns) {
        $columns['movie_engine_rating'] = '_movie_engine_rating';
        $columns['movie_engine_views'] = '_movie_engine_views';
        $columns['movie_engine_likes'] = '_movie_engine_likes_count';
        return $columns;
    }

    public function season_columns($columns) {
        $new_columns = [];
        $new_columns['cb'] = $columns['cb'];
        $new_columns['title'] = $columns['title'];
        $new_columns['season_number'] = esc_html__('Season #', 'cine-movie-engine');
        $new_columns['tv_series'] = esc_html__('TV Series', 'cine-movie-engine');
        $new_columns['episode_count'] = esc_html__('Episodes', 'cine-movie-engine');
        $new_columns['release_year'] = esc_html__('Year', 'cine-movie-engine');
        $new_columns['date'] = $columns['date'];

        return $new_columns;
    }

    public function season_column_data($column, $post_id) {
        switch ($column) {
            case 'season_number':
                $number = get_post_meta($post_id, '_movie_engine_season_number', true);
                echo $number ? esc_html($number) : '—';
                break;

            case 'tv_series':
                $series_id = get_post_meta($post_id, '_movie_engine_series_id', true);
                if ($series_id) {
                    $series = get_post($series_id);
                    if ($series) {
                        echo '<a href="' . esc_url(get_edit_post_link($series_id)) . '">' . esc_html($series->post_title) . '</a>';
                    }
                } else {
                    echo '—';
                }
                break;

            case 'episode_count':
                $count = get_post_meta($post_id, '_movie_engine_episode_count', true);
                $series_id = get_post_meta($post_id, '_movie_engine_series_id', true);
                $season_num = get_post_meta($post_id, '_movie_engine_season_number', true);

                if (!$count) {
                    if ($series_id && $season_num !== '') {
                        $episode_query = new \WP_Query([
                            'post_type'      => 'movie_engine_episode',
                            'posts_per_page' => -1,
                            'fields'         => 'ids',
                            // phpcs:ignore WordPress.DB.SlowDBQuery
                            'meta_query'     => [
                                'relation' => 'AND',
                                [
                                    'key'   => '_movie_engine_series_id',
                                    'value' => $series_id,
                                ],
                                [
                                    'key'   => '_movie_engine_season_number',
                                    'value' => $season_num,
                                ],
                            ],
                        ]);
                        $count = $episode_query->found_posts;
                    }
                }

                if ($count !== false && $count !== '') {
                    $filter_url = add_query_arg([
                        'post_type'               => 'movie_engine_episode',
                        'movie_engine_series_id'            => $series_id,
                        'movie_engine_season_num'           => $season_num,
                    ], esc_url(admin_url('edit.php')));

                    echo '<a href="' . esc_url($filter_url) . '" class="me-link-bold">' . esc_html($count) . '</a>';
                } else {
                    echo '—';
                }
                break;

            case 'release_year':
                $year = get_post_meta($post_id, '_movie_engine_season_year', true);
                echo $year ? esc_html($year) : '—';
                break;
        }
    }

    public function episode_columns($columns) {
        $new_columns = [];
        $new_columns['cb'] = $columns['cb'];
        $new_columns['title'] = $columns['title'];
        $new_columns['tv_series'] = esc_html__('TV Series', 'cine-movie-engine');
        $new_columns['season_number'] = esc_html__('Season #', 'cine-movie-engine');
        $new_columns['episode_number'] = esc_html__('Episode #', 'cine-movie-engine');
        $new_columns['episode_genre'] = esc_html__('Genres', 'cine-movie-engine');
        $new_columns['episode_year'] = esc_html__('Year', 'cine-movie-engine');
        $new_columns['taxonomy-movie_engine_tv_quality'] = esc_html__('Quality', 'cine-movie-engine');
        $new_columns['date'] = $columns['date'];

        return $new_columns;
    }

    public function episode_column_data($column, $post_id) {
        switch ($column) {

            case 'tv_series':
                $series_id = get_post_meta($post_id, '_movie_engine_series_id', true);
                if ($series_id) {
                    $series = get_post($series_id);
                    if ($series) {
                        echo '<a href="' . esc_url(get_edit_post_link($series_id)) . '" class="me-link-semibold">' . esc_html($series->post_title) . '</a>';
                    }
                } else {
                    echo '—';
                }
                break;

            case 'season_number':
                $number = get_post_meta($post_id, '_movie_engine_season_number', true);
                $series_id = get_post_meta($post_id, '_movie_engine_series_id', true);
                if ($number !== '' && $series_id) {
                    $filter_url = add_query_arg([
                        'post_type'     => 'movie_engine_season',
                        'movie_engine_series_id'  => $series_id,
                    ], esc_url(admin_url('edit.php')));
                    echo '<a href="' . esc_url($filter_url) . '">' . esc_html($number) . '</a>';
                } else {
                    echo $number !== '' ? esc_html($number) : '—';
                }
                break;

            case 'episode_number':
                $number = get_post_meta($post_id, '_movie_engine_episode_number', true);
                echo $number ? esc_html($number) : '—';
                break;

            case 'episode_genre':
                $series_id = get_post_meta($post_id, '_movie_engine_series_id', true);
                if ($series_id) {
                    $terms = get_the_term_list($series_id, 'movie_engine_genre', '', ', ');
                    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- kses_post sanitizes HTML, dash is safe
                    echo $terms && !is_wp_error($terms) ? \MovieEngine\Utils\Helpers::kses_post($terms) : '—';
                } else {
                    echo '—';
                }
                break;

            case 'episode_year':
                $series_id = get_post_meta($post_id, '_movie_engine_series_id', true);
                if ($series_id) {
                    $year = get_post_meta($series_id, '_movie_engine_year', true);
                    if (!$year) {
                        $release_date = get_post_meta($series_id, '_movie_engine_release_date', true);
                        if ($release_date) {
                            $year = gmdate('Y', strtotime($release_date));
                        }
                    }
                    echo $year ? esc_html($year) : '—';
                } else {
                    echo '—';
                }
                break;

            case 'taxonomy-movie_engine_tv_quality':
                $this->render_quality_badge($post_id, 'movie_engine_tv_quality');
                break;
        }
    }

    /**
     * TV Series Columns
     */
    public function series_columns($columns) {
        $new_columns = [];
        foreach ($columns as $key => $value) {
            $new_columns[$key] = $value;
            if ($key === 'taxonomy-movie_engine_year') {
                $new_columns['seasons_count'] = esc_html__('Seasons', 'cine-movie-engine');
                $new_columns['episodes_count'] = esc_html__('Episodes', 'cine-movie-engine');
            }
        }

        $new_columns['movie_engine_rating'] = '<span class="dashicons dashicons-star-filled" title="' . esc_attr__('Rating', 'cine-movie-engine') . '"></span>';
        $new_columns['movie_engine_views'] = '<span class="dashicons dashicons-visibility" title="' . esc_attr__('Views', 'cine-movie-engine') . '"></span>';
        $new_columns['movie_engine_likes'] = '<span class="dashicons dashicons-heart" title="' . esc_attr__('Likes', 'cine-movie-engine') . '"></span>';

        if (!isset($new_columns['taxonomy-movie_engine_tv_quality'])) {
            $new_columns['taxonomy-movie_engine_tv_quality'] = esc_html__('Quality', 'cine-movie-engine');
        }

        return $new_columns;
    }

    /**
     * TV Series Column Data
     */
    public function series_column_data($column, $post_id) {
        switch ($column) {
            case 'seasons_count':
                $seasons = new \WP_Query([
                    'post_type'      => 'movie_engine_season',
                    'posts_per_page' => -1,
                    'fields'         => 'ids',
                    // phpcs:ignore WordPress.DB.SlowDBQuery
                    'meta_query'     => [
                        [
                            'key'   => '_movie_engine_series_id',
                            'value' => $post_id,
                        ]
                    ]
                ]);
                $count = $seasons->found_posts;
                if ($count > 0) {
                    $url = add_query_arg([
                        'post_type'    => 'movie_engine_season',
                        'movie_engine_series_id' => $post_id,
                    ], esc_url(admin_url('edit.php')));
                    echo '<a href="' . esc_url($url) . '" class="me-link-bold">' . esc_html($count) . '</a>';
                } else {
                    echo '0';
                }
                break;

            case 'episodes_count':
                $episodes = new \WP_Query([
                    'post_type'      => 'movie_engine_episode',
                    'posts_per_page' => -1,
                    'fields'         => 'ids',
                    // phpcs:ignore WordPress.DB.SlowDBQuery
                    'meta_query'     => [
                        [
                            'key'   => '_movie_engine_series_id',
                            'value' => $post_id,
                        ]
                    ]
                ]);
                $count = $episodes->found_posts;
                if ($count > 0) {
                    $url = add_query_arg([
                        'post_type'    => 'movie_engine_episode',
                        'movie_engine_series_id' => $post_id,
                    ], esc_url(admin_url('edit.php')));
                    echo '<a href="' . esc_url($url) . '" class="me-link-bold">' . esc_html($count) . '</a>';
                } else {
                    echo '0';
                }
                break;

            case 'taxonomy-movie_engine_tv_quality':
                $this->render_quality_badge($post_id, 'movie_engine_tv_quality');
                break;

            case 'movie_engine_rating':
                $rating = get_post_meta($post_id, '_movie_engine_rating', true);
                if (!$rating) {
                    $rating = get_post_meta($post_id, '_movie_engine_user_rating', true);
                    if ($rating) {
                        echo '<strong>' . esc_html($rating) . '</strong>';
                    } else {
                        echo '—';
                    }
                } else {
                    echo '<strong>' . esc_html($rating) . '</strong>';
                }
                break;

            case 'movie_engine_views':
                $views = get_post_meta($post_id, '_movie_engine_views', true);
                echo $views ? esc_html($this->format_number($views)) : '—';
                break;

            case 'movie_engine_likes':
                $likes = get_post_meta($post_id, '_movie_engine_likes_count', true);
                echo $likes ? esc_html($this->format_number($likes)) : '—';
                break;
        }
    }

    public function movie_columns($columns) {
        $new_columns = [];
        foreach ($columns as $key => $value) {
            $new_columns[$key] = $value;
        }

        $new_columns['movie_engine_rating'] = '<span class="dashicons dashicons-star-filled" title="' . esc_attr__('Rating', 'cine-movie-engine') . '"></span>';
        $new_columns['movie_engine_views'] = '<span class="dashicons dashicons-visibility" title="' . esc_attr__('Views', 'cine-movie-engine') . '"></span>';
        $new_columns['movie_engine_likes'] = '<span class="dashicons dashicons-heart" title="' . esc_attr__('Likes', 'cine-movie-engine') . '"></span>';

        return $new_columns;
    }

    public function movie_column_data($column, $post_id) {
        switch ($column) {
            case 'taxonomy-movie_engine_quality':
                $this->render_quality_badge($post_id);
                break;
            case 'movie_engine_rating':
                $rating = get_post_meta($post_id, '_movie_engine_rating', true);
                if (!$rating) {
                    $rating = get_post_meta($post_id, '_movie_engine_user_rating', true);
                    if ($rating) {
                        echo '<strong>' . esc_html($rating) . '</strong>';
                    } else {
                        echo '—';
                    }
                } else {
                    echo '<strong>' . esc_html($rating) . '</strong>';
                }
                break;

            case 'movie_engine_views':
                $views = get_post_meta($post_id, '_movie_engine_views', true);
                echo $views ? esc_html($this->format_number($views)) : '—';
                break;

            case 'movie_engine_likes':
                $likes = get_post_meta($post_id, '_movie_engine_likes_count', true);
                echo $likes ? esc_html($this->format_number($likes)) : '—';
                break;
        }
    }

    /**
     * Format Number (K/M)
     */
    private function format_number($n) {
        if ($n < 1000) return $n;
        $suffix = ['', 'K', 'M', 'B', 'T'];
        $power = floor(log($n, 1000));
        return round($n / pow(1000, $power), 1, PHP_ROUND_HALF_EVEN) . $suffix[$power];
    }

    /**
     * Render Quality Badge
     */
    private function render_quality_badge($post_id, $taxonomy = 'movie_engine_quality') {
        $terms = get_the_terms($post_id, $taxonomy);

        if (!$terms && get_post_type($post_id) === 'movie_engine_series') {
            $episode_query = new \WP_Query([
                'post_type'      => 'movie_engine_episode',
                'posts_per_page' => 1,
                // phpcs:ignore WordPress.DB.SlowDBQuery
                'meta_query'     => [
                    [
                        'key'   => '_movie_engine_series_id',
                        'value' => $post_id,
                    ]
                ],
                'orderby'        => 'ID',
                'order'          => 'DESC',
                'fields'         => 'ids'
            ]);
            if ($episode_query->have_posts()) {
                $terms = get_the_terms($episode_query->posts[0], 'movie_engine_tv_quality');
            }
        }

        if ($terms && !is_wp_error($terms)) {
            foreach ($terms as $term) {
                $color = '#64748b';
                $bg = '#f8fafc';
                $name = strtoupper($term->name);

                if (strpos($name, '4K') !== false || strpos($name, 'ULTRA') !== false) {
                    $color = '#7c3aed';
                    $bg = '#f5f3ff';
                } elseif (strpos($name, 'HD') !== false || strpos($name, '1080') !== false || strpos($name, '720') !== false) {
                    $color = '#059669';
                    $bg = '#ecfdf5';
                } elseif (strpos($name, 'CAM') !== false || strpos($name, 'TS') !== false || strpos($name, 'HDCAM') !== false) {
                    $color = '#d97706';
                    $bg = '#fffbeb';
                }

                echo sprintf(
                    '<span style="background: %s; color: %s; padding: 3px 10px; border-radius: 6px; font-size: 11px; font-weight: 800; border: 1px solid rgba(0,0,0,0.05); display: inline-block; margin: 2px 0;">%s</span> ',
                    esc_attr($bg),
                    esc_attr($color),
                    esc_html($term->name)
                );
            }
        } else {
            echo '<span class="me-text-muted">—</span>';
        }
    }

    /**
     * Filter episodes list in admin area
     */
    public function admin_filter_episodes($query) {
        if (!is_admin() || !$query->is_main_query() || $query->get('post_type') !== 'movie_engine_episode') {
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $series_id = isset($_GET['movie_engine_series_id']) ? absint($_GET['movie_engine_series_id']) : 0;
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $season_num = isset($_GET['movie_engine_season_num']) ? sanitize_text_field(wp_unslash($_GET['movie_engine_season_num'])) : '';

        if ($series_id || $season_num !== '') {
            $meta_query = (array) $query->get('meta_query');

            if ($series_id) {
                $meta_query[] = [
                    'key'   => '_movie_engine_series_id',
                    'value' => $series_id,
                ];
            }

            if ($season_num !== '') {
                $meta_query[] = [
                    'key'   => '_movie_engine_season_number',
                    'value' => $season_num,
                ];
            }

            $query->set('meta_query', $meta_query);
        }
    }
}
