<?php

namespace MovieEngine\Admin\MetaBox;

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

trait MetaBoxTrait {

    public function render_media_content($post) {
        $backdrop = get_post_meta($post->ID, '_movie_engine_backdrop_url', true);
?>
        <div class="movie-engine-field-group">
            <label for="movie_engine_backdrop_url"><span class="dashicons dashicons-format-image"></span> <?php esc_html_e('Backdrop Image URL', 'cine-movie-engine'); ?></label>
            <input type="url" id="movie_engine_backdrop_url" name="movie_engine_backdrop_url" value="<?php echo esc_attr($backdrop); ?>" placeholder="https://image.tmdb.org/t/p/original/...">
            <p class="description me-description-meta"><?php esc_html_e('This image will be used as the large hero background.', 'cine-movie-engine'); ?></p>
        </div>
        <?php $vtt = get_post_meta($post->ID, '_movie_engine_vtt_url', true); ?>
        <div class="movie-engine-field-group">
            <label for="movie_engine_vtt_url"><span class="dashicons dashicons-images-alt2"></span> <?php esc_html_e('VTT Thumbnail URL', 'cine-movie-engine'); ?></label>
            <input type="url" id="movie_engine_vtt_url" name="movie_engine_vtt_url" value="<?php echo esc_attr($vtt); ?>" placeholder="https://example.com/thumbnails.vtt">
            <p class="description me-description-meta"><?php esc_html_e('Used for hover previews on the player progress bar.', 'cine-movie-engine'); ?></p>
        </div>
    <?php
    }

