<?php

namespace MovieEngine\Admin\MetaBox;

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

class EpisodeMetaBox {
    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_episode_tabs',
            esc_html__('Episode Information', 'cine-movie-engine'),
            [$this, 'render_episode_tabs'],
            'movie_engine_episode',
            'normal',
            'high'
        );
    }

    public function render_episode_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="#sources" class="movie-engine-tab-link" data-tab="sources">
                    <span class="fa-solid fa-film"></span> <?php esc_html_e('Video Sources', 'cine-movie-engine'); ?>
                </a>
                <a href="#subtitles" class="movie-engine-tab-link" data-tab="subtitles">
                    <span class="fa-solid fa-closed-captioning"></span> <?php esc_html_e('Subtitles', 'cine-movie-engine'); ?>
                </a>
                <a href="#access" class="movie-engine-tab-link" data-tab="access">
                    <span class="fa-solid fa-lock"></span> <?php esc_html_e('Access Control', '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_episode_details_content($post); ?>
                </div>
                <div id="tab-sources" class="movie-engine-tab-pane">
                    <?php $this->render_sources_content($post); ?>
                </div>
                <div id="tab-subtitles" class="movie-engine-tab-pane">
                    <?php $this->render_subtitles_content($post); ?>
                </div>
                <div id="tab-access" class="movie-engine-tab-pane">
                    <?php $this->render_access_content($post); ?>
                </div>
            </div>
        </div>
    <?php
    }

    public function render_episode_details_content($post) {
        $episode_number = get_post_meta($post->ID, '_movie_engine_episode_number', true);
        $season_id      = get_post_meta($post->ID, '_movie_engine_season_id', true);
        $air_date       = get_post_meta($post->ID, '_movie_engine_air_date', true);
        $runtime        = get_post_meta($post->ID, '_movie_engine_runtime', true);

        if (! $season_id) {
            $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 ($series_id && $season_num !== '') {
                $season_query = new \WP_Query([
                    'post_type'      => 'movie_engine_season',
                    '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],
                    ],
                ]);
                if ($season_query->have_posts()) {
                    $season_id = $season_query->posts[0];
                }
            }
        }

        $seasons_list = get_posts([
            'post_type'      => 'movie_engine_season',
            'posts_per_page' => -1,
            'orderby'        => 'title',
            'order'          => 'ASC',
        ]);
    ?>
        <div class="movie-engine-metabox-grid">
            <div class="movie-engine-field-group">
                <label for="movie_engine_episode_number"><span class="fa-solid fa-sort"></span> <?php esc_html_e('Episode Number', 'cine-movie-engine'); ?></label>
                <input type="number" id="movie_engine_episode_number" name="movie_engine_episode_number" value="<?php echo esc_attr($episode_number); ?>" placeholder="1">
            </div>
            <div class="movie-engine-field-group">
                <label for="movie_engine_runtime"><span class="fa-solid fa-clock"></span> <?php esc_html_e('Runtime (min)', 'cine-movie-engine'); ?></label>
                <input type="number" id="movie_engine_runtime" name="movie_engine_runtime" value="<?php echo esc_attr($runtime); ?>" placeholder="45">
            </div>
            <div class="movie-engine-field-group">
                <label for="movie_engine_air_date"><span class="fa-solid fa-calendar-days"></span> <?php esc_html_e('Air Date', 'cine-movie-engine'); ?></label>
                <input type="date" id="movie_engine_air_date" name="movie_engine_air_date" value="<?php echo esc_attr($air_date); ?>">
            </div>
            <div class="movie-engine-field-group full-width">
                <label for="movie_engine_season_id"><span class="fa-solid fa-list"></span> <?php esc_html_e('Season', 'cine-movie-engine'); ?></label>
                <select id="movie_engine_season_id" name="movie_engine_season_id" class="me-select-full">
                    <option value=""><?php esc_html_e('-- Select Season --', 'cine-movie-engine'); ?></option>
                    <?php foreach ($seasons_list as $season) : ?>
                        <option value="<?php echo esc_attr($season->ID); ?>" <?php selected($season_id, $season->ID); ?>>
                            <?php echo esc_html($season->post_title); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
<?php
    }

    public function render_access_content($post) {
        if (has_action('movie_engine_render_access_metabox')) {
            do_action('movie_engine_render_access_metabox', $post);
            return;
        }

        \MovieEngine\Admin\Upgrade::render_metabox_upgrade_notice(
            esc_html__('Access Control (Pro)', 'cine-movie-engine'),
            esc_html__('Upgrade to Pro to unlock advanced access control for individual episodes, including membership restrictions and pay-per-view options.', 'cine-movie-engine'),
            [
                esc_html__('Episode Level Restrictions', 'cine-movie-engine'),
                esc_html__('Membership Integration', 'cine-movie-engine'),
                esc_html__('Advanced User Permissions', 'cine-movie-engine'),
            ]
        );
    }

    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_episode') {
            return;
        }

        if (isset($_POST['movie_engine_episode_number'])) {
            update_post_meta($post_id, '_movie_engine_episode_number', absint($_POST['movie_engine_episode_number']));
        }
        if (isset($_POST['movie_engine_season_id'])) {
            $season_id = absint($_POST['movie_engine_season_id']);
            update_post_meta($post_id, '_movie_engine_season_id', $season_id);

            if ($season_id) {
                $series_id     = get_post_meta($season_id, '_movie_engine_series_id', true);
                $season_number = get_post_meta($season_id, '_movie_engine_season_number', true);

                if ($series_id) {
                    update_post_meta($post_id, '_movie_engine_series_id', absint($series_id));
                }
                if ($season_number !== '') {
                    update_post_meta($post_id, '_movie_engine_season_number', absint($season_number));
                }
            }
        }
        if (isset($_POST['movie_engine_air_date'])) {
            update_post_meta($post_id, '_movie_engine_air_date', sanitize_text_field(wp_unslash($_POST['movie_engine_air_date'])));
        }
        if (isset($_POST['movie_engine_runtime'])) {
            update_post_meta($post_id, '_movie_engine_runtime', sanitize_text_field(wp_unslash($_POST['movie_engine_runtime'])));
        }

        do_action('movie_engine_save_access_metabox', $post_id);

        $this->save_shared_fields($post_id);
    }
}
