<?php

namespace MovieEngine\Admin;

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

class SetupWizard {

    public function __construct() {
        add_action('admin_menu', [$this, 'add_setup_page'], 99);
        add_action('admin_init', [$this, 'redirect_to_setup']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
        add_action('wp_ajax_movie_engine_save_setup_step', [$this, 'ajax_save_step']);
        add_action('wp_ajax_movie_engine_skip_setup', [$this, 'ajax_skip_setup']);
    }

    public function enqueue_assets($hook) {
        if (strpos($hook, 'movie-engine-setup') === false) {
            return;
        }

        wp_enqueue_style('font-awesome', MOVIE_ENGINE_URL . 'assets/fonts/fontawesome.min.css', [], MOVIE_ENGINE_VERSION);
        wp_enqueue_style('movie-engine-admin', MOVIE_ENGINE_URL . 'assets/css/admin/movie-engine-admin.min.css', ['font-awesome'], MOVIE_ENGINE_VERSION);
        wp_enqueue_script('movie-engine-setup', MOVIE_ENGINE_URL . 'assets/js/admin/setup-wizard.min.js', ['jquery'], MOVIE_ENGINE_VERSION, true);

        wp_localize_script('movie-engine-setup', 'movieEngineSetup', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce'    => wp_create_nonce('movie-engine-setup-nonce'),
            'dashboard_url' => admin_url('admin.php?page=movie-engine-settings'),
            'skip_url' => admin_url('admin.php?page=movie-engine-settings'),
            'i18n'     => [
                'next'   => esc_html__('Next Step', 'cine-movie-engine'),
                'finish' => esc_html__('Finish Setup', 'cine-movie-engine'),
                'skip'   => esc_html__('Skip Setup', 'cine-movie-engine'),
            ]
        ]);
    }

    public function add_setup_page() {
        add_submenu_page(
            'cine-movie-engine',
            esc_html__('MovieEngine Setup', 'cine-movie-engine'),
            esc_html__('Setup Wizard', 'cine-movie-engine'),
            'manage_options',
            'movie-engine-setup',
            [$this, 'render_setup_page']
        );
    }

    public function redirect_to_setup() {
        if (! get_transient('movie_engine_activation_redirect')) {
            return;
        }

        if (function_exists('movieengine_fs')) {
            $fs = movieengine_fs();
            if (! $fs->is_registered() && ! $fs->is_anonymous() && ! $fs->is_pending_activation()) {
                return;
            }
        }

        delete_transient('movie_engine_activation_redirect');

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if (! is_network_admin() && ! isset($_GET['activate-multi'])) {
            wp_safe_redirect(esc_url(admin_url('admin.php?page=movie-engine-setup')));
            exit;
        }
    }