    public function render_cast_content($post) {
        $cast = get_post_meta($post->ID, '_movie_engine_cast', true);
        if (! is_array($cast)) {
            $cast = [];
        }
        if (empty($cast)) {
            $cast[] = ['id' => '', 'name' => '', 'character' => '', 'photo' => ''];
        }
    ?>
        <div id="movie-engine-cast-repeater" class="movie-engine-cast-list">
            <?php foreach ($cast as $index => $actor) :
                $person_id = !empty($actor['id']) ? $actor['id'] : '';
            ?>
                <div class="movie-engine-cast-row movie-engine-repeater-row" data-index="<?php echo esc_attr($index); ?>">
                    <div class="me-cast-avatar-preview">
                        <?php if (!empty($actor['photo'])) : ?>
                            <img src="<?php echo esc_url($actor['photo']); ?>" alt="">
                        <?php else : ?>
                            <span class="dashicons dashicons-admin-users"></span>
                        <?php endif; ?>
                    </div>
                    <div class="me-cast-info">
                        <div class="me-cast-fields-grid">
                            <div class="movie-engine-field-group">
                                <label><?php esc_html_e('Link to Person (Search)', 'cine-movie-engine'); ?></label>
                                <div class="me-person-search-wrapper">
                                    <input type="text" class="me-person-search-input" value="<?php echo $person_id ? esc_attr(get_the_title($person_id)) : ''; ?>" placeholder="<?php esc_attr_e('Search for an actor...', 'cine-movie-engine'); ?>">
                                    <input type="hidden" name="movie_engine_cast[<?php echo esc_attr($index); ?>][id]" class="me-person-id-field" value="<?php echo esc_attr($person_id); ?>">
                                    <div class="me-person-search-results"></div>
                                </div>
                            </div>
                            <div class="movie-engine-field-group">
                                <label><?php esc_html_e('As Character', 'cine-movie-engine'); ?></label>
                                <input type="text" name="movie_engine_cast[<?php echo esc_attr($index); ?>][character]" value="<?php echo esc_attr($actor['character'] ?? ''); ?>" placeholder="<?php esc_attr_e('e.g. Tony Stark', 'cine-movie-engine'); ?>">
                            </div>
                        </div>
                        <div class="me-cast-fields-grid me-mt-10">
                            <div class="movie-engine-field-group">
                                <label><?php esc_html_e('Actor Name (Manual)', 'cine-movie-engine'); ?></label>
                                <input type="text" class="me-cast-name-field" name="movie_engine_cast[<?php echo esc_attr($index); ?>][name]" value="<?php echo esc_attr($actor['name'] ?? ''); ?>" placeholder="<?php esc_attr_e('e.g. Robert Downey Jr.', 'cine-movie-engine'); ?>">
                            </div>
                            <div class="movie-engine-field-group">
                                <label><?php esc_html_e('Photo URL (Manual)', 'cine-movie-engine'); ?></label>
                                <input type="text" class="me-cast-photo-url" name="movie_engine_cast[<?php echo esc_attr($index); ?>][photo]" value="<?php echo esc_attr($actor['photo'] ?? ''); ?>" placeholder="<?php esc_attr_e('Paste TMDB photo URL...', 'cine-movie-engine'); ?>">
                            </div>
                        </div>
                    </div>
                    <div class="me-cast-actions">
                        <button type="button" class="button movie-engine-remove-row me-btn-danger"><span class="dashicons dashicons-trash"></span></button>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        <button type="button" class="button button-primary movie-engine-add-cast-row movie-engine-add-row"><?php esc_html_e('+ Add Actor / Cast', 'cine-movie-engine'); ?></button>

        <script type="text/template" id="movie-engine-cast-row-template">
            <div class="movie-engine-cast-row movie-engine-repeater-row" data-index="{{index}}">
                <div class="me-cast-avatar-preview">
                    <span class="dashicons dashicons-admin-users"></span>
                </div>
                <div class="me-cast-info">
                    <div class="me-cast-fields-grid">
                        <div class="movie-engine-field-group">
                            <label><?php esc_html_e('Link to Person (Search)', 'cine-movie-engine'); ?></label>
                            <div class="me-person-search-wrapper">
                                <input type="text" class="me-person-search-input" value="" placeholder="<?php esc_attr_e('Search for an actor...', 'cine-movie-engine'); ?>">
                                <input type="hidden" name="movie_engine_cast[{{index}}][id]" class="me-person-id-field" value="">
                                <div class="me-person-search-results"></div>
                            </div>
                        </div>
                        <div class="movie-engine-field-group">
                            <label><?php esc_html_e('As Character', 'cine-movie-engine'); ?></label>
                            <input type="text" name="movie_engine_cast[{{index}}][character]" value="" placeholder="<?php esc_attr_e('e.g. Tony Stark', 'cine-movie-engine'); ?>">
                        </div>
                    </div>
                    <div class="me-cast-fields-grid me-mt-10">
                        <div class="movie-engine-field-group">
                            <label><?php esc_html_e('Actor Name (Manual)', 'cine-movie-engine'); ?></label>
                            <input type="text" class="me-cast-name-field" name="movie_engine_cast[{{index}}][name]" value="" placeholder="<?php esc_attr_e('e.g. Robert Downey Jr.', 'cine-movie-engine'); ?>">
                        </div>
                        <div class="movie-engine-field-group">
                            <label><?php esc_html_e('Photo URL (Manual)', 'cine-movie-engine'); ?></label>
                            <input type="text" class="me-cast-photo-url" name="movie_engine_cast[{{index}}][photo]" value="" placeholder="<?php esc_attr_e('Paste TMDB photo URL...', 'cine-movie-engine'); ?>">
                        </div>
                    </div>
                </div>
                <div class="me-cast-actions">
                    <button type="button" class="button movie-engine-remove-row me-btn-danger"><span class="dashicons dashicons-trash"></span></button>
                </div>
            </div>
        </script>
    <?php
    }

