<?php

namespace MovieEngine\Admin\MetaBox;

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

class PersonMetaBox {
    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_person_tabs',
            esc_html__('Person Information', 'cine-movie-engine'),
            [$this, 'render_person_tabs'],
            'movie_engine_person',
            'normal',
            'high'
        );
    }

    public function render_person_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="#tmdb" class="movie-engine-tab-link" data-tab="tmdb">
                    <span class="fa-solid fa-download"></span> <?php esc_html_e('TMDb Import', '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_details_content($post); ?>
                </div>

                <div id="tab-tmdb" class="movie-engine-tab-pane">
                    <?php $this->render_tmdb_import_content($post, 'person'); ?>
                </div>
            </div>
        </div>
    <?php
    }

    public function render_details_content($post) {
        $tmdb_id        = get_post_meta($post->ID, '_movie_engine_tmdb_id', true);
        $birthday       = get_post_meta($post->ID, '_movie_engine_birthday', true);
        $place_of_birth = get_post_meta($post->ID, '_movie_engine_place_of_birth', true);
        $known_for      = get_post_meta($post->ID, '_movie_engine_known_for', true);
        $gender         = get_post_meta($post->ID, '_movie_engine_gender', true);
        $social_links    = get_post_meta($post->ID, '_movie_engine_social_links', true);
        if (!is_array($social_links)) $social_links = [];
        $aka            = get_post_meta($post->ID, '_movie_engine_also_known_as', true);
        if (is_array($aka)) $aka = implode("\n", $aka);

        $platforms = [
            'twitter'   => 'Twitter / X',
            'instagram' => 'Instagram',
            'facebook'  => 'Facebook',
            'tiktok'    => 'TikTok',
            'youtube'   => 'YouTube',
            'link'      => 'Other Website'
        ];
    ?>
        <div class="movie-engine-metabox-grid">
            <div class="movie-engine-field-group">
                <label for="movie_engine_tmdb_id"><span class="fa-solid fa-id-card"></span> <?php esc_html_e('TMDb ID', 'cine-movie-engine'); ?></label>
                <input type="text" id="movie_engine_tmdb_id" name="movie_engine_tmdb_id" value="<?php echo esc_attr($tmdb_id); ?>" placeholder="e.g. 12345">
            </div>

            <div class="movie-engine-field-group">
                <label for="movie_engine_known_for"><span class="fa-solid fa-briefcase"></span> <?php esc_html_e('Known For (Department)', 'cine-movie-engine'); ?></label>
                <input type="text" id="movie_engine_known_for" name="movie_engine_known_for" value="<?php echo esc_attr($known_for); ?>" placeholder="e.g. Acting">
            </div>

            <div class="movie-engine-field-group">
                <label for="movie_engine_birthday"><span class="fa-solid fa-cake-candles"></span> <?php esc_html_e('Birthday', 'cine-movie-engine'); ?></label>
                <input type="date" id="movie_engine_birthday" name="movie_engine_birthday" value="<?php echo esc_attr($birthday); ?>">
            </div>

            <div class="movie-engine-field-group">
                <label for="movie_engine_gender"><span class="fa-solid fa-venus-mars"></span> <?php esc_html_e('Gender', 'cine-movie-engine'); ?></label>
                <select id="movie_engine_gender" name="movie_engine_gender">
                    <option value="0" <?php selected($gender, 0); ?>><?php esc_html_e('Not set / Other', 'cine-movie-engine'); ?></option>
                    <option value="1" <?php selected($gender, 1); ?>><?php esc_html_e('Female', 'cine-movie-engine'); ?></option>
                    <option value="2" <?php selected($gender, 2); ?>><?php esc_html_e('Male', 'cine-movie-engine'); ?></option>
                    <option value="3" <?php selected($gender, 3); ?>><?php esc_html_e('Non-binary', 'cine-movie-engine'); ?></option>
                </select>
            </div>

            <div class="movie-engine-field-group full-width">
                <label for="movie_engine_place_of_birth"><span class="fa-solid fa-location-dot"></span> <?php esc_html_e('Place of Birth', 'cine-movie-engine'); ?></label>
                <input type="text" id="movie_engine_place_of_birth" name="movie_engine_place_of_birth" value="<?php echo esc_attr($place_of_birth); ?>" placeholder="e.g. New York City, USA">
            </div>

            <div class="movie-engine-field-group full-width">
                <label><span class="fa-solid fa-share-nodes"></span> <?php esc_html_e('Social Links', 'cine-movie-engine'); ?></label>
                <div id="movie-engine-social-repeater" class="movie-engine-social-repeater-list">
                    <?php if (!empty($social_links)) : ?>
                        <?php foreach ($social_links as $index => $link) : ?>
                            <div class="movie-engine-repeater-row me-d-flex me-align-center me-gap-3 me-mb-2">
                                <div class="me-social-platform-select">
                                    <select name="movie_engine_social_links[<?php echo esc_attr($index); ?>][platform]">
                                        <?php foreach ($platforms as $key => $label) : ?>
                                            <option value="<?php echo esc_attr($key); ?>" <?php selected($link['platform'], $key); ?>><?php echo esc_html($label); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="me-social-url-input me-flex-1">
                                    <input type="text" name="movie_engine_social_links[<?php echo esc_attr($index); ?>][url]" value="<?php echo esc_attr($link['url']); ?>" placeholder="<?php esc_attr_e('Username or Profile URL', 'cine-movie-engine'); ?>" class="widefat">
                                </div>
                                <button type="button" class="button movie-engine-remove-row me-btn-danger"><span class="dashicons dashicons-trash"></span></button>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                <button type="button" class="button button-primary movie-engine-add-social-row me-mt-2"><?php esc_html_e('+ Add Social Link', 'cine-movie-engine'); ?></button>

                <script type="text/template" id="movie-engine-social-row-template">
                    <div class="movie-engine-repeater-row me-d-flex me-align-center me-gap-3 me-mb-2">
                        <div class="me-social-platform-select">
                            <select name="movie_engine_social_links[{{index}}][platform]">
                                <?php foreach ($platforms as $key => $label) : ?>
                                    <option value="<?php echo esc_attr($key); ?>"><?php echo esc_html($label); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="me-social-url-input me-flex-1">
                            <input type="text" name="movie_engine_social_links[{{index}}][url]" value="" placeholder="<?php esc_attr_e('Username or Profile URL', 'cine-movie-engine'); ?>" class="widefat">
                        </div>
                        <button type="button" class="button movie-engine-remove-row me-btn-danger"><span class="dashicons dashicons-trash"></span></button>
                    </div>
                </script>
            </div>

            <div class="movie-engine-field-group full-width">
                <label for="movie_engine_also_known_as"><span class="fa-solid fa-tags"></span> <?php esc_html_e('Also Known As (One per line)', 'cine-movie-engine'); ?></label>
                <textarea id="movie_engine_also_known_as" name="movie_engine_also_known_as" rows="3"><?php echo esc_textarea($aka); ?></textarea>
            </div>
        </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_person') {
            return;
        }

        if (isset($_POST['movie_engine_tmdb_id'])) {
            update_post_meta($post_id, '_movie_engine_tmdb_id', sanitize_text_field(wp_unslash($_POST['movie_engine_tmdb_id'])));
        }

        if (isset($_POST['movie_engine_known_for'])) {
            update_post_meta($post_id, '_movie_engine_known_for', sanitize_text_field(wp_unslash($_POST['movie_engine_known_for'])));
        }

        if (isset($_POST['movie_engine_birthday'])) {
            update_post_meta($post_id, '_movie_engine_birthday', sanitize_text_field(wp_unslash($_POST['movie_engine_birthday'])));
        }

        if (isset($_POST['movie_engine_place_of_birth'])) {
            update_post_meta($post_id, '_movie_engine_place_of_birth', sanitize_text_field(wp_unslash($_POST['movie_engine_place_of_birth'])));
        }

        if (isset($_POST['movie_engine_gender'])) {
            update_post_meta($post_id, '_movie_engine_gender', absint($_POST['movie_engine_gender']));
        }

        if (isset($_POST['movie_engine_social_links'])) {
            $social_links = [];
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
            $posted_links = wp_unslash($_POST['movie_engine_social_links']);
            if (is_array($posted_links)) {
                foreach ($posted_links as $link) {
                    if (!empty($link['url'])) {
                        $social_links[] = [
                            'platform' => sanitize_text_field($link['platform']),
                            'url'      => sanitize_text_field($link['url']),
                        ];
                    }
                }
            }
            update_post_meta($post_id, '_movie_engine_social_links', $social_links);
        } else {
            delete_post_meta($post_id, '_movie_engine_social_links');
        }

        if (isset($_POST['movie_engine_also_known_as'])) {
            $aka_text = sanitize_textarea_field(wp_unslash($_POST['movie_engine_also_known_as']));
            $aka = array_filter(array_map('trim', explode("\n", $aka_text)));
            update_post_meta($post_id, '_movie_engine_also_known_as', $aka);
        }
    }
}
