<?php

namespace MovieEngine\Utils;

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

class Seo {

    public function __construct() {
        add_action('wp_head', [$this, 'inject_seo_meta'], 5);
        add_action('wp_head', [$this, 'inject_schema'], 30);
    }

    public function inject_seo_meta() {
        if (!is_singular(['movie_engine_movie', 'movie_engine_series', 'movie_engine_episode'])) {
            return;
        }

        $post_id = get_the_ID();
        $title = get_the_title();
        $description = wp_trim_words(get_the_content(), 25);
        $url = get_permalink();
        $thumb = get_the_post_thumbnail_url($post_id, 'large');

        echo "\n";
        echo '<meta property="og:title" content="' . esc_attr($title) . '" />' . "\n";
        echo '<meta property="og:description" content="' . esc_attr($description) . '" />' . "\n";
        echo '<meta property="og:url" content="' . esc_url($url) . '" />' . "\n";
        echo '<meta property="og:type" content="video.movie" />' . "\n";
        if ($thumb) {
            echo '<meta property="og:image" content="' . esc_url($thumb) . '" />' . "\n";
        }

        echo '<meta name="twitter:card" content="summary_large_image" />' . "\n";
        echo '<meta name="twitter:title" content="' . esc_attr($title) . '" />' . "\n";
        echo '<meta name="twitter:description" content="' . esc_attr($description) . '" />' . "\n";
        if ($thumb) {
            echo '<meta name="twitter:image" content="' . esc_url($thumb) . '" />' . "\n";
        }
        echo "\n";
    }

    public function inject_schema() {
        if (!is_singular(['movie_engine_movie', 'movie_engine_series', 'movie_engine_episode'])) {
            return;
        }
        $post_id = get_the_ID();
        $post_type = get_post_type($post_id);
        $schema = [];
        if ($post_type === 'movie_engine_movie') {
            $schema = $this->get_movie_schema($post_id);
        } elseif ($post_type === 'movie_engine_series') {
            $schema = $this->get_series_schema($post_id);
        } elseif ($post_type === 'movie_engine_episode') {
            $schema = $this->get_episode_schema($post_id);
        }
        if (!empty($schema)) {
            echo "\n";
            echo '<script type="application/ld+json">' . json_encode($schema, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . '</script>' . "\n";
            echo "\n";
        }
    }

    private function get_movie_schema($post_id) {
        $rating = get_post_meta($post_id, '_movie_engine_rating', true);
        $date = get_post_meta($post_id, '_movie_engine_release_date', true);
        $runtime = get_post_meta($post_id, '_movie_engine_runtime', true);
        $schema = [
            '@context'      => 'https://schema.org',
            '@type'         => 'Movie',
            'name'          => get_the_title($post_id),
            'description'   => wp_trim_words(get_the_content(), 50),
            'url'           => get_permalink($post_id),
            'image'         => get_the_post_thumbnail_url($post_id, 'full'),
            'datePublished' => $date ? $date : get_the_date('Y-m-d', $post_id),
        ];

        if ($runtime) {
            $schema['duration'] = 'PT' . $runtime . 'M';
        }

        if ($rating) {
            $schema['aggregateRating'] = [
                '@type'       => 'AggregateRating',
                'ratingValue' => $rating,
                'bestRating'  => '10',
                'worstRating' => '1',
                'ratingCount' => '100'
            ];
        }

        $cast = get_post_meta($post_id, '_movie_engine_cast', true);
        if ($cast && is_array($cast)) {
            $schema['actor'] = [];
            foreach (array_slice($cast, 0, 10) as $actor) {
                $schema['actor'][] = [
                    '@type' => 'Person',
                    'name'  => $actor['name']
                ];
            }
        }

        $directors = get_the_terms($post_id, 'movie_engine_director');
        if ($directors && !is_wp_error($directors)) {
            $schema['director'] = [];
            foreach ($directors as $dir) {
                $schema['director'][] = [
                    '@type' => 'Person',
                    'name'  => $dir->name
                ];
            }
        }
        return $schema;
    }

    private function get_series_schema($post_id) {
        $rating = get_post_meta($post_id, '_movie_engine_rating', true);
        $date = get_post_meta($post_id, '_movie_engine_release_date', true);
        $schema = [
            '@context'      => 'https://schema.org',
            '@type'         => 'TVSeries',
            'name'          => get_the_title($post_id),
            'description'   => wp_trim_words(get_the_content(), 50),
            'url'           => get_permalink($post_id),
            'image'         => get_the_post_thumbnail_url($post_id, 'full'),
            'datePublished' => $date ? $date : get_the_date('Y-m-d', $post_id),
        ];
        if ($rating) {
            $schema['aggregateRating'] = [
                '@type'       => 'AggregateRating',
                'ratingValue' => $rating,
                'bestRating'  => '10',
                'worstRating' => '1',
                'ratingCount' => '100'
            ];
        }
        return $schema;
    }

    private function get_episode_schema($post_id) {
        $series_id = get_post_meta($post_id, '_movie_engine_series_id', true);
        $ep_num = get_post_meta($post_id, '_movie_engine_episode_number', true);
        $season_num = get_post_meta($post_id, '_movie_engine_season_number', true);
        $air_date = get_post_meta($post_id, '_movie_engine_air_date', true);
        $schema = [
            '@context'      => 'https://schema.org',
            '@type'         => 'TVEpisode',
            'name'          => get_the_title($post_id),
            'episodeNumber' => $ep_num,
            'description'   => wp_trim_words(get_the_content(), 50),
            'url'           => get_permalink($post_id),
            'image'         => get_the_post_thumbnail_url($post_id, 'full'),
            'datePublished' => $air_date ? $air_date : get_the_date('Y-m-d', $post_id),
        ];
        if ($series_id) {
            $schema['partOfSeries'] = [
                '@type' => 'TVSeries',
                'name'  => get_the_title($series_id)
            ];
        }
        if ($season_num) {
            $schema['partOfSeason'] = [
                '@type'        => 'TVSeason',
                'seasonNumber' => $season_num
            ];
        }
        return $schema;
    }
}