    public function render_sources_content($post) {
        $sources = get_post_meta($post->ID, '_movie_engine_sources', true);
        if (! is_array($sources)) {
            $sources = [];
        }

        $limit = apply_filters('movie_engine_video_sources_limit', 10);
        if ($limit > 0 && count($sources) > $limit) {
            $sources = array_slice($sources, 0, $limit);
        }

        if (empty($sources)) {
            $sources[] = ['name' => 'Server 1', 'url' => '', 'type' => 'iframe', 'lang' => 'en', 'quality' => '1080p'];
        }

        $languages = $this->get_language_list();
        $is_pro = has_action('movie_engine_render_pro_sources_features');
        $types = [
            'iframe' => ['label' => esc_html__('Embed / Iframe', 'cine-movie-engine'), 'pro' => false],
            'mp4'    => ['label' => esc_html__('Direct File (MP4/MKV)', 'cine-movie-engine'), 'pro' => false],
            'hls'    => ['label' => esc_html__('HLS (M3U8)', 'cine-movie-engine'), 'pro' => true],
            'dash'   => ['label' => esc_html__('MPEG-DASH (MPD)', 'cine-movie-engine'), 'pro' => true],
        ];
    ?>
        <div class="movie-engine-sources-container">
            <!-- Sentinel: signals to the save handler that this field was rendered -->
            <input type="hidden" name="movie_engine_sources_field_rendered" value="1">
            <p class="description" style="margin:0 0 12px;padding:8px 12px;background:#f0f6fc;border-left:3px solid #2271b1;border-radius:0 4px 4px 0;"><?php esc_html_e('MP4 quality selector: Add multiple rows with the same server name and different quality (e.g. 1080p, 720p, 480p).', 'cine-movie-engine'); ?></p>
            <p class="description" style="margin:0 0 12px;padding:8px 12px;background:#f0f0f1;border-left:3px solid #50575e;border-radius:0 4px 4px 0;"><?php esc_html_e('Audio menu (gear → Audio): Add one row per language, each with its own MP4 URL (e.g. Row 1: English + link to English MP4, Row 2: Spanish + link to Spanish MP4). The player will show the Audio option only when there are 2+ rows with different languages.', 'cine-movie-engine'); ?></p>
            <div id="movie-engine-video-sources-repeater" class="movie-engine-sources-list">
                <?php foreach ($sources as $index => $source) : ?>
                    <div class="movie-engine-source-row movie-engine-repeater-row">
                        <div class="movie-engine-field-group me-flex-120">
                            <label><?php esc_html_e('Server Name', 'cine-movie-engine'); ?></label>
                            <input type="text" name="movie_engine_sources[<?php echo esc_attr($index); ?>][name]" value="<?php echo esc_attr($source['name'] ?? ''); ?>" placeholder="<?php esc_attr_e('e.g. Server 1', 'cine-movie-engine'); ?>">
                        </div>
                        <div class="movie-engine-field-group me-flex-100">
                            <label><?php esc_html_e('Type', 'cine-movie-engine'); ?></label>
                            <select name="movie_engine_sources[<?php echo esc_attr($index); ?>][type]">
                                <?php foreach ($types as $val => $data):
                                    $label = $data['label'];
                                    if ($data['pro'] && !$is_pro) {
                                        $label .= ' ' . esc_html__('(PRO)', 'cine-movie-engine');
                                    }
                                    $disabled = ($data['pro'] && !$is_pro) ? 'disabled' : '';
                                ?>
                                    <option value="<?php echo esc_attr($val); ?>" <?php selected($source['type'] ?? 'iframe', $val); ?> <?php echo esc_attr($disabled); ?>><?php echo esc_html($label); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="movie-engine-field-group me-flex-100">
                            <label><?php esc_html_e('Language', 'cine-movie-engine'); ?></label>
                            <select name="movie_engine_sources[<?php echo esc_attr($index); ?>][lang]">
                                <?php foreach ($languages as $code => $name): ?>
                                    <option value="<?php echo esc_attr($code); ?>" <?php selected($source['lang'] ?? 'en', $code); ?>><?php echo esc_html($name); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="movie-engine-field-group me-flex-120">
                            <label><?php esc_html_e('Quality', 'cine-movie-engine'); ?></label>
                            <?php
                            $q = $source['quality'] ?? 'HD';
                            $qMatch = function ($vals) use ($q) {
                                return in_array($q, (array) $vals, true);
                            };
                            $qualityOpts = [
                                '2160' => '2160p (4K)',
                                '1440' => '1440p (2K)',
                                '1080' => '1080p (HD)',
                                '720'  => '720p',
                                '480'  => '480p',
                                '360'  => '360p',
                                '240'  => '240p',
                                '144'  => '144p',
                                'HD'   => 'HD (label)',
                            ];
                            ?>
                            <select name="movie_engine_sources[<?php echo esc_attr($index); ?>][quality]">
                                <?php foreach ($qualityOpts as $val => $label) :
                                    $saved_q_clean = preg_replace('/[^0-9]/', '', (string)$q);
                                    $opt_val_clean = preg_replace('/[^0-9]/', '', (string)$val);

                                    if (!empty($saved_q_clean) && !empty($opt_val_clean)) {
                                        $match = ($saved_q_clean === $opt_val_clean);
                                    } else {
                                        $match = (strtolower(trim((string)$q)) === strtolower(trim((string)$val)));
                                    }
                                    if (!$match && $q === 'HD') {
                                        $match = ($val === 'HD');
                                    }
                                ?>
                                    <option value="<?php echo esc_attr($val); ?>" <?php selected($match); ?>><?php echo esc_html($label); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="movie-engine-field-group grow">
                            <label><?php esc_html_e('URL / Embed Code', 'cine-movie-engine'); ?></label>
                            <input type="text" name="movie_engine_sources[<?php echo esc_attr($index); ?>][url]" value="<?php echo esc_attr($source['url'] ?? ''); ?>" placeholder="<?php esc_attr_e('https://...', 'cine-movie-engine'); ?>">
                        </div>
                        <?php if (has_action('movie_engine_render_pro_sources_features')) : ?>
                            <div class="me-source-actions">
                                <button type="button" class="button movie-engine-remove-row me-btn-danger"><span class="dashicons dashicons-trash"></span></button>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            </div>
            <div class="movie-engine-sources-actions me-actions-flex">
                <?php if (has_action('movie_engine_render_pro_sources_features')) : ?>
                    <button type="button" class="button button-primary movie-engine-add-row"><?php esc_html_e('+ Add Server', 'cine-movie-engine'); ?></button>

                    <button type="button" id="movie-engine-fetch-auto-sources" class="button button-primary movie-engine-add-row" data-post-id="<?php echo esc_attr($post->ID); ?>">
                        <span class="dashicons dashicons-admin-plugins me-icon-align"></span>
                        <?php esc_html_e('Fetch from API', 'cine-movie-engine'); ?>
                    </button>
                <?php endif; ?>
            </div>

            <?php if (!has_action('movie_engine_render_pro_sources_features')) : ?>
                <div class="me-sources-upgrade-notice-wrapper me-mt-20">
                    <?php \MovieEngine\Admin\Upgrade::render_metabox_upgrade_notice(
                        esc_html__('Advanced Video Sources', 'cine-movie-engine'),
                        esc_html__('Upgrade to Pro to unlock advanced streaming formats and multi-server support.', 'cine-movie-engine'),
                        [
                            esc_html__('HLS (M3U8) Adaptive Streaming', 'cine-movie-engine'),
                            esc_html__('MPEG-DASH Support', 'cine-movie-engine'),
                            esc_html__('Unlimited Video Sources (Multi-Server)', 'cine-movie-engine'),
                            esc_html__('Automatic Video Fetch (API)', 'cine-movie-engine'),
                        ]
                    ); ?>
                </div>
            <?php endif; ?>
        </div>

        <script type="text/template" id="movie-engine-source-row-template">
            <div class="movie-engine-source-row movie-engine-repeater-row">
                <div class="movie-engine-field-group me-flex-120">
                    <label><?php esc_html_e('Server Name', 'cine-movie-engine'); ?></label>
                    <input type="text" name="movie_engine_sources[{{index}}][name]" value="Server {{index_plus}}" placeholder="<?php esc_attr_e('Server Name', 'cine-movie-engine'); ?>">
                </div>
                <div class="movie-engine-field-group me-flex-100">
                    <label><?php esc_html_e('Type', 'cine-movie-engine'); ?></label>
                    <select name="movie_engine_sources[{{index}}][type]">
                        <?php foreach ($types as $val => $data):
                            $label = $data['label'];
                            if ($data['pro'] && !$is_pro) {
                                $label .= ' ' . esc_html__('(PRO)', 'cine-movie-engine');
                            }
                            $disabled_attr = ($data['pro'] && !$is_pro) ? ' disabled' : '';
                        ?>
                            <option value="<?php echo esc_attr($val); ?>"<?php echo esc_attr($disabled_attr); ?>><?php echo esc_html($label); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="movie-engine-field-group me-flex-100">
                    <label><?php esc_html_e('Language', 'cine-movie-engine'); ?></label>
                    <select name="movie_engine_sources[{{index}}][lang]">
                        <?php foreach ($languages as $code => $name): ?>
                            <option value="<?php echo esc_attr($code); ?>"<?php selected('en', $code); ?>><?php echo esc_html($name); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="movie-engine-field-group me-flex-120">
                    <label><?php esc_html_e('Quality', 'cine-movie-engine'); ?></label>
                    <select name="movie_engine_sources[{{index}}][quality]">
                        <option value="2160"><?php esc_html_e('2160p (4K)', 'cine-movie-engine'); ?></option>
                        <option value="1440"><?php esc_html_e('1440p (2K)', 'cine-movie-engine'); ?></option>
                        <option value="1080"><?php esc_html_e('1080p (HD)', 'cine-movie-engine'); ?></option>
                        <option value="720" selected><?php esc_html_e('720p', 'cine-movie-engine'); ?></option>
                        <option value="480"><?php esc_html_e('480p', 'cine-movie-engine'); ?></option>
                        <option value="360"><?php esc_html_e('360p', 'cine-movie-engine'); ?></option>
                        <option value="240"><?php esc_html_e('240p', 'cine-movie-engine'); ?></option>
                        <option value="144"><?php esc_html_e('144p', 'cine-movie-engine'); ?></option>
                        <option value="HD"><?php esc_html_e('HD (label)', 'cine-movie-engine'); ?></option>
                    </select>
                </div>
                <div class="movie-engine-field-group grow">
                    <label><?php esc_html_e('URL / Embed Code', 'cine-movie-engine'); ?></label>
                    <input type="text" name="movie_engine_sources[{{index}}][url]" value="" placeholder="<?php esc_attr_e('https://...', 'cine-movie-engine'); ?>">
                </div>
                <?php if (has_action('movie_engine_render_pro_sources_features')) : ?>
                    <div class="me-source-actions">
                        <button type="button" class="button movie-engine-remove-row me-btn-danger"><span class="dashicons dashicons-trash"></span></button>
                    </div>
                <?php endif; ?>
            </div>
        </script>
    <?php
    }

