<?php

namespace MovieEngine\Admin\MetaBox;

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

class SeasonMetaBox {
    use MetaBoxTrait;

    public function init() {
        add_action('add_meta_boxes', [$this, 'add_meta_boxes']);
        add_action('save_post', [$this, 'save_meta_boxes']);
    }

    public function add_meta_boxes() {
        add_meta_box(
            'movie_engine_season_tabs',
            esc_html__('Season Information', 'cine-movie-engine'),
            [$this, 'render_season_tabs'],
            'movie_engine_season',
            'normal',
            'high'
        );
    }

    public function render_season_tabs($post) {
        wp_nonce_field('movie_engine_save_meta', 'movie_engine_meta_nonce');
?>
        <div class="movie-engine-metabox-tabs-wrapper">
            <div class="movie-engine-metabox-tabs-nav">
                <a href="#details" class="movie-engine-tab-link active" data-tab="details">
                    <span class="fa-solid fa-circle-info"></span> <?php esc_html_e('Details', 'cine-movie-engine'); ?>
                </a>
                <a href="#series" class="movie-engine-tab-link" data-tab="series">
                    <span class="fa-solid fa-list"></span> <?php esc_html_e('TV Series', 'cine-movie-engine'); ?>
                </a>
            </div>

            <div class="movie-engine-metabox-tabs-content">
                <div id="tab-details" class="movie-engine-tab-pane active">
                    <?php $this->render_season_details_content($post); ?>
                </div>
                <div id="tab-series" class="movie-engine-tab-pane">
                    <?php $this->render_season_series_content($post); ?>
                </div>
            </div>
        </div>
    <?php
    }

    public function render_season_details_content($post) {
        $season_number = get_post_meta($post->ID, '_movie_engine_season_number', true);
        $release_year  = get_post_meta($post->ID, '_movie_engine_season_year', true);
        $episode_count = get_post_meta($post->ID, '_movie_engine_episode_count', true);

        if (! $episode_count) {
            $series_id = get_post_meta($post->ID, '_movie_engine_series_id', true);
            if ($series_id && $season_number !== '') {
                $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_number],
                    ],
                ]);
                $episode_count = $episode_query->found_posts;
            }
        }
    ?>
        <div class="movie-engine-metabox-grid">
            <div class="movie-engine-field-group">
                <label for="movie_engine_season_number"><span class="fa-solid fa-sort"></span> <?php esc_html_e('Season Number', 'cine-movie-engine'); ?></label>
                <input type="number" id="movie_engine_season_number" name="movie_engine_season_number" value="<?php echo esc_attr($season_number); ?>" placeholder="1">
            </div>
            <div class="movie-engine-field-group">
                <label for="movie_engine_season_year"><span class="fa-solid fa-calendar-days"></span> <?php esc_html_e('Release Year', 'cine-movie-engine'); ?></label>
                <input type="number" id="movie_engine_season_year" name="movie_engine_season_year" value="<?php echo esc_attr($release_year); ?>" placeholder="2024">
            </div>
            <div class="movie-engine-field-group full-width">
                <label for="movie_engine_episode_count"><span class="fa-solid fa-film"></span> <?php esc_html_e('Number of Episodes', 'cine-movie-engine'); ?></label>
                <input type="number" id="movie_engine_episode_count" name="movie_engine_episode_count" value="<?php echo esc_attr($episode_count); ?>" placeholder="10">
            </div>
        </div>
    <?php
    }

    public function render_season_series_content($post) {
        $series_id = get_post_meta($post->ID, '_movie_engine_series_id', true);

        $series_list = get_posts([
            'post_type'      => 'movie_engine_series',
            'posts_per_page' => -1,
            'orderby'        => 'title',
            'order'          => 'ASC',
        ]);
    ?>
        <div class="movie-engine-field-group">
            <label for="movie_engine_series_id"><?php esc_html_e('Select TV Series', 'cine-movie-engine'); ?></label>
            <select id="movie_engine_series_id" name="movie_engine_series_id" class="me-select-full-auto">
                <option value=""><?php esc_html_e('-- Select Series --', 'cine-movie-engine'); ?></option>
                <?php foreach ($series_list as $series) : ?>
                    <option value="<?php echo esc_attr($series->ID); ?>" <?php selected($series_id, $series->ID); ?>>
                        <?php echo esc_html($series->post_title); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
<?php
    }

    public function save_meta_boxes($post_id) {
        if (! isset($_POST['movie_engine_meta_nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['movie_engine_meta_nonce'])), 'movie_engine_save_meta')) {
            return;
        }

        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }

        if (! current_user_can('edit_post', $post_id)) {
            return;
        }

        if (get_post_type($post_id) !== 'movie_engine_season') {
            return;
        }

        if (isset($_POST['movie_engine_series_id'])) {
            update_post_meta($post_id, '_movie_engine_series_id', absint($_POST['movie_engine_series_id']));
        }
        if (isset($_POST['movie_engine_season_number'])) {
            update_post_meta($post_id, '_movie_engine_season_number', absint($_POST['movie_engine_season_number']));
        }
        if (isset($_POST['movie_engine_season_year'])) {
            update_post_meta($post_id, '_movie_engine_season_year', sanitize_text_field(wp_unslash($_POST['movie_engine_season_year'])));
        }
        if (isset($_POST['movie_engine_episode_count'])) {
            update_post_meta($post_id, '_movie_engine_episode_count', absint($_POST['movie_engine_episode_count']));
        }
    }
}