    public function ajax_save_step() {
        check_ajax_referer('movie-engine-setup-nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Permission denied', 'cine-movie-engine')]);
        }

        $step = isset($_POST['step']) ? intval($_POST['step']) : 0;
        $post_data = isset($_POST['data']) ? wp_unslash($_POST['data']) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        parse_str($post_data, $data);

        switch ($step) {
            case 2: // API Keys
                $settings = get_option('movie_engine_api_settings', []);
                $settings['movie_engine_tmdb_api_key'] = sanitize_text_field($data['tmdb_api_key'] ?? '');
                $settings['movie_engine_omdb_api_key'] = sanitize_text_field($data['omdb_api_key'] ?? '');
                update_option('movie_engine_api_settings', $settings);
                break;

            case 3: // Pages
                if (!empty($data['create_pages'])) {
                    $page_names = isset($data['page_names']) ? $data['page_names'] : [];
                    $page_slugs = isset($data['page_slugs']) ? $data['page_slugs'] : [];

                    // Create pages with custom names
                    $pages = \MovieEngine\Core\PageSetup::get_pages();
                    $design_settings = get_option('movie_engine_design_settings', []);

                    foreach ($pages as $key => $page_data) {
                        $page_id = isset($design_settings[$key]) ? absint($design_settings[$key]) : 0;
                        $page_object = $page_id ? get_post($page_id) : null;

                        if (!$page_object || $page_object->post_status === 'trash') {
                            $page_title = isset($page_names[$key]) ? sanitize_text_field($page_names[$key]) : $page_data['title'];
                            $page_slug = isset($page_slugs[$key]) ? sanitize_title($page_slugs[$key]) : $page_data['name'];
                            $existing_page = get_page_by_path($page_slug);

                            if ($existing_page) {
                                $design_settings[$key] = $existing_page->ID;
                            } else {
                                $new_page_id = wp_insert_post([
                                    'post_title'     => $page_title,
                                    'post_name'      => $page_slug,
                                    'post_content'   => $page_data['content'],
                                    'post_status'    => 'publish',
                                    'post_type'      => 'page',
                                    'comment_status' => 'closed',
                                ]);

                                if ($new_page_id && !is_wp_error($new_page_id)) {
                                    $design_settings[$key] = $new_page_id;
                                    if (!empty($page_data['template'])) {
                                        update_post_meta($new_page_id, '_wp_page_template', $page_data['template']);
                                    }
                                }
                            }
                        }
                    }
                    update_option('movie_engine_design_settings', $design_settings);
                }
                break;

            case 4: // Design
                $design = get_option('movie_engine_design_settings', []);
                $design['color_preset'] = sanitize_text_field($data['color_preset'] ?? 'netflix');
                update_option('movie_engine_design_settings', $design);
                \MovieEngine\Core\Cache::update_custom_css();
                break;

            case 5: // Final
                update_option('movie_engine_setup_completed', time());
                break;
        }

        wp_send_json_success();
    }

    public function ajax_skip_setup() {
        check_ajax_referer('movie-engine-setup-nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Permission denied', 'cine-movie-engine')]);
        }

        update_option('movie_engine_setup_completed', time());
        update_option('movie_engine_setup_skipped', true);

        wp_send_json_success([
            'redirect' => admin_url('admin.php?page=movie-engine-settings')
        ]);
    }

    public function render_setup_page() {
?>
        <div class="movie-engine-setup-wizard">
            <header class="me-setup-header">
                <h1><?php esc_html_e('Welcome to MovieEngine', 'cine-movie-engine'); ?></h1>
                <p><?php esc_html_e('The ultimate movie library solution for WordPress.', 'cine-movie-engine'); ?></p>
            </header>

            <div class="me-setup-steps-bar">
                <?php
                $steps = [
                    1 => ['icon' => 'fa-play', 'label' => esc_html__('Welcome', 'cine-movie-engine')],
                    2 => ['icon' => 'fa-key', 'label' => esc_html__('API Keys', 'cine-movie-engine')],
                    3 => ['icon' => 'fa-file-lines', 'label' => esc_html__('Pages', 'cine-movie-engine')],
                    4 => ['icon' => 'fa-palette', 'label' => esc_html__('Design', 'cine-movie-engine')],
                    5 => ['icon' => 'fa-check', 'label' => esc_html__('Finish', 'cine-movie-engine')],
                ];

                foreach ($steps as $i => $step) : ?>
                    <div class="me-setup-step <?php echo $i === 1 ? 'active' : ''; ?>" data-step="<?php echo esc_attr($i); ?>">
                        <span class="me-setup-step-icon"><i class="fa-solid <?php echo esc_attr($step['icon']); ?>"></i></span>
                        <span class="me-setup-step-label"><?php echo esc_html($step['label']); ?></span>
                    </div>
                <?php endforeach; ?>
            </div>

            <div class="me-setup-content">
                <div class="me-setup-step-panel active" data-step="1">
                    <h2><?php esc_html_e('Getting Started', 'cine-movie-engine'); ?></h2>
                    <p><?php esc_html_e('Thank you for choosing MovieEngine. This wizard will help you configure the core settings to get your movie site up and running in minutes.', 'cine-movie-engine'); ?></p>
                    <p><?php esc_html_e('Click "Next Step" to start the configuration.', 'cine-movie-engine'); ?></p>
                </div>

                <div class="me-setup-step-panel" data-step="2">
                    <h2><?php esc_html_e('Connect Data Sources', 'cine-movie-engine'); ?></h2>
                    <p><?php esc_html_e('MovieEngine uses TMDb and OMDb to fetch movie data, posters, and ratings automatically.', 'cine-movie-engine'); ?></p>

                    <div class="me-setup-field">
                        <label><?php esc_html_e('TMDb API Key', 'cine-movie-engine'); ?></label>
                        <input type="text" name="tmdb_api_key" placeholder="e.g. 1a2b3c4d5e6f...">
                        <span class="description">
                            <?php
                            /* translators: %s: Link to TMDb API settings page */
                            printf(esc_html__('Required for movie data. Get it here: %s', 'cine-movie-engine'), '<a href="https://www.themoviedb.org/settings/api" target="_blank">themoviedb.org</a>');
                            ?>
                        </span>
                    </div>

                    <div class="me-setup-field">
                        <label><?php esc_html_e('OMDb API Key (Optional)', 'cine-movie-engine'); ?></label>
                        <input type="text" name="omdb_api_key" placeholder="e.g. 7f8e9d0c...">
                        <span class="description"><?php esc_html_e('Used for OMDb & IMDb ratings.', 'cine-movie-engine'); ?></span>
                    </div>
                </div>

                <div class="me-setup-step-panel" data-step="3">
                    <h2><?php esc_html_e('Customize Your Pages', 'cine-movie-engine'); ?></h2>
                    <p><?php esc_html_e('Customize the names of your pages. The URL slugs will be generated automatically from the page names.', 'cine-movie-engine'); ?></p>

                    <div class="me-setup-field">
                        <label>
                            <input type="checkbox" name="create_pages" value="1" checked>
                            <?php esc_html_e('Create all required library and user pages', 'cine-movie-engine'); ?>
                        </label>
                    </div>


                    <div class="me-setup-pages-list">
                        <table class="me-setup-pages-table">
                            <thead>
                                <tr>
                                    <th><?php esc_html_e('Page', 'cine-movie-engine'); ?></th>
                                    <th><?php esc_html_e('Page Title', 'cine-movie-engine'); ?></th>
                                    <th><?php esc_html_e('URL Slug', 'cine-movie-engine'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $pages = \MovieEngine\Core\PageSetup::get_pages();
                                foreach ($pages as $key => $page) :
                                ?>
                                    <tr>
                                        <td class="me-page-label">
                                            <strong><?php echo esc_html($page['title']); ?></strong>
                                        </td>
                                        <td>
                                            <input type="text"
                                                name="page_names[<?php echo esc_attr($key); ?>]"
                                                value="<?php echo esc_attr($page['title']); ?>"
                                                class="me-page-name-input"
                                                data-page-key="<?php echo esc_attr($key); ?>"
                                                placeholder="<?php echo esc_attr($page['title']); ?>">
                                        </td>
                                        <td>
                                            <input type="text"
                                                name="page_slugs[<?php echo esc_attr($key); ?>]"
                                                value="<?php echo esc_attr($page['name']); ?>"
                                                class="me-page-slug-input"
                                                readonly>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <div class="me-setup-info-box">
                        <p class="me-setup-info-text">
                            <i class="fa-solid fa-lightbulb me-setup-info-icon"></i>
                            <?php esc_html_e('The URL slug is automatically generated from the page name. You can change page names anytime in Settings → Design → Pages.', 'cine-movie-engine'); ?>
                        </p>
                    </div>
                </div>

                <div class="me-setup-step-panel" data-step="4">
                    <h2><?php esc_html_e('Choose Your Aesthetic', 'cine-movie-engine'); ?></h2>
                    <p><?php esc_html_e('Select a design preset that matches your brand. You can always customize colors later in Design Settings.', 'cine-movie-engine'); ?></p>

                    <div class="me-preset-grid">
                        <div class="me-preset-card active">
                            <input type="radio" name="color_preset" value="netflix" checked style="display:none;">
                            <div class="me-preset-thumb" style="background: #141414; border-bottom: 4px solid #E50914;"></div>
                            <span class="me-preset-name"><?php esc_html_e('Netflix Style', 'cine-movie-engine'); ?></span>
                        </div>
                        <div class="me-preset-card">
                            <input type="radio" name="color_preset" value="hulu" style="display:none;">
                            <div class="me-preset-thumb" style="background: #0b0c0f; border-bottom: 4px solid #1CE783;"></div>
                            <span class="me-preset-name"><?php esc_html_e('Hulu Style', 'cine-movie-engine'); ?></span>
                        </div>
                        <div class="me-preset-card">
                            <input type="radio" name="color_preset" value="prime" style="display:none;">
                            <div class="me-preset-thumb" style="background: #0f171e; border-bottom: 4px solid #00A8E1;"></div>
                            <span class="me-preset-name"><?php esc_html_e('Prime Style', 'cine-movie-engine'); ?></span>
                        </div>
                    </div>
                </div>
                <div class="me-setup-step-panel" data-step="5">
                    <div class="me-setup-success">
                        <i class="fa-solid fa-circle-check"></i>
                        <h2><?php esc_html_e('You\'re all set!', 'cine-movie-engine'); ?></h2>
                        <p><?php esc_html_e('Congratulations! Your movie site is now configured and ready for content.', 'cine-movie-engine'); ?></p>
                        <p><?php esc_html_e('Click the button below to finish and start importing your first movie.', 'cine-movie-engine'); ?></p>
                    </div>
                </div>
            </div>

            <footer class="me-setup-footer">
                <button type="button" class="me-setup-btn me-setup-btn-secondary me-setup-prev" style="display:none;"><?php esc_html_e('Previous', 'cine-movie-engine'); ?></button>
                <button type="button" class="me-setup-btn me-setup-btn-text me-setup-skip"><?php esc_html_e('Skip Setup', 'cine-movie-engine'); ?></button>
                <div style="flex:1;"></div>
                <button type="button" class="me-setup-btn me-setup-btn-primary me-setup-next" data-step="1"><?php esc_html_e('Next Step', 'cine-movie-engine'); ?></button>
            </footer>
        </div>
<?php
    }
}