    public function render_subtitles_content($post) {
        $subtitles = get_post_meta($post->ID, '_movie_engine_subtitles', true);
        if (! is_array($subtitles)) {
            $subtitles = [];
        }
        if (empty($subtitles)) {
            $subtitles[] = ['label' => 'English', 'srclang' => 'en', 'src' => '', 'default' => ''];
        }
    ?>
        <p class="description me-mb-15">
            <?php esc_html_e('Add subtitle tracks in WebVTT (.vtt) format. Upload VTT files to your media library or use external URLs.', 'cine-movie-engine'); ?>
        </p>

        <div id="movie-engine-subtitles-repeater" class="movie-engine-subtitle-list">
            <?php foreach ($subtitles as $index => $subtitle) : ?>
                <div class="movie-engine-subtitle-row movie-engine-repeater-row">
                    <div class="movie-engine-field-group me-flex-150">
                        <label><?php esc_html_e('Label', 'cine-movie-engine'); ?></label>
                        <input type="text" name="movie_engine_subtitles[<?php echo esc_attr($index); ?>][label]" value="<?php echo esc_attr($subtitle['label']); ?>" placeholder="<?php esc_attr_e('English', 'cine-movie-engine'); ?>">
                    </div>
                    <div class="movie-engine-field-group me-flex-80">
                        <label><?php esc_html_e('Lang', 'cine-movie-engine'); ?></label>
                        <input type="text" name="movie_engine_subtitles[<?php echo esc_attr($index); ?>][srclang]" value="<?php echo esc_attr($subtitle['srclang']); ?>" placeholder="<?php esc_attr_e('en', 'cine-movie-engine'); ?>" maxlength="5">
                    </div>
                    <div class="movie-engine-field-group grow">
                        <label><?php esc_html_e('VTT File URL', 'cine-movie-engine'); ?></label>
                        <input type="url" name="movie_engine_subtitles[<?php echo esc_attr($index); ?>][src]" value="<?php echo esc_attr($subtitle['src']); ?>" placeholder="<?php esc_attr_e('https://example.com/subtitles.vtt', 'cine-movie-engine'); ?>">
                    </div>
                    <div class="me-subtitle-default-toggle">
                        <label>
                            <input type="checkbox" name="movie_engine_subtitles[<?php echo esc_attr($index); ?>][default]" value="1" <?php checked(!empty($subtitle['default']), true); ?>>
                            <span><?php esc_html_e('Default', 'cine-movie-engine'); ?></span>
                        </label>
                    </div>
                    <div class="me-subtitle-actions">
                        <button type="button" class="button movie-engine-remove-row"><span class="dashicons dashicons-trash"></span></button>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        <button type="button" class="button button-primary movie-engine-add-subtitle-row movie-engine-add-row"><?php esc_html_e('+ Add Subtitle Track', 'cine-movie-engine'); ?></button>

        <script type="text/template" id="movie-engine-subtitle-row-template">
            <div class="movie-engine-subtitle-row movie-engine-repeater-row">
                <div class="movie-engine-field-group me-flex-150">
                    <label><?php esc_html_e('Label', 'cine-movie-engine'); ?></label>
                    <input type="text" name="movie_engine_subtitles[{{index}}][label]" value="" placeholder="<?php esc_attr_e('English', 'cine-movie-engine'); ?>">
                </div>
                <div class="movie-engine-field-group me-flex-80">
                    <label><?php esc_html_e('Lang', 'cine-movie-engine'); ?></label>
                    <input type="text" name="movie_engine_subtitles[{{index}}][srclang]" value="" placeholder="<?php esc_attr_e('en', 'cine-movie-engine'); ?>" maxlength="5">
                </div>
                <div class="movie-engine-field-group grow">
                    <label><?php esc_html_e('VTT File URL', 'cine-movie-engine'); ?></label>
                    <input type="url" name="movie_engine_subtitles[{{index}}][src]" value="" placeholder="<?php esc_attr_e('https://example.com/subtitles.vtt', 'cine-movie-engine'); ?>">
                </div>
                <div class="me-subtitle-default-toggle">
                    <label>
                        <input type="checkbox" name="movie_engine_subtitles[{{index}}][default]" value="1">
                        <span><?php esc_html_e('Default', 'cine-movie-engine'); ?></span>
                    </label>
                </div>
                <div class="me-subtitle-actions">
                    <button type="button" class="button movie-engine-remove-row"><span class="dashicons dashicons-trash"></span></button>
                </div>
            </div>
        </script>
    <?php
    }

