<?php

namespace MovieEngine\Admin\Api;

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

class ApiSettings {

    public static function render() {
        settings_fields('movie_engine_api');
        $options = get_option('movie_engine_api_settings', []);
        $tmdb_key = $options['movie_engine_tmdb_api_key'] ?? '';
        $omdb_key = $options['movie_engine_omdb_api_key'] ?? '';

        $tmdb_connected = false;
        if (!empty($tmdb_key)) {
            $trans_key = 'movie_engine_tmdb_conn_' . md5($tmdb_key);
            $tmdb_connected = get_transient($trans_key);
            if ($tmdb_connected === false) {
                $tmdb = new \MovieEngine\Api\TmdbClient();
                $tmdb_connected = $tmdb->validate() ? '1' : '0';
                set_transient($trans_key, $tmdb_connected, DAY_IN_SECONDS);
            }
            $tmdb_connected = ($tmdb_connected === '1');
        }

        $omdb_connected = false;
        if (!empty($omdb_key)) {
            $trans_key = 'movie_engine_omdb_conn_' . md5($omdb_key);
            $omdb_connected = get_transient($trans_key);
            if ($omdb_connected === false) {
                $omdb = new \MovieEngine\Api\OmdbClient();
                $omdb_connected = $omdb->validate() ? '1' : '0';
                set_transient($trans_key, $omdb_connected, DAY_IN_SECONDS);
            }
            $omdb_connected = ($omdb_connected === '1');
        }

        $tmdb_error = !empty($tmdb_key) ? get_transient('movie_engine_tmdb_error_' . md5($tmdb_key)) : '';
        $omdb_error = !empty($omdb_key) ? get_transient('movie_engine_omdb_error_' . md5($omdb_key)) : '';

        $stripe_connected = false;
        $stripe_options = get_option('movie_engine_payments_settings', []);
        $stripe_key = $stripe_options['movie_engine_stripe_secret_key'] ?? ($stripe_options['stripe_secret_key'] ?? '');
        $publishable_key = $stripe_options['movie_engine_stripe_publishable_key'] ?? ($stripe_options['stripe_publishable_key'] ?? '');
        $mode = $stripe_options['movie_engine_mode'] ?? ($stripe_options['mode'] ?? 'test');

        if (!empty($stripe_key) && !empty($publishable_key)) {
            $trans_key = 'movie_engine_stripe_conn_' . md5($stripe_key . $publishable_key . $mode);
            $stripe_data = get_transient($trans_key);

            if ($stripe_data === false || !is_array($stripe_data)) {
                if (class_exists('\MovieEnginePro\Payments\StripeClient')) {
                    $stripe = new \MovieEnginePro\Payments\StripeClient();
                    $validation = $stripe->validate_with_error();
                    $stripe_data = [
                        'connected' => $validation['success'] ? '1' : '0'
                    ];
                } else {
                    $stripe_data = ['connected' => '0'];
                }
                set_transient($trans_key, $stripe_data, HOUR_IN_SECONDS);
            }

            $stripe_connected = (isset($stripe_data['connected']) && $stripe_data['connected'] === '1');
        }
?>
        <div class="movie-engine-settings-section">
            <div class="movie-engine-section-header">
                <h2><?php esc_html_e('API Settings', 'cine-movie-engine'); ?></h2>
                <p class="description"><?php esc_html_e('Configure external API integrations for metadata and video sources', 'cine-movie-engine'); ?></p>
            </div>

            <div class="movie-engine-card">
                <div class="movie-engine-card-header">
                    <h3><span class="fa-solid fa-cloud"></span> <?php esc_html_e('TMDb API', 'cine-movie-engine'); ?></h3>
                    <?php if ($tmdb_connected) : ?>
                        <span class="movie-engine-badge movie-engine-badge-success"><?php esc_html_e('Connected', 'cine-movie-engine'); ?></span>
                    <?php else : ?>
                        <div class="movie-engine-status-group">
                            <span class="movie-engine-badge movie-engine-badge-error"><?php esc_html_e('Disconnected', 'cine-movie-engine'); ?></span>
                            <?php if ($tmdb_error) : ?>
                                <span class="movie-engine-error-text"><?php echo esc_html($tmdb_error); ?></span>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </div>
                <div class="movie-engine-card-body">
                    <div class="movie-engine-form-group">
                        <label for="movie_engine_tmdb_api_key"><?php esc_html_e('TMDb API Key', 'cine-movie-engine'); ?></label>
                        <input type="text"
                            id="movie_engine_tmdb_api_key"
                            name="movie_engine_api_settings[movie_engine_tmdb_api_key]"
                            value="<?php echo esc_attr($tmdb_key); ?>"
                            class="movie-engine-input"
                            placeholder="Enter your TMDb API key">
                        <p class="movie-engine-help-text">
                            <?php esc_html_e('Used for Movie/TV metadata, cast, and images. Get it from', 'cine-movie-engine'); ?>
                            <a href="https://www.themoviedb.org/settings/api" target="_blank"><?php esc_html_e('TMDb Settings', 'cine-movie-engine'); ?></a>
                        </p>
                    </div>
                </div>
            </div>

            <?php $omdb_key = $options['movie_engine_omdb_api_key'] ?? ''; ?>
            <div class="movie-engine-card me-mt-20">
                <div class="movie-engine-card-header">
                    <h3><span class="fa-solid fa-star"></span> <?php esc_html_e('OMDb API (IMDb Ratings)', 'cine-movie-engine'); ?></h3>
                    <?php if ($omdb_connected) : ?>
                        <span class="movie-engine-badge movie-engine-badge-success"><?php esc_html_e('Connected', 'cine-movie-engine'); ?></span>
                    <?php else : ?>
                        <div class="movie-engine-status-group">
                            <span class="movie-engine-badge movie-engine-badge-error"><?php esc_html_e('Disconnected', 'cine-movie-engine'); ?></span>
                            <?php if ($omdb_error) : ?>
                                <span class="movie-engine-error-text"><?php echo esc_html($omdb_error); ?></span>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </div>
                <div class="movie-engine-card-body">
                    <div class="movie-engine-form-group">
                        <label for="movie_engine_omdb_api_key"><?php esc_html_e('OMDb API Key', 'cine-movie-engine'); ?></label>
                        <input type="text"
                            id="movie_engine_omdb_api_key"
                            name="movie_engine_api_settings[movie_engine_omdb_api_key]"
                            value="<?php echo esc_attr($omdb_key); ?>"
                            class="movie-engine-input"
                            placeholder="Enter your OMDb API key">
                        <p class="movie-engine-help-text">
                            <?php esc_html_e('Required to show official IMDb, Rotten Tomatoes, and Metacritic ratings. Get it for free at', 'cine-movie-engine'); ?>
                            <a href="http://www.omdbapi.com/apikey.aspx" target="_blank"><?php esc_html_e('OMDb API', 'cine-movie-engine'); ?></a>
                        </p>
                    </div>
                </div>
            </div>

            <?php if (has_action('movie_engine_render_pro_stripe_api_card')) : ?>
                <?php do_action('movie_engine_render_pro_stripe_api_card'); ?>
            <?php else : ?>
                <div class="movie-engine-card me-mt-20">
                    <div class="movie-engine-card-header">
                        <h3><span class="fa-solid fa-shield-halved"></span> <?php esc_html_e('Stripe API (Payments)', 'cine-movie-engine'); ?> <span class="me-pro-badge"><?php esc_html_e('PRO', 'cine-movie-engine'); ?></span></h3>
                        <span class="movie-engine-badge"><span class="dashicons dashicons-lock"></span></span>
                    </div>
                    <div class="movie-engine-card-body">
                        <div class="me-pro-notice-box">
                            <span class="dashicons dashicons-lock"></span>
                            <div class="me-pro-notice-message">
                                <strong><?php esc_html_e('Pro Feature', 'cine-movie-engine'); ?></strong>
                                <p><?php esc_html_e('Upgrade to Movie Engine Pro to accept payments via Stripe.', 'cine-movie-engine'); ?></p>
                            </div>
                            <a href="<?php echo esc_url(\MovieEngine\Admin\Upgrade::get_pro_url('pricing')); ?>" target="_blank" class="button button-primary me-pro-notice-btn"><?php esc_html_e('Upgrade', 'cine-movie-engine'); ?></a>
                        </div>
                        <div style="opacity: 0.5; pointer-events: none; filter: blur(1px); margin-top: 20px;">
                            <p class="description"><?php esc_html_e('Stripe API status used for memberships and PPV.', 'cine-movie-engine'); ?></p>
                            <a href="#" class="movie-engine-btn me-mt-10">
                                <span class="fa-solid fa-gears"></span> <?php esc_html_e('Configure Keys', 'cine-movie-engine'); ?>
                            </a>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <?php
            $external_player_enabled = $options['movie_engine_external_player_enabled'] ?? 0;
            $movie_engine_video_servers = $options['movie_engine_video_servers'] ?? [];
            if (empty($movie_engine_video_servers)) {
                $movie_engine_video_servers[] = [
                    'name' => 'Server 1',
                    'url' => 'https://example.com/embed/movie/{tmdb_id}',
                    'type' => 'movie'
                ];
            }
            ?>
            <?php if (has_action('movie_engine_render_pro_external_player_api_card')) : ?>
                <?php do_action('movie_engine_render_pro_external_player_api_card'); ?>
            <?php else : ?>
                <div class="movie-engine-card me-card-premium">
                    <div class="movie-engine-card-header">
                        <h3>
                            <span class="fa-solid fa-film"></span>
                            <?php esc_html_e('External Player API', 'cine-movie-engine'); ?>
                            <span class="me-pro-badge"><?php esc_html_e('PRO', 'cine-movie-engine'); ?></span>
                        </h3>
                        <span class="movie-engine-badge"><span class="dashicons dashicons-lock"></span></span>
                    </div>
                    <div class="movie-engine-card-body">

                        <div class="me-pro-notice-box">
                            <span class="dashicons dashicons-lock"></span>
                            <div class="me-pro-notice-message">
                                <strong><?php esc_html_e('Pro Feature', 'cine-movie-engine'); ?></strong>
                                <p><?php esc_html_e('Upgrade to automatically generate video sources from external APIs.', 'cine-movie-engine'); ?></p>
                            </div>
                            <a href="<?php echo esc_url(\MovieEngine\Admin\Upgrade::get_pro_url('pricing')); ?>" target="_blank" class="button button-primary me-pro-notice-btn"><?php esc_html_e('Upgrade', 'cine-movie-engine'); ?></a>
                        </div>

                        <div style="opacity: 0.5; pointer-events: none; filter: blur(1px);">
                            <div class="movie-engine-form-group" style="margin-bottom: 20px;">
                                <label class="movie-engine-checkbox-label">
                                    <input type="checkbox" disabled>
                                    <span><?php esc_html_e('Enable External Player API', 'cine-movie-engine'); ?></span>
                                </label>
                                <p class="description"><?php esc_html_e('When enabled, external video player sources will be automatically generated based on the server configurations below.', 'cine-movie-engine'); ?></p>
                            </div>

                            <div id="movie-engine-external-player-settings">
                                <p class="description">
                                    <?php esc_html_e('Define external video players that support embedding via IDs.', 'cine-movie-engine'); ?><br>
                                </p>
                                <div class="movie-engine-video-servers-list">
                                    <div class="video-server-header">
                                        <span><?php esc_html_e('Server Name', 'cine-movie-engine'); ?></span>
                                        <span><?php esc_html_e('Embed URL Template', 'cine-movie-engine'); ?></span>
                                        <span><?php esc_html_e('Type', 'cine-movie-engine'); ?></span>
                                    </div>
                                    <div class="movie-engine-repeater-row">
                                        <div><input type="text" class="movie-engine-input" placeholder="Server 1" disabled></div>
                                        <div><input type="text" class="movie-engine-input" placeholder="https://example.com/embed/{tmdb_id}" disabled></div>
                                        <div><select class="movie-engine-input" disabled>
                                                <option>Movies Only</option>
                                            </select></div>
                                    </div>
                                    <button type="button" class="movie-engine-btn" disabled>
                                        <span class="fa-solid fa-plus"></span> <?php esc_html_e('Add New Server', 'cine-movie-engine'); ?>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <div class="movie-engine-form-actions">
                <button type="submit" name="submit" id="submit" class="movie-engine-btn me-btn-primary"><?php esc_html_e('Save Changes', 'cine-movie-engine'); ?></button>
            </div>

    <?php
    }
}