    public function render_tmdb_import_content($post, $type = 'movie') {
        $tmdb_id = get_post_meta($post->ID, '_movie_engine_tmdb_id', true);
    ?>
        <div class="movie-engine-tmdb-import-wrapper" data-type="<?php echo esc_attr($type); ?>">
            <div class="movie-engine-tmdb-search-box">
                <h3><?php esc_html_e('Search TMDb', 'cine-movie-engine'); ?></h3>
                <p class="description">
                    <?php esc_html_e('Search for a movie or TV series on TMDb and auto-fill all fields with one click.', 'cine-movie-engine'); ?>
                </p>

                <div class="movie-engine-search-input-group">
                    <input type="text" id="movie-engine-tmdb-search-input" class="widefat" placeholder="<?php esc_attr_e('Enter movie or TV series name...', 'cine-movie-engine'); ?>">
                    <button type="button" id="movie-engine-tmdb-search-btn" class="button button-primary">
                        <span class="dashicons dashicons-search"></span> <?php esc_html_e('Search', 'cine-movie-engine'); ?>
                    </button>
                </div>

                <div id="movie-engine-tmdb-results" class="movie-engine-tmdb-results"></div>
            </div>

            <?php if ($tmdb_id) : ?>
                <div class="movie-engine-tmdb-info">
                    <p class="success">
                        <span class="dashicons dashicons-yes"></span>
                        <?php printf(
                            /* translators: 1: post type (movie/series), 2: TMDb ID */
                            esc_html__('This %1$s was imported from TMDb (ID: %2$s)', 'cine-movie-engine'),
                            esc_html($type === 'tv' ? 'series' : 'movie'),
                            esc_html($tmdb_id)
                        ); ?>
                    </p>
                </div>
            <?php endif; ?>
        </div>

        <?php
    }

    public function render_affiliate_content($post) {
        $affiliate_links = get_post_meta($post->ID, '_movie_engine_affiliate_links', true);
        if (!is_array($affiliate_links)) {
            $affiliate_links = [];
        }

        $settings = get_option('movie_engine_monetization_settings', []);

        $affiliate_enabled = !empty($settings['movie_engine_enable_affiliates']) || !empty($settings['enable_affiliates']);
        $amazon_enabled    = !empty($settings['movie_engine_enable_amazon'])     || !empty($settings['enable_amazon']);
        $tickets_enabled   = !empty($settings['movie_engine_enable_tickets'])    || !empty($settings['enable_tickets']);

        $streaming_services = ['netflix', 'amazon_prime', 'disney_plus', 'hulu', 'hbo_max', 'apple_tv'];
        $any_streaming = false;
        foreach ($streaming_services as $svc) {
            if (!empty($settings['movie_engine_enable_' . $svc]) || !empty($settings['enable_' . $svc])) {
                $any_streaming = true;
                break;
            }
        }

        $has_any = $affiliate_enabled && ($amazon_enabled || $tickets_enabled || $any_streaming);

        echo '<div class="movie-engine-metabox-grid">';

        if ($has_any) {
            if ($amazon_enabled) {
                $amazon_url = $affiliate_links['amazon'] ?? '';
        ?>
                <div class="movie-engine-field-group full-width">
                    <label for="movie_engine_affiliate_amazon"><span class="dashicons dashicons-cart"></span> <?php esc_html_e('Amazon Product URL or ASIN', 'cine-movie-engine'); ?></label>
                    <input type="text" id="movie_engine_affiliate_amazon" name="movie_engine_affiliate_links[amazon]" value="<?php echo esc_attr($amazon_url); ?>" placeholder="https://amazon.com/dp/...">
                </div>
                <?php
            }

            $service_labels = [
                'netflix'      => 'Netflix',
                'amazon_prime' => 'Amazon Prime Video',
                'disney_plus'  => 'Disney+',
                'hulu'         => 'Hulu',
                'hbo_max'      => 'HBO Max',
                'apple_tv'     => 'Apple TV+',
            ];
            $service_meta_keys = [
                'netflix'      => 'netflix',
                'amazon_prime' => 'prime',
                'disney_plus'  => 'disney',
                'hulu'         => 'hulu',
                'hbo_max'      => 'hbo',
                'apple_tv'     => 'apple',
            ];

            foreach ($streaming_services as $svc) {
                if (!empty($settings['movie_engine_enable_' . $svc]) || !empty($settings['enable_' . $svc])) {
                    $meta_key = $service_meta_keys[$svc];
                    $url = $affiliate_links[$meta_key] ?? '';
                    $label = $service_labels[$svc];
                ?>
                    <div class="movie-engine-field-group full-width">
                        <label for="movie_engine_affiliate_<?php echo esc_attr($meta_key); ?>">
                            <span class="dashicons dashicons-video-alt3"></span>
                            <?php printf(
                                /* translators: %s: streaming service name (e.g. Netflix) */
                                esc_html__('%s URL', 'cine-movie-engine'),
                                esc_html($label)
                            ); ?>
                        </label>
                        <input type="url"
                            id="movie_engine_affiliate_<?php echo esc_attr($meta_key); ?>"
                            name="movie_engine_affiliate_links[<?php echo esc_attr($meta_key); ?>]"
                            value="<?php echo esc_attr($url); ?>"
                            placeholder="https://...">
                    </div>
                <?php
                }
            }

            if ($tickets_enabled) {
                $ticket_url = $affiliate_links['tickets'] ?? '';
                ?>
                <div class="movie-engine-field-group full-width">
                    <label for="movie_engine_affiliate_tickets"><span class="dashicons dashicons-tickets-alt"></span> <?php esc_html_e('Ticket Purchase URL', 'cine-movie-engine'); ?></label>
                    <input type="url" id="movie_engine_affiliate_tickets" name="movie_engine_affiliate_links[tickets]" value="<?php echo esc_attr($ticket_url); ?>" placeholder="https://fandango.com/...">
                </div>
<?php
            }
        } else {
            echo '<p class="description">' . esc_html__('Please enable affiliate services in MovieEngine Settings > Monetization > Affiliate Links.', 'cine-movie-engine') . '</p>';
        }

        echo '</div>';
    }

    public function save_shared_fields($post_id) {
        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        if (isset($_POST['movie_engine_backdrop_url'])) {
            // phpcs:ignore WordPress.Security.NonceVerification.Missing
            update_post_meta($post_id, '_movie_engine_backdrop_url', esc_url_raw(wp_unslash($_POST['movie_engine_backdrop_url'])));
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        if (isset($_POST['movie_engine_vtt_url'])) {
            // phpcs:ignore WordPress.Security.NonceVerification.Missing
            update_post_meta($post_id, '_movie_engine_vtt_url', esc_url_raw(wp_unslash($_POST['movie_engine_vtt_url'])));
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        if (isset($_POST['movie_engine_cast']) && is_array($_POST['movie_engine_cast'])) {
            $cast = [];
            // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
            $posted_cast = wp_unslash($_POST['movie_engine_cast']);
            foreach ($posted_cast as $actor) {
                if (! empty($actor['name']) || ! empty($actor['character']) || ! empty($actor['id'])) {
                    $cast[] = [
                        'id'        => isset($actor['id']) ? absint($actor['id']) : 0,
                        'name'      => sanitize_text_field($actor['name']),
                        'character' => sanitize_text_field($actor['character']),
                        'photo'     => esc_url_raw($actor['photo']),
                    ];
                }
            }
            update_post_meta($post_id, '_movie_engine_cast', $cast);
        } else {

            // phpcs:ignore WordPress.Security.NonceVerification.Missing
            if (isset($_POST['movie_engine_cast'])) {
            }

            // phpcs:ignore WordPress.Security.NonceVerification.Missing
            if (isset($_POST['movie_engine_cast']) && !is_array($_POST['movie_engine_cast'])) {
                delete_post_meta($post_id, '_movie_engine_cast');
            }
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        if (isset($_POST['movie_engine_sources']) && is_array($_POST['movie_engine_sources'])) {
            $sources = [];
            // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
            $posted_sources = wp_unslash($_POST['movie_engine_sources']);

            $limit = apply_filters('movie_engine_video_sources_limit', 10);
            if ($limit > 0 && count($posted_sources) > $limit) {
                $posted_sources = array_slice($posted_sources, 0, $limit);
            }

            foreach ($posted_sources as $source) {
                if (! empty($source['url'])) {
                    $sources[] = [
                        'name'    => sanitize_text_field($source['name']),
                        'url'     => $source['url'],
                        'type'    => sanitize_text_field($source['type'] ?? 'iframe'),
                        'lang'    => sanitize_text_field($source['lang'] ?? 'en'),
                        'quality' => sanitize_text_field($source['quality'] ?? 'HD'),
                    ];
                }
            }
            update_post_meta($post_id, '_movie_engine_sources', $sources);
            // phpcs:ignore WordPress.Security.NonceVerification.Missing
        } elseif (isset($_POST['movie_engine_sources_field_rendered'])) {
            // The sources field was rendered but all rows were deleted — clear the meta.
            delete_post_meta($post_id, '_movie_engine_sources');
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        if (isset($_POST['movie_engine_subtitles']) && is_array($_POST['movie_engine_subtitles'])) {
            $subtitles = [];
            // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
            $posted_subtitles = wp_unslash($_POST['movie_engine_subtitles']);
            foreach ($posted_subtitles as $subtitle) {
                if (! empty($subtitle['src'])) {
                    $subtitles[] = [
                        'label' => sanitize_text_field($subtitle['label']),
                        'srclang' => sanitize_text_field($subtitle['srclang']),
                        'src'  => esc_url_raw($subtitle['src']),
                        'default' => !empty($subtitle['default']) ? '1' : '',
                    ];
                }
            }
            update_post_meta($post_id, '_movie_engine_subtitles', $subtitles);
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        if (isset($_POST['movie_engine_affiliate_links']) && is_array($_POST['movie_engine_affiliate_links'])) {
            $links = [];
            // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
            $posted_affiliate = wp_unslash($_POST['movie_engine_affiliate_links']);
            foreach ($posted_affiliate as $key => $url) {
                if (!empty($url)) {
                    if ($key === 'amazon' && !filter_var($url, FILTER_VALIDATE_URL)) {
                        $links[$key] = sanitize_text_field($url);
                    } else {
                        $links[$key] = esc_url_raw($url);
                    }
                }
            }
            update_post_meta($post_id, '_movie_engine_affiliate_links', $links);
        }
    }

    private function get_language_list() {
        return [
            'en' => esc_html__('English', 'cine-movie-engine'),
            'es' => esc_html__('Spanish', 'cine-movie-engine'),
            'fr' => esc_html__('French', 'cine-movie-engine'),
            'de' => esc_html__('German', 'cine-movie-engine'),
            'it' => esc_html__('Italian', 'cine-movie-engine'),
            'pt' => esc_html__('Portuguese', 'cine-movie-engine'),
            'ru' => esc_html__('Russian', 'cine-movie-engine'),
            'tr' => esc_html__('Turkish', 'cine-movie-engine'),
            'zh' => esc_html__('Chinese', 'cine-movie-engine'),
            'jp' => esc_html__('Japanese', 'cine-movie-engine'),
            'hi' => esc_html__('Hindi', 'cine-movie-engine'),
            'multi' => esc_html__('Multi-Audio', 'cine-movie-engine'),
        ];
    }
}
