<?php
/**
 * Cast Conductor Proprietary License v5
 * SPDX-License-Identifier: LicenseRef-CastConductor-Proprietary-v5
 * 
 * Copyright (c) 2025 CastConductor.com. All Rights Reserved.
 * 
 * This file is part of Cast Conductor ("Software"). The Software and its source
 * code constitute proprietary, confidential, and trade secret information of
 * CastConductor.com ("Company"). Any access or use is governed strictly by the
 * Cast Conductor Proprietary License v5 ("License"). By installing, copying,
 * accessing, compiling, or otherwise using the Software you agree to be bound by
 * all terms of the License. If you do not agree, you must cease use immediately.
 * 
 * Key Terms (Summary – see full License for binding terms):
 *  1. No Redistribution: You may not publish, distribute, sublicense, rent,
 *     lease, transfer, sell, or otherwise make the Software (or any derivative)
 *     available to any third party without prior written consent of Company.
 *  2. No Modification: Modification, reverse engineering, decompilation, or
 *     disassembly is prohibited except to the limited extent expressly permitted
 *     by applicable law that cannot be contractually waived.
 *  3. Confidentiality: Treat all source code and related artifacts as Company
 *     Confidential Information. Maintain at least the same degree of care as for
 *     your own confidential materials, and not less than reasonable care.
 *  4. No Patent License: No express or implied patent rights are granted. Future
 *     patents (if any) are fully reserved.
 *  5. No Trademark License: Company names, marks, and logos may not be used
 *     without prior written permission.
 *  6. Limited Internal Use: Use is limited solely to internal evaluation and
 *     operation of licensed Cast Conductor deployments. Commercial hosting or
 *     resale as a service requires a separate written agreement.
 *  7. Telemetry & License Validation: The Software may periodically transmit a
 *     hashed installation identifier, domain (or site ID), plugin/app version,
 *     and a truncated (non-reversible) fragment of the license key solely to
 *     validate activation status and enforce licensing. This minimal "phone home"
 *     check contains no personal or content data. If optional telemetry is later
 *     introduced it will be limited to aggregate operational metrics (no PII),
 *     fully documented, and optionally disableable per published instructions.
 *  8. Third-Party Components: The Software may include open source components
 *     covered by their own licenses. See THIRD-PARTY-NOTICES.md. Those licenses
 *     govern their respective components; this License governs all remaining code.
 *  9. Export Compliance: You are responsible for compliance with all applicable
 *     export control and sanctions laws.
 * 10. Warranty Disclaimer: THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF
 *     ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO MERCHANTABILITY,
 *     FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT.
 * 11. Limitation of Liability: IN NO EVENT WILL COMPANY OR AUTHORS BE LIABLE FOR
 *     ANY INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL, EXEMPLARY, OR PUNITIVE
 *     DAMAGES, OR LOST PROFITS, EVEN IF ADVISED OF THE POSSIBILITY.
 * 12. Acceptance: Use of the Software constitutes acceptance of the License.
 * 13. Enforcement: Unauthorized reproduction or distribution may result in civil
 *     and criminal penalties and will be prosecuted to the maximum extent allowed
 *     by law.
 * 
 * Authoritative EULA: EULA-v5.1.md (repository root – private) and https://castconductor.com/eula
 * Precedence: If this summary conflicts with the EULA, the EULA governs.
 * Revision: Current EULA revision v5.1 (subject to update; check EULA for current enterprise thresholds).
 * 
 * Full License text available from: licensing@castconductor.com
 * Security reports: security@castconductor.com
 * Commercial inquiries: licensing@castconductor.com
 * 
 * END OF HEADER
 */

/**
 * CastConductor Admin Interface
 * 
 * Handles WordPress admin interface and menu system
 */

if (!defined('ABSPATH')) {
    exit;
}

class CastConductor_Admin {
    
    /**
     * Constructor
     */
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        add_action('admin_init', array($this, 'admin_init'));
        add_action('add_meta_boxes', array($this, 'add_meta_boxes'));
        add_action('save_post', array($this, 'save_meta_boxes'));
        
        // AJAX handler for clearing feed cache
        add_action('wp_ajax_castconductor_clear_feed_cache', array($this, 'ajax_clear_feed_cache'));
    }
    
    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        // Main menu
        add_menu_page(
            __('CastConductor', 'castconductor'),
            __('CastConductor', 'castconductor'),
            'edit_posts',  // Allow editors access to CastConductor
            'castconductor',
            array($this, 'dashboard_page'),
            'data:image/svg+xml;base64,' . base64_encode('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="currentColor" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>'),
            30
        );
        
        // Dashboard
        add_submenu_page(
            'castconductor',
            __('Dashboard', 'castconductor'),
            __('Dashboard', 'castconductor'),
            'edit_posts',  // Allow editors access
            'castconductor',
            array($this, 'dashboard_page')
        );
        
        // Content Blocks and Canvas Editor are handled by class-castconductor-content-blocks.php
        // This prevents duplicate menu entries
        
        // API Endpoints
        add_submenu_page(
            'castconductor',
            __('API Endpoints', 'castconductor'),
            __('API Endpoints', 'castconductor'),
            'edit_posts',  // Allow editors to view API endpoints
            'castconductor-api-endpoints',
            array($this, 'api_endpoints_page')
        );
        
        // Settings - Hidden from non-super-admins on Multisite (demo mode)
        if (!is_multisite() || is_super_admin()) {
            add_submenu_page(
                'castconductor',
                __('Settings', 'castconductor'),
                __('Settings', 'castconductor'),
                'manage_options',
                'castconductor-settings',
                array($this, 'settings_page')
            );
        }
        
        // Data Management - Hidden from non-super-admins on Multisite (demo mode)
        if (!is_multisite() || is_super_admin()) {
            add_submenu_page(
                'castconductor',
                __('Data Management', 'castconductor'),
                __('Data Management', 'castconductor'),
                'manage_options',
                'castconductor-data-management',
                array($this, 'data_management_page')
            );
        }
        
        // CPT Manager - Admin only (can break site configuration)
        if (!is_multisite() || is_super_admin()) {
            add_submenu_page(
                'castconductor',
                __('Content Type Manager', 'castconductor'),
                __('Content Types', 'castconductor'),
                'manage_options',
                'castconductor-cpt-manager',
                array($this, 'cpt_manager_page')
            );
        }
        
        // Setup Wizard (if not completed) - Admin only
        if (!get_option('castconductor_setup_completed') && (!is_multisite() || is_super_admin())) {
            add_submenu_page(
                'castconductor',
                __('Setup Wizard', 'castconductor'),
                __('🚀 Setup Wizard', 'castconductor'),
                'manage_options',
                'castconductor-setup',
                array($this, 'setup_wizard_page')
            );
        }
    }
    
    /**
     * Enqueue admin scripts and styles
     */
    public function enqueue_admin_scripts($hook) {
        // Only load on CastConductor pages
        if (strpos($hook, 'castconductor') === false) {
            return;
        }
        
        // Ensure WordPress media library is available for image pickers
        if (function_exists('wp_enqueue_media')) {
            wp_enqueue_media();
        }

        wp_enqueue_style(
            'castconductor-admin',
            CASTCONDUCTOR_PLUGIN_URL . 'assets/css/admin.css',
            array(),
            CASTCONDUCTOR_VERSION
        );
        
        wp_enqueue_script(
            'castconductor-admin',
            CASTCONDUCTOR_PLUGIN_URL . 'assets/js/admin.js',
            array('jquery', 'wp-api'),
            CASTCONDUCTOR_VERSION,
            true
        );
        
        // Localize script
        wp_localize_script('castconductor-admin', 'castconductor_admin', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'api_url' => home_url('/wp-json/castconductor/v5/'),
            'nonce' => wp_create_nonce('castconductor_admin'),
            // Add REST nonce so admin JS can call protected REST endpoints (e.g., content-blocks)
            'rest_nonce' => wp_create_nonce('wp_rest'),
            'version' => CASTCONDUCTOR_VERSION
        ));
    }
    
    /**
     * Admin initialization
     */
    public function admin_init() {
        // Register settings
        $this->register_settings();
    }
    
    /**
     * Register plugin settings
     */
    private function register_settings() {
        // URL Configuration Settings
        register_setting('castconductor_settings', 'castconductor_stream_url', array(
            'type' => 'string',
            'sanitize_callback' => 'esc_url_raw',
            'default' => ''
        ));
        
        register_setting('castconductor_settings', 'castconductor_video_url', array(
            'type' => 'string',
            'sanitize_callback' => 'esc_url_raw',
            'default' => ''
        ));
        
        register_setting('castconductor_settings', 'castconductor_streaming_mode', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => 'auto'
        ));
        
        // Phase 4: Playback Mode (dual source support)
        register_setting('castconductor_settings', 'castconductor_playback_mode', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => 'standard'
        ));
        
        register_setting('castconductor_settings', 'castconductor_metadata_url', array(
            'type' => 'string',
            'sanitize_callback' => 'esc_url_raw',
            'default' => ''
        ));
        
        // API Keys
        register_setting('castconductor_settings', 'castconductor_openweather_api_key', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => ''
        ));
        
        // Feature Toggles
        register_setting('castconductor_settings', 'castconductor_artwork_search_enabled', array(
            'type' => 'boolean',
            'default' => true
        ));
        
        register_setting('castconductor_settings', 'castconductor_geolocation_enabled', array(
            'type' => 'boolean',
            'default' => true
        ));

        // Branding attachments (store attachment IDs)
        register_setting('castconductor_settings', 'castconductor_current_square_logo_600x600', array(
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => 0,
        ));

        register_setting('castconductor_settings', 'castconductor_current_animated_center_logo_1280x250', array(
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => 0,
        ));

        register_setting('castconductor_settings', 'castconductor_current_background_1920x1080', array(
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => 0,
        ));

        // Scene rotation interval (seconds)
        register_setting('castconductor_settings', 'castconductor_scene_rotation_interval', array(
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => 60
        ));

        // Roku App Configuration (separate settings group to avoid conflicts with main settings)
        register_setting('castconductor_roku_settings', 'castconductor_channel_name', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => ''
        ));

        register_setting('castconductor_roku_settings', 'castconductor_app_name', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => ''
        ));

        // Roku Channel Artwork (store attachment IDs)
        // Matches Toaster specs exactly
        register_setting('castconductor_roku_settings', 'castconductor_roku_icon_fhd', array(
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => 0
        ));

        register_setting('castconductor_roku_settings', 'castconductor_roku_icon_hd', array(
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => 0
        ));

        register_setting('castconductor_roku_settings', 'castconductor_roku_splash_fhd', array(
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => 0
        ));

        register_setting('castconductor_roku_settings', 'castconductor_roku_splash_hd', array(
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => 0
        ));

        register_setting('castconductor_roku_settings', 'castconductor_roku_splash_sd', array(
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => 0
        ));
    }
    
    /**
     * AJAX handler for clearing feed cache
     * 
     * Deletes all cc_feed_* transients from the database
     * 
     * @since 5.7.4
     */
    public function ajax_clear_feed_cache() {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'castconductor_clear_feed_cache')) {
            wp_send_json_error('Invalid security token');
            return;
        }
        
        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permission denied');
            return;
        }
        
        global $wpdb;
        
        // Count existing transients before deletion
        $count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->options} WHERE option_name LIKE '_transient_cc_feed_%'");
        
        // Delete transients and their timeouts
        $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_cc_feed_%'");
        $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_cc_feed_%'");
        
        wp_send_json_success(array(
            'message' => sprintf(
                _n('Cleared %d cached feed', 'Cleared %d cached feeds', $count, 'castconductor'),
                $count
            ),
            'count' => $count
        ));
    }
    
    /**
     * Dashboard page
     */
    public function dashboard_page() {
        $setup_completed = get_option('castconductor_setup_completed');
        $setup_date = get_option('castconductor_setup_date');
        
        ?>
        <div class="wrap">
            <h1>
                <?php _e('CastConductor V5 Dashboard', 'castconductor'); ?>
                <span style="font-size: 12px; font-weight: normal; background: #2271b1; color: #fff; padding: 3px 8px; border-radius: 3px; margin-left: 10px; vertical-align: middle;">v<?php echo esc_html(CASTCONDUCTOR_VERSION); ?></span>
            </h1>
            
            <?php if (!$setup_completed): ?>
                <div class="notice notice-warning">
                    <h3><?php _e('🚀 Setup Required', 'castconductor'); ?></h3>
                    <p><?php _e('Complete the setup wizard to configure your CastConductor installation.', 'castconductor'); ?></p>
                    <p>
                        <a href="<?php echo admin_url('admin.php?page=castconductor-setup&from_dashboard=1'); ?>" class="button button-primary">
                            <?php _e('Run Setup Wizard', 'castconductor'); ?>
                        </a>
                    </p>
                </div>
            <?php else: ?>
                <div class="notice notice-success">
                    <h3><?php _e('✅ Setup Completed', 'castconductor'); ?></h3>
                    <p><?php printf(__('Setup completed on %s. Your station is ready!', 'castconductor'), $setup_date); ?></p>
                </div>
            <?php endif; ?>
            
            <div class="castconductor-dashboard">
                <div class="dashboard-widgets">
                    
                    <!-- System Status -->
                    <div class="dashboard-widget">
                        <h3><?php _e('📊 System Status', 'castconductor'); ?></h3>
                        <div class="widget-content">
                            <?php $this->render_system_status(); ?>
                        </div>
                    </div>
                    
                    <!-- Quick Stats -->
                    <div class="dashboard-widget">
                        <h3><?php _e('📈 Quick Stats', 'castconductor'); ?></h3>
                        <div class="widget-content">
                            <?php $this->render_quick_stats(); ?>
                        </div>
                    </div>
                    
                    <!-- Recent Activity -->
                    <div class="dashboard-widget">
                        <h3><?php _e('📝 Recent Activity', 'castconductor'); ?></h3>
                        <div class="widget-content">
                            <?php $this->render_recent_activity(); ?>
                        </div>
                    </div>
                    
                    <!-- API Endpoints -->
                    <div class="dashboard-widget">
                        <h3><?php _e('🔗 API Quick Access', 'castconductor'); ?></h3>
                        <div class="widget-content">
                            <?php $this->render_api_quick_access(); ?>
                        </div>
                    </div>
                    
                </div>
            </div>
        </div>
        <?php
    }
    
    /**
     * Render system status widget
     */
    private function render_system_status() {
        $stream_url = get_option('castconductor_stream_url');
        $metadata_url = get_option('castconductor_metadata_url');
        $weather_key = get_option('castconductor_openweather_api_key');
        
        echo '<ul class="status-list">';
        
        // Stream URL
        if (!empty($stream_url)) {
            echo '<li class="status-ok">✅ Stream URL configured</li>';
        } else {
            echo '<li class="status-warning">⚠️ Stream URL not configured</li>';
        }
        
        // Metadata URL
        if (!empty($metadata_url)) {
            echo '<li class="status-ok">✅ Metadata API configured</li>';
        } else {
            echo '<li class="status-warning">⚠️ Metadata API not configured</li>';
        }
        
        // Weather API
        if (!empty($weather_key)) {
            echo '<li class="status-ok">✅ Weather API configured</li>';
        } else {
            echo '<li class="status-info">ℹ️ Weather API optional</li>';
        }
        
        // Database
        global $wpdb;
        $containers_table = $wpdb->prefix . 'castconductor_containers';
        if ($wpdb->get_var("SHOW TABLES LIKE '{$containers_table}'") === $containers_table) {
            echo '<li class="status-ok">✅ Database tables ready</li>';
        } else {
            echo '<li class="status-error">❌ Database tables missing</li>';
        }
        
        echo '</ul>';
    }
    
    /**
     * Render quick stats widget
     */
    private function render_quick_stats() {
        global $wpdb;
        
        // Count content
        $shoutouts = wp_count_posts('cc_shoutout')->publish ?? 0;
        $sponsors = wp_count_posts('cc_sponsor')->publish ?? 0;
        $promos = wp_count_posts('cc_promo')->publish ?? 0;
        
        // Count content blocks
        $blocks_table = $wpdb->prefix . 'castconductor_content_blocks';
        $content_blocks = $wpdb->get_var("SELECT COUNT(*) FROM {$blocks_table} WHERE enabled = 1") ?? 0;
        
        // Count containers
        $containers_table = $wpdb->prefix . 'castconductor_containers';
        $containers = $wpdb->get_var("SELECT COUNT(*) FROM {$containers_table} WHERE enabled = 1") ?? 0;
        
        echo '<div class="stats-grid">';
        echo '<div class="stat-item"><span class="stat-number">' . $content_blocks . '</span><span class="stat-label">Active Content Blocks</span></div>';
        echo '<div class="stat-item"><span class="stat-number">' . $containers . '</span><span class="stat-label">Active Containers</span></div>';
        echo '<div class="stat-item"><span class="stat-number">' . $shoutouts . '</span><span class="stat-label">Shoutouts</span></div>';
        echo '<div class="stat-item"><span class="stat-number">' . $sponsors . '</span><span class="stat-label">Sponsors</span></div>';
        echo '<div class="stat-item"><span class="stat-number">' . $promos . '</span><span class="stat-label">Promos</span></div>';
        echo '</div>';
    }
    
    /**
     * Render recent activity widget
     */
    private function render_recent_activity() {
        $recent_shoutouts = get_posts(array(
            'post_type' => 'cc_shoutout',
            'posts_per_page' => 3,
            'post_status' => 'publish'
        ));
        
        if (empty($recent_shoutouts)) {
            echo '<p>' . __('No recent activity. Create some test content with the setup wizard!', 'castconductor') . '</p>';
            return;
        }
        
        echo '<ul class="activity-list">';
        foreach ($recent_shoutouts as $shoutout) {
            $name = get_post_meta($shoutout->ID, 'cc_shoutout_name', true);
            $location = get_post_meta($shoutout->ID, 'cc_shoutout_location', true);
            $time_diff = human_time_diff(strtotime($shoutout->post_date));
            
            echo '<li>';
            echo '<strong>' . esc_html($name) . '</strong> from ' . esc_html($location);
            echo '<br><small>' . $time_diff . ' ago</small>';
            echo '</li>';
        }
        echo '</ul>';
    }
    
    /**
     * Render API quick access widget
     */
    private function render_api_quick_access() {
        $base_url = home_url('/wp-json/castconductor/v5');
        
        $endpoints = array(
            'Master App Config' => $base_url . '/roku/app-config',
            'Active Shoutouts' => $base_url . '/content/shoutouts/active',
            'Active Sponsors' => $base_url . '/content/sponsors/active',
            'Album Artwork Search' => $base_url . '/artwork/search'
        );
        
        echo '<div class="api-endpoints">';
        foreach ($endpoints as $name => $url) {
            echo '<div class="endpoint-item">';
            echo '<label>' . $name . ':</label>';
            echo '<div class="endpoint-url">';
            echo '<input type="text" value="' . esc_attr($url) . '" readonly onclick="this.select()">';
            echo '<button class="button button-small copy-endpoint" data-url="' . esc_attr($url) . '">Copy</button>';
            echo '<a href="' . esc_attr($url) . '" target="_blank" class="button button-small">View</a>';
            echo '</div>';
            echo '</div>';
        }
        echo '</div>';
    }

    /**
     * Render Roku App Settings section
     * 
     * Displays channel name, app name, artwork uploads, status checklist, and Toaster launch button
     * 
     * @since 5.7.14
     */
    private function render_roku_app_settings() {
        // Get current settings
        $channel_name = get_option('castconductor_channel_name', '');
        $app_name = get_option('castconductor_app_name', '');
        $license_key = get_option('castconductor_license_key', '');
        $stream_url = get_option('castconductor_stream_url', '');
        $metadata_url = get_option('castconductor_metadata_url', '');
        
        // Roku artwork attachment IDs - matches Toaster specs exactly
        $artwork = array(
            'icon_fhd' => array(
                'id' => (int) get_option('castconductor_roku_icon_fhd', 0),
                'label' => __('Channel Icon (FHD)', 'castconductor'),
                'size' => '540×405',
                'format' => 'PNG',
                'option' => 'castconductor_roku_icon_fhd',
                'required' => true
            ),
            'icon_hd' => array(
                'id' => (int) get_option('castconductor_roku_icon_hd', 0),
                'label' => __('Channel Icon (HD)', 'castconductor'),
                'size' => '290×218',
                'format' => 'PNG',
                'option' => 'castconductor_roku_icon_hd',
                'required' => true
            ),
            'splash_fhd' => array(
                'id' => (int) get_option('castconductor_roku_splash_fhd', 0),
                'label' => __('Splash Screen (FHD)', 'castconductor'),
                'size' => '1920×1080',
                'format' => 'JPG',
                'option' => 'castconductor_roku_splash_fhd',
                'required' => true
            ),
            'splash_hd' => array(
                'id' => (int) get_option('castconductor_roku_splash_hd', 0),
                'label' => __('Splash Screen (HD)', 'castconductor'),
                'size' => '1280×720',
                'format' => 'JPG',
                'option' => 'castconductor_roku_splash_hd',
                'required' => true
            ),
            'splash_sd' => array(
                'id' => (int) get_option('castconductor_roku_splash_sd', 0),
                'label' => __('Splash Screen (SD)', 'castconductor'),
                'size' => '720×480',
                'format' => 'JPG',
                'option' => 'castconductor_roku_splash_sd',
                'required' => true
            ),
        );
        
        // Check completeness
        $missing_items = array();
        if (empty($channel_name)) $missing_items[] = __('Channel Name', 'castconductor');
        if (empty($app_name)) $missing_items[] = __('App Name', 'castconductor');
        foreach ($artwork as $key => $item) {
            if ($item['required'] && $item['id'] === 0) {
                $missing_items[] = $item['label'] . ' (' . $item['size'] . ')';
            }
        }
        $is_complete = empty($missing_items);
        
        ?>
        <form method="post" action="options.php" id="roku-app-settings-form">
            <?php settings_fields('castconductor_roku_settings'); ?>
            
            <table class="form-table" style="margin-bottom: 20px;">
                <tr>
                    <th scope="row"><?php _e('Channel Name', 'castconductor'); ?></th>
                    <td>
                        <input type="text" name="castconductor_channel_name" value="<?php echo esc_attr($channel_name); ?>" class="regular-text" placeholder="<?php esc_attr_e('My Radio Station', 'castconductor'); ?>" />
                        <p class="description"><?php _e('The name displayed on Roku channel store and in the channel itself.', 'castconductor'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php _e('App Name', 'castconductor'); ?></th>
                    <td>
                        <input type="text" name="castconductor_app_name" value="<?php echo esc_attr($app_name); ?>" class="regular-text" placeholder="<?php esc_attr_e('MyStation', 'castconductor'); ?>" maxlength="20" />
                        <p class="description"><?php _e('Short name for the app (max 20 characters, no spaces recommended).', 'castconductor'); ?></p>
                    </td>
                </tr>
            </table>
            
            <h3 style="margin-top: 30px; margin-bottom: 15px;">🎨 <?php _e('Channel Artwork', 'castconductor'); ?></h3>
            <p class="description" style="margin-bottom: 20px;">
                <?php _e('Upload the required artwork for your Roku channel. All 5 images are required to build your app.', 'castconductor'); ?>
            </p>
            
            <div class="cc-roku-artwork-grid" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 20px; margin-bottom: 20px;">
                <?php foreach ($artwork as $key => $item): 
                    $url = $item['id'] ? wp_get_attachment_image_url($item['id'], 'medium') : '';
                    $format = isset($item['format']) ? $item['format'] : '';
                ?>
                <div class="cc-roku-artwork-item" style="background: #f6f7f7; padding: 15px; border-radius: 4px;">
                    <label style="display: block; font-weight: 600; margin-bottom: 8px;">
                        <?php echo esc_html($item['label']); ?>
                    </label>
                    <small style="display: block; color: #666; margin-bottom: 8px;"><?php echo esc_html($item['size']); ?> <?php echo esc_html($format); ?></small>
                    <div class="cc-media-control" data-option="<?php echo esc_attr($item['option']); ?>">
                        <div class="cc-media-preview" style="margin: 8px 0; min-height: 80px; background: #fff; border: 1px dashed #c3c4c7; border-radius: 4px; display: flex; align-items: center; justify-content: center;">
                            <img src="<?php echo esc_url($url); ?>" style="max-width: 100%; max-height: 120px; <?php echo $url ? '' : 'display: none;'; ?>" alt="" />
                            <span class="cc-media-placeholder" style="color: #999; <?php echo $url ? 'display: none;' : ''; ?>">❌ <?php _e('Not uploaded', 'castconductor'); ?></span>
                        </div>
                        <input type="hidden" name="<?php echo esc_attr($item['option']); ?>" value="<?php echo esc_attr($item['id']); ?>" />
                        <button type="button" class="button cc-select-media" data-title="<?php printf(esc_attr__('Select %s', 'castconductor'), $item['label']); ?>" data-button="<?php esc_attr_e('Use this image', 'castconductor'); ?>"><?php _e('Select Image', 'castconductor'); ?></button>
                        <button type="button" class="button cc-clear-media" style="margin-left: 6px; <?php echo $item['id'] ? '' : 'display:none;'; ?>"><?php _e('Clear', 'castconductor'); ?></button>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            
            <?php submit_button(__('Save Roku Settings', 'castconductor'), 'secondary', 'submit', false); ?>
        </form>
        
        <!-- Artwork Status Checklist -->
        <div style="margin-top: 30px; padding: 20px; background: <?php echo $is_complete ? '#d1e7dd' : '#fff3cd'; ?>; border-radius: 4px; border-left: 4px solid <?php echo $is_complete ? '#198754' : '#ffc107'; ?>;">
            <h4 style="margin: 0 0 15px 0;">
                <?php if ($is_complete): ?>
                    ✅ <?php _e('Ready to Build!', 'castconductor'); ?>
                <?php else: ?>
                    ⚠️ <?php _e('Complete the following to enable Toaster:', 'castconductor'); ?>
                <?php endif; ?>
            </h4>
            
            <?php if (!$is_complete): ?>
                <ul style="margin: 0; padding-left: 20px;">
                    <?php foreach ($missing_items as $item): ?>
                        <li style="color: #856404;">❌ <?php echo esc_html($item); ?></li>
                    <?php endforeach; ?>
                </ul>
            <?php else: ?>
                <p style="margin: 0 0 15px 0;"><?php _e('All required settings and artwork are configured. Click below to launch the Toaster with your settings pre-filled.', 'castconductor'); ?></p>
                
                <?php
                // Build Toaster URL with all parameters
                $toaster_url = $this->build_toaster_url($channel_name, $app_name, $license_key, $stream_url, $metadata_url, $artwork);
                ?>
                
                <a href="<?php echo esc_url($toaster_url); ?>" target="_blank" class="button button-primary button-hero" style="font-size: 16px;">
                    🚀 <?php _e('Launch Toaster with Current Settings', 'castconductor'); ?>
                </a>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Build the Toaster URL with pre-filled parameters
     * 
     * @param string $channel_name Channel display name
     * @param string $app_name Short app name
     * @param string $license_key License key
     * @param string $stream_url Audio/video stream URL
     * @param string $metadata_url Metadata API URL
     * @param array $artwork Array of artwork with attachment IDs
     * @return string Full Toaster URL with query parameters
     * 
     * @since 5.7.14
     */
    private function build_toaster_url($channel_name, $app_name, $license_key, $stream_url, $metadata_url, $artwork) {
        $base_url = 'https://toaster.castconductor.com/';
        
        $params = array(
            'license' => $license_key,
            'domain' => wp_parse_url(home_url(), PHP_URL_HOST),
            'channel_name' => $channel_name,
            'app_name' => $app_name,
        );
        
        // Add optional URLs
        if (!empty($stream_url)) {
            $params['stream_url'] = $stream_url;
        }
        
        // Auto-generate metadata URL if not set
        if (empty($metadata_url)) {
            $metadata_url = home_url('/wp-json/castconductor/v5/icecast');
        }
        $params['metadata_url'] = $metadata_url;
        
        // Add artwork URLs
        foreach ($artwork as $key => $item) {
            if ($item['id'] > 0) {
                $url = wp_get_attachment_url($item['id']);
                if ($url) {
                    $params[$key] = $url;
                }
            }
        }
        
        return add_query_arg($params, $base_url);
    }
    
    /**
     * Content blocks page
     */
    public function content_blocks_page() {
        ?>
        <div class="wrap">
            <h1><?php _e('Content Blocks', 'castconductor'); ?></h1>
            <p><?php _e('Manage your content blocks. Each block provides real data to your Roku app.', 'castconductor'); ?></p>
            
            <div id="castconductor-content-blocks-app">
                <!-- React app will be mounted here -->
                <p><?php _e('Loading content blocks...', 'castconductor'); ?></p>
            </div>
        </div>
        <?php
    }
    
    /**
     * Containers page
     */
    public function containers_page() {
        ?>
        <div class="wrap">
            <h1><?php _e('Containers', 'castconductor'); ?></h1>
            <p><?php _e('Manage layout containers for your Roku app overlay system.', 'castconductor'); ?></p>
            
            <div id="castconductor-containers-app">
                <!-- React app will be mounted here -->
                <p><?php _e('Loading containers...', 'castconductor'); ?></p>
            </div>
        </div>
        <?php
    }
    
    /**
     * Canvas editor page
     */
    public function canvas_editor_page() {
        ?>
        <div class="wrap">
            <h1><?php _e('Canvas Editor', 'castconductor'); ?></h1>
            <p><?php _e('Visual design interface for creating and editing content blocks.', 'castconductor'); ?></p>
            
            <div id="castconductor-canvas-editor-app">
                <!-- React app will be mounted here -->
                <p><?php _e('Loading canvas editor...', 'castconductor'); ?></p>
            </div>
        </div>
        <?php
    }
    
    /**
     * API endpoints page
     */
    public function api_endpoints_page() {
        ?>
        <div class="wrap">
            <h1><?php _e('🔗 API Endpoints', 'castconductor'); ?></h1>
            <p><?php _e('Live endpoint browser with copy-paste functionality for development and testing.', 'castconductor'); ?></p>
            
            <div class="api-endpoints-browser">
                <!-- Will be populated by JavaScript -->
                <p><?php _e('Loading API endpoints...', 'castconductor'); ?></p>
            </div>
        </div>
        <?php
    }
    
    /**
     * Settings page
     */
    public function settings_page() {
        ?>
        <div class="wrap">
            <h1>
                <?php _e('CastConductor Settings', 'castconductor'); ?>
                <span style="font-size: 12px; font-weight: normal; background: #2271b1; color: #fff; padding: 3px 8px; border-radius: 3px; margin-left: 10px; vertical-align: middle;">v<?php echo esc_html(CASTCONDUCTOR_VERSION); ?></span>
            </h1>
            
            <?php
            // License section (rendered via hook)
            do_action('castconductor_settings_license_section');
            ?>
            
            <!-- Shoutout Embed Shortcode Section -->
            <div class="card" style="max-width: 800px; margin-bottom: 20px; padding: 20px;">
                <h2 style="margin-top: 0;"><?php _e('Embed Shoutout Form', 'castconductor'); ?></h2>
                <p class="description" style="margin-bottom: 15px;">
                    <?php _e('Use this shortcode to embed the shoutout submission form on any page, post, or widget area on your website.', 'castconductor'); ?>
                </p>
                <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 15px;">
                    <code id="shoutout-shortcode" style="padding: 12px 18px; background: #f0f0f1; border: 1px solid #c3c4c7; border-radius: 4px; font-size: 14px; font-family: monospace;">[castconductor_shoutout_form]</code>
                    <button type="button" id="copy-shoutout-shortcode" class="button button-primary" onclick="
                        navigator.clipboard.writeText('[castconductor_shoutout_form]').then(function() {
                            var btn = document.getElementById('copy-shoutout-shortcode');
                            var originalText = btn.innerHTML;
                            btn.innerHTML = '<?php esc_attr_e('Copied!', 'castconductor'); ?> ✓';
                            btn.disabled = true;
                            setTimeout(function() {
                                btn.innerHTML = originalText;
                                btn.disabled = false;
                            }, 2000);
                        });
                    ">
                        <span class="dashicons dashicons-clipboard" style="margin-right: 5px; vertical-align: text-bottom;"></span>
                        <?php _e('Copy Shortcode', 'castconductor'); ?>
                    </button>
                </div>
                <details>
                    <summary style="cursor: pointer; font-weight: 500; color: #2271b1;"><?php _e('Advanced Shortcode Options', 'castconductor'); ?></summary>
                    <div style="margin-top: 12px; padding: 15px; background: #f6f7f7; border-radius: 4px;">
                        <p style="margin: 0 0 10px 0;"><strong><?php _e('Dark Theme:', 'castconductor'); ?></strong></p>
                        <code style="display: block; margin-bottom: 15px; padding: 8px; background: #fff;">[castconductor_shoutout_form theme="dark"]</code>
                        
                        <p style="margin: 0 0 10px 0;"><strong><?php _e('Custom Button Text:', 'castconductor'); ?></strong></p>
                        <code style="display: block; margin-bottom: 15px; padding: 8px; background: #fff;">[castconductor_shoutout_form button_text="Send Your Shoutout!"]</code>
                        
                        <p style="margin: 0 0 10px 0;"><strong><?php _e('Custom Width:', 'castconductor'); ?></strong></p>
                        <code style="display: block; margin-bottom: 15px; padding: 8px; background: #fff;">[castconductor_shoutout_form width="400px"]</code>
                        
                        <p style="margin: 0 0 10px 0;"><strong><?php _e('Custom Placeholders:', 'castconductor'); ?></strong></p>
                        <code style="display: block; margin-bottom: 15px; padding: 8px; background: #fff;">[castconductor_shoutout_form placeholder_name="Your Name" placeholder_message="What do you want to say?"]</code>
                        
                        <p style="margin: 0 0 10px 0;"><strong><?php _e('Full Example:', 'castconductor'); ?></strong></p>
                        <code style="display: block; padding: 8px; background: #fff; font-size: 12px;">[castconductor_shoutout_form theme="dark" width="500px" button_text="Shout it!" placeholder_name="Name" placeholder_location="City" placeholder_message="Your message..."]</code>
                    </div>
                </details>
            </div>
            
            <form method="post" action="options.php">
                <?php settings_fields('castconductor_settings'); ?>
                <?php do_settings_sections('castconductor_settings'); ?>
                
                <table class="form-table">
                    <tr>
                        <th scope="row"><?php _e('Branding', 'castconductor'); ?></th>
                        <td>
                            <p class="description"><?php _e('Upload or choose your default branding assets. These are used across content blocks and containers unless overridden.', 'castconductor'); ?></p>

                            <?php
                                $square_id = (int) get_option('castconductor_current_square_logo_600x600');
                                $square_url = $square_id ? wp_get_attachment_image_url($square_id, 'medium') : '';
                                $horiz_id = (int) get_option('castconductor_current_animated_center_logo_1280x250');
                                $horiz_url = $horiz_id ? wp_get_attachment_image_url($horiz_id, 'large') : '';
                                $bg_id = (int) get_option('castconductor_current_background_1920x1080');
                                $bg_url = $bg_id ? wp_get_attachment_image_url($bg_id, 'large') : '';
                            ?>

                            <div class="cc-branding-grid">
                                <div class="cc-branding-item">
                                    <label><strong><?php _e('Square Logo (600x600)', 'castconductor'); ?></strong></label>
                                    <div class="cc-media-control" data-option="castconductor_current_square_logo_600x600">
                                        <div class="cc-media-preview" style="margin:8px 0;">
                                            <img src="<?php echo esc_url($square_url); ?>" style="max-width:120px; max-height:120px; display: <?php echo $square_url ? 'block' : 'none'; ?>;" alt="" />
                                        </div>
                                        <input type="hidden" name="castconductor_current_square_logo_600x600" value="<?php echo esc_attr($square_id); ?>" />
                                        <button type="button" class="button cc-select-media" data-title="<?php esc_attr_e('Select Square Logo', 'castconductor'); ?>" data-button="<?php esc_attr_e('Use this logo', 'castconductor'); ?>"><?php _e('Select Image', 'castconductor'); ?></button>
                                        <button type="button" class="button cc-clear-media" style="margin-left:6px; <?php echo $square_id ? '' : 'display:none;'; ?>"><?php _e('Clear', 'castconductor'); ?></button>
                                        <p class="description"><?php _e('Recommended: 600x600 PNG with transparent background.', 'castconductor'); ?></p>
                                    </div>
                                </div>

                                <div class="cc-branding-item">
                                    <label><strong><?php _e('Horizontal Logo (1280x250)', 'castconductor'); ?></strong></label>
                                    <div class="cc-media-control" data-option="castconductor_current_animated_center_logo_1280x250">
                                        <div class="cc-media-preview" style="margin:8px 0;">
                                            <img src="<?php echo esc_url($horiz_url); ?>" style="max-width:320px; max-height:120px; display: <?php echo $horiz_url ? 'block' : 'none'; ?>;" alt="" />
                                        </div>
                                        <input type="hidden" name="castconductor_current_animated_center_logo_1280x250" value="<?php echo esc_attr($horiz_id); ?>" />
                                        <button type="button" class="button cc-select-media" data-title="<?php esc_attr_e('Select Horizontal Logo', 'castconductor'); ?>" data-button="<?php esc_attr_e('Use this logo', 'castconductor'); ?>"><?php _e('Select Image', 'castconductor'); ?></button>
                                        <button type="button" class="button cc-clear-media" style="margin-left:6px; <?php echo $horiz_id ? '' : 'display:none;'; ?>"><?php _e('Clear', 'castconductor'); ?></button>
                                        <p class="description"><?php _e('Recommended: 1280x250 PNG with transparent background.', 'castconductor'); ?></p>
                                    </div>
                                </div>

                                <div class="cc-branding-item">
                                    <label><strong><?php _e('Background Image (1920x1080)', 'castconductor'); ?></strong></label>
                                    <div class="cc-media-control" data-option="castconductor_current_background_1920x1080">
                                        <div class="cc-media-preview" style="margin:8px 0;">
                                            <img src="<?php echo esc_url($bg_url); ?>" style="max-width:320px; max-height:180px; display: <?php echo $bg_url ? 'block' : 'none'; ?>;" alt="" />
                                        </div>
                                        <input type="hidden" name="castconductor_current_background_1920x1080" value="<?php echo esc_attr($bg_id); ?>" />
                                        <button type="button" class="button cc-select-media" data-title="<?php esc_attr_e('Select Background', 'castconductor'); ?>" data-button="<?php esc_attr_e('Use this image', 'castconductor'); ?>"><?php _e('Select Image', 'castconductor'); ?></button>
                                        <button type="button" class="button cc-clear-media" style="margin-left:6px; <?php echo $bg_id ? '' : 'display:none;'; ?>"><?php _e('Clear', 'castconductor'); ?></button>
                                        <p class="description"><?php _e('Recommended: 1920x1080 JPG/PNG. Large images may impact performance.', 'castconductor'); ?></p>
                                    </div>
                                </div>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php _e('Stream URL', 'castconductor'); ?></th>
                        <td>
                            <input type="url" name="castconductor_stream_url" value="<?php echo esc_attr(get_option('castconductor_stream_url')); ?>" class="regular-text" />
                            <p class="description"><?php _e('Your audio stream URL (e.g., https://stream.station.com:8000/stream)', 'castconductor'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php _e('Video URL', 'castconductor'); ?></th>
                        <td>
                            <input type="url" name="castconductor_video_url" value="<?php echo esc_attr(get_option('castconductor_video_url')); ?>" class="regular-text" />
                            <p class="description"><?php _e('Your video stream URL (e.g., https://stream.example.com/live.m3u8 or RTMP URL)', 'castconductor'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php _e('Streaming Mode', 'castconductor'); ?></th>
                        <td>
                            <?php $streaming_mode = get_option('castconductor_streaming_mode', 'auto'); ?>
                            <select name="castconductor_streaming_mode">
                                <option value="auto" <?php selected($streaming_mode, 'auto'); ?>><?php _e('Auto-detect', 'castconductor'); ?></option>
                                <option value="audio" <?php selected($streaming_mode, 'audio'); ?>><?php _e('Audio Only', 'castconductor'); ?></option>
                                <option value="video" <?php selected($streaming_mode, 'video'); ?>><?php _e('Video', 'castconductor'); ?></option>
                            </select>
                            <p class="description"><?php _e('Choose how your content is streamed. Auto-detect will analyze the URL to determine the best mode.', 'castconductor'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php _e('Playback Mode', 'castconductor'); ?></th>
                        <td>
                            <?php $playback_mode = get_option('castconductor_playback_mode', 'standard'); ?>
                            <select name="castconductor_playback_mode">
                                <option value="standard" <?php selected($playback_mode, 'standard'); ?>><?php _e('Standard (One Source)', 'castconductor'); ?></option>
                                <option value="dual_source" <?php selected($playback_mode, 'dual_source'); ?>><?php _e('Dual Source (Video Muted + Audio)', 'castconductor'); ?></option>
                                <option value="video_only" <?php selected($playback_mode, 'video_only'); ?>><?php _e('Video Only', 'castconductor'); ?></option>
                                <option value="audio_only" <?php selected($playback_mode, 'audio_only'); ?>><?php _e('Audio Only', 'castconductor'); ?></option>
                            </select>
                            <p class="description"><?php _e('Standard: Play video OR audio. Dual Source: Play video (muted) with separate audio stream on top. Ideal for visualizers with live radio.', 'castconductor'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php _e('Metadata URL', 'castconductor'); ?></th>
                        <td>
                            <input type="url" name="castconductor_metadata_url" value="<?php echo esc_attr(get_option('castconductor_metadata_url')); ?>" class="regular-text" />
                            <p class="description"><?php _e('Your metadata API URL (e.g., https://stream.station.com:8000/api/nowplaying)', 'castconductor'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php _e('OpenWeather API Key', 'castconductor'); ?></th>
                        <td>
                            <input type="text" name="castconductor_openweather_api_key" value="<?php echo esc_attr(get_option('castconductor_openweather_api_key')); ?>" class="regular-text" />
                            <p class="description"><?php _e('Optional: API key for weather data. Get one free at openweathermap.org', 'castconductor'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php _e('Album Artwork Search', 'castconductor'); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="castconductor_artwork_search_enabled" value="1" <?php checked(get_option('castconductor_artwork_search_enabled'), 1); ?> />
                                <?php _e('Enable enhanced album artwork discovery', 'castconductor'); ?>
                            </label>
                            <p class="description"><?php _e('Searches iTunes, MusicBrainz, and Deezer for high-quality album artwork', 'castconductor'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php _e('IP Geolocation', 'castconductor'); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="castconductor_geolocation_enabled" value="1" <?php checked(get_option('castconductor_geolocation_enabled'), 1); ?> />
                                <?php _e('Enable viewer location detection', 'castconductor'); ?>
                            </label>
                            <p class="description"><?php _e('Provides local weather and time based on Roku viewer\'s IP address', 'castconductor'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php _e('Scene Rotation Interval', 'castconductor'); ?></th>
                        <td>
                            <select name="castconductor_scene_rotation_interval">
                                <?php
                                $current_interval = (int) get_option('castconductor_scene_rotation_interval', 60);
                                $intervals = array(
                                    30 => __('30 seconds', 'castconductor'),
                                    60 => __('1 minute', 'castconductor'),
                                    120 => __('2 minutes', 'castconductor'),
                                    300 => __('5 minutes', 'castconductor'),
                                    600 => __('10 minutes', 'castconductor'),
                                    900 => __('15 minutes', 'castconductor'),
                                    1800 => __('30 minutes', 'castconductor'),
                                    3600 => __('1 hour', 'castconductor'),
                                );
                                foreach ($intervals as $value => $label) {
                                    printf(
                                        '<option value="%d" %s>%s</option>',
                                        $value,
                                        selected($current_interval, $value, false),
                                        esc_html($label)
                                    );
                                }
                                ?>
                            </select>
                            <p class="description"><?php _e('How often the Roku app checks for scene rotation. Lower values provide faster scene switching but use more bandwidth.', 'castconductor'); ?></p>
                        </td>
                    </tr>
                </table>
                
                <?php submit_button(); ?>
            </form>
            
            <!-- Feed Cache Management Section -->
            <div class="card" style="max-width: 800px; margin-top: 20px; margin-bottom: 20px; padding: 20px;">
                <h2 style="margin-top: 0;">🗑️ <?php _e('Feed Cache Management', 'castconductor'); ?></h2>
                <p class="description" style="margin-bottom: 15px;">
                    <?php _e('Podcast and RSS feed data is cached for 1 hour to improve performance. Use this button to force a refresh of all cached feeds.', 'castconductor'); ?>
                </p>
                <button type="button" id="cc-clear-feed-cache" class="button button-secondary">
                    <span class="dashicons dashicons-update" style="margin-right: 5px; vertical-align: text-bottom;"></span>
                    <?php _e('Clear Feed Cache', 'castconductor'); ?>
                </button>
                <span id="cc-feed-cache-status" style="margin-left: 15px; display: none;"></span>
                <script>
                    document.getElementById('cc-clear-feed-cache').addEventListener('click', function() {
                        var btn = this;
                        var status = document.getElementById('cc-feed-cache-status');
                        
                        btn.disabled = true;
                        btn.innerHTML = '<span class="dashicons dashicons-update" style="margin-right: 5px; vertical-align: text-bottom; animation: spin 1s linear infinite;"></span><?php esc_attr_e('Clearing...', 'castconductor'); ?>';
                        status.style.display = 'inline';
                        status.innerHTML = '';
                        
                        fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                            body: 'action=castconductor_clear_feed_cache&nonce=<?php echo wp_create_nonce('castconductor_clear_feed_cache'); ?>'
                        })
                        .then(function(response) { return response.json(); })
                        .then(function(data) {
                            btn.disabled = false;
                            btn.innerHTML = '<span class="dashicons dashicons-update" style="margin-right: 5px; vertical-align: text-bottom;"></span><?php esc_attr_e('Clear Feed Cache', 'castconductor'); ?>';
                            
                            if (data.success) {
                                status.innerHTML = '<span style="color: #00a32a;">✓ ' + data.data.message + '</span>';
                            } else {
                                status.innerHTML = '<span style="color: #d63638;">✗ ' + (data.data || 'Error') + '</span>';
                            }
                            
                            setTimeout(function() { status.style.display = 'none'; }, 5000);
                        })
                        .catch(function(err) {
                            btn.disabled = false;
                            btn.innerHTML = '<span class="dashicons dashicons-update" style="margin-right: 5px; vertical-align: text-bottom;"></span><?php esc_attr_e('Clear Feed Cache', 'castconductor'); ?>';
                            status.innerHTML = '<span style="color: #d63638;">✗ Network error</span>';
                        });
                    });
                </script>
                <style>
                    @keyframes spin { 100% { transform: rotate(360deg); } }
                </style>
            </div>
            
            <!-- Roku App Configuration Section -->
            <div class="card" style="max-width: 800px; margin-top: 20px; margin-bottom: 20px; padding: 20px;">
                <h2 style="margin-top: 0;">🚀 <?php _e('Roku App Configuration', 'castconductor'); ?></h2>
                <p class="description" style="margin-bottom: 20px;">
                    <?php _e('Configure your Roku channel settings and artwork. Once complete, use the Launch Toaster button to build your app with these settings pre-filled.', 'castconductor'); ?>
                </p>
                
                <?php $this->render_roku_app_settings(); ?>
            </div>
            
            <?php if (!get_option('castconductor_setup_completed')): ?>
                <div class="setup-section">
                    <h2><?php _e('Setup Wizard', 'castconductor'); ?></h2>
                    <p><?php _e('Run the setup wizard to create test content and configure your station.', 'castconductor'); ?></p>
                    <a href="<?php echo admin_url('admin.php?page=castconductor-setup'); ?>" class="button button-primary">
                        <?php _e('Run Setup Wizard', 'castconductor'); ?>
                    </a>
                </div>
            <?php endif; ?>
        </div>
        <?php
    }
    
    /**
     * Setup wizard page
     */
    public function setup_wizard_page() {
        $setup_completed = get_option('castconductor_setup_completed');
        $from_dashboard = isset($_GET['from_dashboard']);
        ?>
        <div class="wrap">
            <h1><?php _e('🚀 CastConductor Setup Wizard', 'castconductor'); ?></h1>
            
            <div class="setup-wizard">
                <div class="wizard-header">
                    <h2><?php _e('Welcome to CastConductor!', 'castconductor'); ?></h2>
                    <p><?php _e('This wizard will help you configure your station with real content.', 'castconductor'); ?></p>
                    
                    <?php if (!$setup_completed): ?>
                        <div class="notice notice-success inline" style="margin: 20px 0;">
                            <p><strong><?php _e('Ready to begin!', 'castconductor'); ?></strong> <?php _e('Click the button below to start creating your test content and configuring your station.', 'castconductor'); ?></p>
                            
                            <div class="wizard-actions" style="margin-top: 15px;">
                                <button id="start-setup-wizard" class="button button-primary button-hero">
                                    <?php _e('🚀 Start Setup Wizard', 'castconductor'); ?>
                                </button>
                                <button id="skip-setup-wizard" class="button button-secondary">
                                    <?php _e('Skip Setup (Manual Configuration)', 'castconductor'); ?>
                                </button>
                            </div>
                        </div>
                        
                        <!-- Progress indicator positioned above the steps -->
                        <div class="wizard-progress" style="display: none; margin: 20px 0; padding: 20px; background: #f0f0f1; border-radius: 5px;">
                            <div class="progress-bar" style="background: #ddd; height: 20px; border-radius: 10px; overflow: hidden; margin-bottom: 10px;">
                                <div class="progress-fill" style="background: #00a32a; height: 100%; width: 0%; transition: width 0.3s ease;"></div>
                            </div>
                            <div class="progress-text" style="text-align: center; font-weight: bold;">Setting up your station...</div>
                        </div>
                    <?php endif; ?>
                </div>
                
                <div class="wizard-content">
                    <div class="setup-step" id="setup-step-1">
                        <h3><?php _e('Step 1: Database Setup', 'castconductor'); ?></h3>
                        <p><?php _e('Create database tables and default containers.', 'castconductor'); ?></p>
                        <div class="step-status">⏳ <?php _e('Ready to start', 'castconductor'); ?></div>
                    </div>
                    
                    <div class="setup-step" id="setup-step-2">
                        <h3><?php _e('Step 2: Real Test Content', 'castconductor'); ?></h3>
                        <p><?php _e('Create realistic shoutouts, sponsors, and promos with actual content.', 'castconductor'); ?></p>
                        <div class="step-status">⏳ <?php _e('Waiting...', 'castconductor'); ?></div>
                    </div>
                    
                    <div class="setup-step" id="setup-step-3">
                        <h3><?php _e('Step 3: Default Branding', 'castconductor'); ?></h3>
                        <p><?php _e('Setup default logos and branding elements.', 'castconductor'); ?></p>
                        <div class="step-status">⏳ <?php _e('Waiting...', 'castconductor'); ?></div>
                    </div>
                    
                    <div class="setup-step" id="setup-step-4">
                        <h3><?php _e('Step 4: API Configuration', 'castconductor'); ?></h3>
                        <p><?php _e('Configure real API endpoints (no hardcoded URLs).', 'castconductor'); ?></p>
                        <div class="step-status">⏳ <?php _e('Waiting...', 'castconductor'); ?></div>
                    </div>
                    
                    <div class="setup-step" id="setup-step-5">
                        <h3><?php _e('Step 5: Container Assignments', 'castconductor'); ?></h3>
                        <p><?php _e('Assign content blocks to default containers.', 'castconductor'); ?></p>
                        <div class="step-status">⏳ <?php _e('Waiting...', 'castconductor'); ?></div>
                    </div>
                </div>
            </div>
        </div>
        
        <script>
        jQuery(document).ready(function($) {
            $('#start-setup-wizard').on('click', function() {
                runSetupWizard();
            });
            
            $('#skip-setup-wizard').on('click', function() {
                if (confirm('<?php _e('Skip setup? You can run it later from Settings.', 'castconductor'); ?>')) {
                    window.location.href = '<?php echo admin_url('admin.php?page=castconductor'); ?>';
                }
            });
            
            function runSetupWizard() {
                $('.wizard-actions').hide();
                $('.wizard-progress').show();
                
                $.post(ajaxurl, {
                    action: 'castconductor_run_setup_wizard',
                    nonce: '<?php echo wp_create_nonce('castconductor_setup'); ?>'
                }, function(response) {
                    if (response.success) {
                        $('.progress-text').text('✅ Setup completed successfully!');
                        setTimeout(function() {
                            window.location.href = response.data.redirect;
                        }, 2000);
                    } else {
                        $('.progress-text').text('❌ Setup failed: ' + response.data.message);
                        $('.wizard-actions').show();
                    }
                }).fail(function() {
                    $('.progress-text').text('❌ Setup failed due to network error');
                    $('.wizard-actions').show();
                });
            }
        });
        </script>
        <?php
    }
    
    /**
     * Add meta boxes for custom post types
     */
    public function add_meta_boxes() {
        // Shoutout meta box
        add_meta_box(
            'castconductor_shoutout_details',
            __('Shoutout Details', 'castconductor'),
            array($this, 'shoutout_meta_box'),
            'cc_shoutout',
            'normal',
            'high'
        );
        
        // Sponsor meta box  
        add_meta_box(
            'castconductor_sponsor_schedule',
            __('Sponsor Scheduling', 'castconductor'),
            array($this, 'sponsor_meta_box'),
            'cc_sponsor',
            'normal',
            'high'
        );
        
        // Promo meta box
        add_meta_box(
            'castconductor_promo_schedule',
            __('Promo Scheduling', 'castconductor'),
            array($this, 'promo_meta_box'),
            'cc_promo',
            'normal',
            'high'
        );
        
        // Post type reassignment meta box (for all CPTs)
        $cpt_types = array('cc_shoutout', 'cc_sponsor', 'cc_promo', 'cc_layer');
        foreach ($cpt_types as $cpt) {
            add_meta_box(
                'castconductor_reassign_type',
                __('Content Type', 'castconductor'),
                array($this, 'reassign_type_meta_box'),
                $cpt,
                'side',
                'default'
            );
        }
    }
    
    /**
     * Shoutout meta box content
     */
    public function shoutout_meta_box($post) {
        wp_nonce_field('castconductor_meta_box', 'castconductor_meta_nonce');
        
        $name = get_post_meta($post->ID, 'cc_shoutout_name', true);
        $location = get_post_meta($post->ID, 'cc_shoutout_location', true);
        $approved = get_post_meta($post->ID, 'cc_shoutout_approved', true);
        $source = get_post_meta($post->ID, 'cc_shoutout_source', true);
        $featured_image_url = get_the_post_thumbnail_url($post->ID, 'full');
        
        ?>
        <table class="form-table">
            <tr>
                <th><label for="cc_shoutout_name"><?php _e('Name', 'castconductor'); ?></label></th>
                <td><input type="text" id="cc_shoutout_name" name="cc_shoutout_name" value="<?php echo esc_attr($name); ?>" class="regular-text" /></td>
            </tr>
            <tr>
                <th><label for="cc_shoutout_location"><?php _e('Location', 'castconductor'); ?></label></th>
                <td><input type="text" id="cc_shoutout_location" name="cc_shoutout_location" value="<?php echo esc_attr($location); ?>" class="regular-text" /></td>
            </tr>
            <tr>
                <th><label for="cc_shoutout_approved"><?php _e('Approved', 'castconductor'); ?></label></th>
                <td><input type="checkbox" id="cc_shoutout_approved" name="cc_shoutout_approved" value="1" <?php checked($approved, 1); ?> /></td>
            </tr>
            <tr>
                <th><label for="cc_shoutout_source"><?php _e('Source', 'castconductor'); ?></label></th>
                <td><input type="text" id="cc_shoutout_source" name="cc_shoutout_source" value="<?php echo esc_attr($source); ?>" class="regular-text" readonly /></td>
            </tr>
            <tr>
                <th><label><?php _e('Shoutout Artwork', 'castconductor'); ?></label></th>
                <td>
                    <?php if ($featured_image_url): ?>
                        <img src="<?php echo esc_url($featured_image_url); ?>" style="max-width:200px;height:auto;display:block;margin-bottom:10px;" />
                    <?php endif; ?>
                    <p class="description"><?php _e('Set artwork using the "Featured Image" box in the sidebar. This artwork will display in the lower third alongside the shoutout text.', 'castconductor'); ?></p>
                </td>
            </tr>
        </table>
        
        <div class="notice notice-info inline">
            <p><strong><?php _e('Display Format:', 'castconductor'); ?></strong> <?php echo esc_html($name); ?> from <?php echo esc_html($location); ?> says: "<?php echo esc_html($post->post_content); ?>"</p>
        </div>
        <?php
    }
    
    /**
     * Sponsor meta box content
     */
    public function sponsor_meta_box($post) {
        wp_nonce_field('castconductor_meta_box', 'castconductor_meta_nonce');
        
        $start_date = get_post_meta($post->ID, 'cc_sponsor_start_date', true);
        $end_date = get_post_meta($post->ID, 'cc_sponsor_end_date', true);
        $timezone = get_post_meta($post->ID, 'cc_sponsor_timezone', true);
        $source = get_post_meta($post->ID, 'cc_sponsor_source', true);
        $image_credit = get_post_meta($post->ID, 'castconductor_image_credit', true);
        
        // Convert to local time for display
        $start_date_local = $start_date ? get_date_from_gmt($start_date, 'Y-m-d\TH:i') : '';
        $end_date_local = $end_date ? get_date_from_gmt($end_date, 'Y-m-d\TH:i') : '';
        
        ?>
        <table class="form-table">
            <tr>
                <th><label for="cc_sponsor_start_date"><?php _e('Start Date & Time', 'castconductor'); ?></label></th>
                <td>
                    <input type="datetime-local" id="cc_sponsor_start_date" name="cc_sponsor_start_date" value="<?php echo esc_attr($start_date_local); ?>" />
                    <p class="description"><?php _e('When this sponsor campaign should begin displaying.', 'castconductor'); ?></p>
                </td>
            </tr>
            <tr>
                <th><label for="cc_sponsor_end_date"><?php _e('End Date & Time', 'castconductor'); ?></label></th>
                <td>
                    <input type="datetime-local" id="cc_sponsor_end_date" name="cc_sponsor_end_date" value="<?php echo esc_attr($end_date_local); ?>" />
                    <p class="description"><?php _e('When this sponsor campaign should stop displaying.', 'castconductor'); ?></p>
                </td>
            </tr>
            <tr>
                <th><label for="cc_sponsor_timezone"><?php _e('Timezone', 'castconductor'); ?></label></th>
                <td>
                    <select id="cc_sponsor_timezone" name="cc_sponsor_timezone">
                        <?php
                        $timezones = timezone_identifiers_list();
                        foreach ($timezones as $tz) {
                            echo '<option value="' . esc_attr($tz) . '"' . selected($timezone, $tz, false) . '>' . esc_html($tz) . '</option>';
                        }
                        ?>
                    </select>
                </td>
            </tr>
            <tr>
                <th><label for="castconductor_image_credit"><?php _e('Image Credit', 'castconductor'); ?></label></th>
                <td>
                    <input type="text" id="castconductor_image_credit" name="castconductor_image_credit" value="<?php echo esc_attr($image_credit); ?>" class="regular-text" />
                    <p class="description"><?php _e('Attribution for the featured image (for admin reference only - not sent to Roku by default).', 'castconductor'); ?></p>
                </td>
            </tr>
            <tr>
                <th><label for="cc_sponsor_source"><?php _e('Source', 'castconductor'); ?></label></th>
                <td><input type="text" id="cc_sponsor_source" name="cc_sponsor_source" value="<?php echo esc_attr($source); ?>" class="regular-text" readonly /></td>
            </tr>
        </table>
        <?php
    }
    
    /**
     * Promo meta box content  
     */
    public function promo_meta_box($post) {
        wp_nonce_field('castconductor_meta_box', 'castconductor_meta_nonce');
        
        $start_date = get_post_meta($post->ID, 'cc_promo_start_date', true);
        $end_date = get_post_meta($post->ID, 'cc_promo_end_date', true);
        $schedule = get_post_meta($post->ID, 'cc_promo_schedule', true);
        $timezone = get_post_meta($post->ID, 'cc_promo_timezone', true);
        $source = get_post_meta($post->ID, 'cc_promo_source', true);
        $image_credit = get_post_meta($post->ID, 'castconductor_image_credit', true);
        
        // Convert to local time for display
        $start_date_local = $start_date ? get_date_from_gmt($start_date, 'Y-m-d\TH:i') : '';
        $end_date_local = $end_date ? get_date_from_gmt($end_date, 'Y-m-d\TH:i') : '';
        
        ?>
        <table class="form-table">
            <tr>
                <th><label for="cc_promo_start_date"><?php _e('Start Date & Time', 'castconductor'); ?></label></th>
                <td>
                    <input type="datetime-local" id="cc_promo_start_date" name="cc_promo_start_date" value="<?php echo esc_attr($start_date_local); ?>" />
                    <p class="description"><?php _e('When this promo should begin displaying.', 'castconductor'); ?></p>
                </td>
            </tr>
            <tr>
                <th><label for="cc_promo_end_date"><?php _e('End Date & Time', 'castconductor'); ?></label></th>
                <td>
                    <input type="datetime-local" id="cc_promo_end_date" name="cc_promo_end_date" value="<?php echo esc_attr($end_date_local); ?>" />
                    <p class="description"><?php _e('When this promo should stop displaying.', 'castconductor'); ?></p>
                </td>
            </tr>
            <tr>
                <th><label for="cc_promo_schedule"><?php _e('Schedule Type', 'castconductor'); ?></label></th>
                <td>
                    <select id="cc_promo_schedule" name="cc_promo_schedule">
                        <option value="continuous" <?php selected($schedule, 'continuous'); ?>><?php _e('Continuous', 'castconductor'); ?></option>
                        <option value="recurring_daily" <?php selected($schedule, 'recurring_daily'); ?>><?php _e('Recurring Daily', 'castconductor'); ?></option>
                        <option value="recurring_weekly" <?php selected($schedule, 'recurring_weekly'); ?>><?php _e('Recurring Weekly', 'castconductor'); ?></option>
                        <option value="recurring_monthly" <?php selected($schedule, 'recurring_monthly'); ?>><?php _e('Recurring Monthly', 'castconductor'); ?></option>
                    </select>
                </td>
            </tr>
            <tr>
                <th><label for="cc_promo_timezone"><?php _e('Timezone', 'castconductor'); ?></label></th>
                <td>
                    <select id="cc_promo_timezone" name="cc_promo_timezone">
                        <?php
                        $timezones = timezone_identifiers_list();
                        foreach ($timezones as $tz) {
                            echo '<option value="' . esc_attr($tz) . '"' . selected($timezone, $tz, false) . '>' . esc_html($tz) . '</option>';
                        }
                        ?>
                    </select>
                </td>
            </tr>
            <tr>
                <th><label for="castconductor_image_credit"><?php _e('Image Credit', 'castconductor'); ?></label></th>
                <td>
                    <input type="text" id="castconductor_image_credit" name="castconductor_image_credit" value="<?php echo esc_attr($image_credit); ?>" class="regular-text" />
                    <p class="description"><?php _e('Attribution for the featured image (for admin reference only - not sent to Roku by default).', 'castconductor'); ?></p>
                </td>
            </tr>
            <tr>
                <th><label for="cc_promo_source"><?php _e('Source', 'castconductor'); ?></label></th>
                <td><input type="text" id="cc_promo_source" name="cc_promo_source" value="<?php echo esc_attr($source); ?>" class="regular-text" readonly /></td>
            </tr>
        </table>
        <?php
    }
    
    /**
     * Post type reassignment meta box content
     */
    public function reassign_type_meta_box($post) {
        $current_type = get_post_type($post);
        $cpt_labels = $this->get_cpt_labels();
        
        // Get all CastConductor post types
        $cpt_types = array(
            'cc_shoutout' => $cpt_labels['cc_shoutout']['singular'] ?? __('Shoutout', 'castconductor'),
            'cc_sponsor'  => $cpt_labels['cc_sponsor']['singular'] ?? __('Sponsor', 'castconductor'),
            'cc_promo'    => $cpt_labels['cc_promo']['singular'] ?? __('Promo', 'castconductor'),
            'cc_layer'    => $cpt_labels['cc_layer']['singular'] ?? __('Layer', 'castconductor'),
        );
        
        ?>
        <p>
            <label for="cc_reassign_post_type"><strong><?php _e('Current Type:', 'castconductor'); ?></strong></label>
        </p>
        <select id="cc_reassign_post_type" name="cc_reassign_post_type" style="width: 100%;">
            <?php foreach ($cpt_types as $type => $label): ?>
                <option value="<?php echo esc_attr($type); ?>" <?php selected($current_type, $type); ?>>
                    <?php echo esc_html($label); ?>
                </option>
            <?php endforeach; ?>
        </select>
        <p class="description" style="margin-top: 8px;">
            <?php _e('Change the content type of this item. Metadata will be preserved but may need adjustment after reassignment.', 'castconductor'); ?>
        </p>
        <?php if ($current_type !== 'cc_layer'): ?>
        <p class="description" style="color: #b32d2e;">
            <strong><?php _e('Note:', 'castconductor'); ?></strong> <?php _e('Reassigning may affect scheduling and display settings.', 'castconductor'); ?>
        </p>
        <?php endif; ?>
        <?php
    }
    
    /**
     * Get custom CPT labels (from options or defaults)
     */
    public function get_cpt_labels() {
        $defaults = array(
            'cc_shoutout' => array('name' => __('Shoutouts', 'castconductor'), 'singular' => __('Shoutout', 'castconductor')),
            'cc_sponsor'  => array('name' => __('Sponsors', 'castconductor'), 'singular' => __('Sponsor', 'castconductor')),
            'cc_promo'    => array('name' => __('Promos', 'castconductor'), 'singular' => __('Promo', 'castconductor')),
            'cc_layer'    => array('name' => __('Layers', 'castconductor'), 'singular' => __('Layer', 'castconductor')),
        );
        
        $custom = get_option('castconductor_cpt_labels', array());
        
        return array_merge($defaults, $custom);
    }
    
    /**
     * Save meta box data
     */
    public function save_meta_boxes($post_id) {
        // Check nonce
        if (!isset($_POST['castconductor_meta_nonce']) || !wp_verify_nonce($_POST['castconductor_meta_nonce'], 'castconductor_meta_box')) {
            return;
        }
        
        // Check permissions
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        // Save shoutout fields
        if (get_post_type($post_id) === 'cc_shoutout') {
            update_post_meta($post_id, 'cc_shoutout_name', sanitize_text_field($_POST['cc_shoutout_name'] ?? ''));
            update_post_meta($post_id, 'cc_shoutout_location', sanitize_text_field($_POST['cc_shoutout_location'] ?? ''));
            update_post_meta($post_id, 'cc_shoutout_approved', isset($_POST['cc_shoutout_approved']) ? 1 : 0);
            update_post_meta($post_id, 'cc_shoutout_source', sanitize_text_field($_POST['cc_shoutout_source'] ?? ''));
        }
        
        // Save sponsor fields
        if (get_post_type($post_id) === 'cc_sponsor') {
            // Convert local time to GMT for storage
            $start_date = sanitize_text_field($_POST['cc_sponsor_start_date'] ?? '');
            $end_date = sanitize_text_field($_POST['cc_sponsor_end_date'] ?? '');
            
            if ($start_date) {
                $start_date_gmt = get_gmt_from_date($start_date . ':00');
                update_post_meta($post_id, 'cc_sponsor_start_date', $start_date_gmt);
            }
            
            if ($end_date) {
                $end_date_gmt = get_gmt_from_date($end_date . ':00');
                update_post_meta($post_id, 'cc_sponsor_end_date', $end_date_gmt);
            }
            
            update_post_meta($post_id, 'cc_sponsor_timezone', sanitize_text_field($_POST['cc_sponsor_timezone'] ?? ''));
            update_post_meta($post_id, 'castconductor_image_credit', sanitize_text_field($_POST['castconductor_image_credit'] ?? ''));
            update_post_meta($post_id, 'cc_sponsor_source', sanitize_text_field($_POST['cc_sponsor_source'] ?? ''));
        }
        
        // Save promo fields
        if (get_post_type($post_id) === 'cc_promo') {
            // Convert local time to GMT for storage
            $start_date = sanitize_text_field($_POST['cc_promo_start_date'] ?? '');
            $end_date = sanitize_text_field($_POST['cc_promo_end_date'] ?? '');
            
            if ($start_date) {
                $start_date_gmt = get_gmt_from_date($start_date . ':00');
                update_post_meta($post_id, 'cc_promo_start_date', $start_date_gmt);
            }
            
            if ($end_date) {
                $end_date_gmt = get_gmt_from_date($end_date . ':00');
                update_post_meta($post_id, 'cc_promo_end_date', $end_date_gmt);
            }
            
            update_post_meta($post_id, 'cc_promo_schedule', sanitize_text_field($_POST['cc_promo_schedule'] ?? ''));
            update_post_meta($post_id, 'cc_promo_timezone', sanitize_text_field($_POST['cc_promo_timezone'] ?? ''));
            update_post_meta($post_id, 'castconductor_image_credit', sanitize_text_field($_POST['castconductor_image_credit'] ?? ''));
            update_post_meta($post_id, 'cc_promo_source', sanitize_text_field($_POST['cc_promo_source'] ?? ''));
        }
        
        // Handle post type reassignment (must be done last, after other saves)
        if (isset($_POST['cc_reassign_post_type'])) {
            $new_type = sanitize_key($_POST['cc_reassign_post_type']);
            $current_type = get_post_type($post_id);
            $valid_types = array('cc_shoutout', 'cc_sponsor', 'cc_promo', 'cc_layer');
            
            if ($new_type !== $current_type && in_array($new_type, $valid_types, true)) {
                // Use wpdb to directly update post_type to avoid triggering save_post again
                global $wpdb;
                $wpdb->update(
                    $wpdb->posts,
                    array('post_type' => $new_type),
                    array('ID' => $post_id),
                    array('%s'),
                    array('%d')
                );
                
                // Clear post cache
                clean_post_cache($post_id);
                
                // Log the reassignment
                update_post_meta($post_id, 'cc_reassigned_from', $current_type);
                update_post_meta($post_id, 'cc_reassigned_at', current_time('mysql'));
            }
        }
    }
    
    /**
     * Data management page
     */
    public function data_management_page() {
        // Handle form submissions
        if (isset($_POST['submit'])) {
            check_admin_referer('castconductor_data_management');
            
            if (isset($_POST['preserve_data_on_uninstall'])) {
                update_option('castconductor_preserve_data_on_uninstall', true);
                // Reset data removal confirmation when protection is re-enabled
                delete_option('castconductor_data_removal_confirmed');
            } else {
                update_option('castconductor_preserve_data_on_uninstall', false);
            }
            
            echo '<div class="notice notice-success"><p>' . __('Data management settings saved.', 'castconductor') . '</p></div>';
        }
        
        // Handle data removal confirmation
        if (isset($_POST['confirm_data_removal'])) {
            check_admin_referer('castconductor_confirm_removal');
            
            if ($_POST['confirm_text'] === 'DELETE ALL DATA') {
                update_option('castconductor_data_removal_confirmed', true);
                echo '<div class="notice notice-warning"><p><strong>' . __('Data removal confirmed. Your data will be deleted when the plugin is uninstalled.', 'castconductor') . '</strong></p></div>';
            } else {
                echo '<div class="notice notice-error"><p>' . __('Confirmation text does not match. Please type "DELETE ALL DATA" exactly.', 'castconductor') . '</p></div>';
            }
        }
        
        $preserve_data = get_option('castconductor_preserve_data_on_uninstall', true);
        $data_removal_confirmed = get_option('castconductor_data_removal_confirmed', false);
        
        ?>
        <div class="wrap">
            <h1><?php _e('🛡️ Data Management & Protection', 'castconductor'); ?></h1>
            
            <div class="notice notice-info">
                <h3><?php _e('🔒 Data Protection Philosophy', 'castconductor'); ?></h3>
                <p><?php _e('CastConductor V5 is designed to protect your content by default. When you uninstall the plugin, your data is preserved unless you explicitly choose to remove it.', 'castconductor'); ?></p>
            </div>
            
            <div class="postbox">
                <div class="postbox-header">
                    <h2><?php _e('Uninstall Data Protection', 'castconductor'); ?></h2>
                </div>
                <div class="inside">
                    <form method="post" action="">
                        <?php wp_nonce_field('castconductor_data_management'); ?>
                        
                        <table class="form-table">
                            <tr>
                                <th scope="row"><?php _e('Preserve Data on Uninstall', 'castconductor'); ?></th>
                                <td>
                                    <label>
                                        <input type="checkbox" name="preserve_data_on_uninstall" value="1" <?php checked($preserve_data); ?> />
                                        <?php _e('Keep all my content when uninstalling the plugin (RECOMMENDED)', 'castconductor'); ?>
                                    </label>
                                    <p class="description">
                                        <?php _e('When enabled (default), uninstalling the plugin will preserve all your containers, content blocks, shoutouts, sponsors, and promos. Only plugin settings will be removed.', 'castconductor'); ?>
                                    </p>
                                </td>
                            </tr>
                        </table>
                        
                        <?php submit_button(__('Save Data Protection Settings', 'castconductor')); ?>
                    </form>
                </div>
            </div>
            
            <?php if (!$preserve_data && !$data_removal_confirmed): ?>
            <div class="postbox" style="border-left: 4px solid #d63638;">
                <div class="postbox-header">
                    <h2><?php _e('⚠️ Confirm Complete Data Removal', 'castconductor'); ?></h2>
                </div>
                <div class="inside">
                    <div class="notice notice-warning inline">
                        <p><strong><?php _e('WARNING:', 'castconductor'); ?></strong> <?php _e('You have disabled data protection. To completely remove all your CastConductor data when uninstalling, you must explicitly confirm this action.', 'castconductor'); ?></p>
                    </div>
                    
                    <h3><?php _e('What will be permanently deleted:', 'castconductor'); ?></h3>
                    <ul>
                        <li><?php _e('All database tables (containers, content blocks, assignments)', 'castconductor'); ?></li>
                        <li><?php _e('All shoutouts, sponsors, and promos content', 'castconductor'); ?></li>
                        <li><?php _e('All plugin settings and configuration', 'castconductor'); ?></li>
                        <li><?php _e('All uploaded images and media associated with the plugin', 'castconductor'); ?></li>
                    </ul>
                    
                    <form method="post" action="" onsubmit="return confirm('Are you absolutely sure you want to allow complete data removal? This cannot be undone!');">
                        <?php wp_nonce_field('castconductor_confirm_removal'); ?>
                        
                        <table class="form-table">
                            <tr>
                                <th scope="row"><?php _e('Type "DELETE ALL DATA" to confirm', 'castconductor'); ?></th>
                                <td>
                                    <input type="text" name="confirm_text" class="regular-text" required />
                                    <p class="description"><?php _e('This confirmation is required to enable data removal on uninstall.', 'castconductor'); ?></p>
                                </td>
                            </tr>
                        </table>
                        
                        <input type="submit" name="confirm_data_removal" class="button button-primary" value="<?php esc_attr_e('Confirm Data Removal', 'castconductor'); ?>" />
                    </form>
                </div>
            </div>
            <?php elseif ($data_removal_confirmed): ?>
            <div class="postbox" style="border-left: 4px solid #d63638;">
                <div class="postbox-header">
                    <h2><?php _e('❌ Data Removal Confirmed', 'castconductor'); ?></h2>
                </div>
                <div class="inside">
                    <p><strong><?php _e('Your data WILL be permanently deleted when you uninstall this plugin.', 'castconductor'); ?></strong></p>
                    <p><?php _e('To change this, enable "Preserve Data on Uninstall" above and save your settings.', 'castconductor'); ?></p>
                </div>
            </div>
            <?php endif; ?>
            
            <div class="postbox">
                <div class="postbox-header">
                    <h2><?php _e('📊 Current Data Summary', 'castconductor'); ?></h2>
                </div>
                <div class="inside">
                    <?php
                    global $wpdb;
                    
                    // Count data
                    $containers_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}castconductor_containers");
                    $content_blocks_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}castconductor_content_blocks");
                    $shoutouts_count = wp_count_posts('cc_shoutout')->publish ?? 0;
                    $sponsors_count = wp_count_posts('cc_sponsor')->publish ?? 0;
                    $promos_count = wp_count_posts('cc_promo')->publish ?? 0;
                    ?>
                    
                    <table class="wp-list-table widefat fixed striped">
                        <thead>
                            <tr>
                                <th><?php _e('Data Type', 'castconductor'); ?></th>
                                <th><?php _e('Count', 'castconductor'); ?></th>
                                <th><?php _e('Status', 'castconductor'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><?php _e('Containers', 'castconductor'); ?></td>
                                <td><?php echo esc_html($containers_count); ?></td>
                                <td><?php echo $preserve_data ? '🛡️ ' . __('Protected', 'castconductor') : '⚠️ ' . __('Will be removed', 'castconductor'); ?></td>
                            </tr>
                            <tr>
                                <td><?php _e('Content Blocks', 'castconductor'); ?></td>
                                <td><?php echo esc_html($content_blocks_count); ?></td>
                                <td><?php echo $preserve_data ? '🛡️ ' . __('Protected', 'castconductor') : '⚠️ ' . __('Will be removed', 'castconductor'); ?></td>
                            </tr>
                            <tr>
                                <td><?php _e('Shoutouts', 'castconductor'); ?></td>
                                <td><?php echo esc_html($shoutouts_count); ?></td>
                                <td><?php echo $preserve_data ? '🛡️ ' . __('Protected', 'castconductor') : '⚠️ ' . __('Will be removed', 'castconductor'); ?></td>
                            </tr>
                            <tr>
                                <td><?php _e('Sponsors', 'castconductor'); ?></td>
                                <td><?php echo esc_html($sponsors_count); ?></td>
                                <td><?php echo $preserve_data ? '🛡️ ' . __('Protected', 'castconductor') : '⚠️ ' . __('Will be removed', 'castconductor'); ?></td>
                            </tr>
                            <tr>
                                <td><?php _e('Promos', 'castconductor'); ?></td>
                                <td><?php echo esc_html($promos_count); ?></td>
                                <td><?php echo $preserve_data ? '🛡️ ' . __('Protected', 'castconductor') : '⚠️ ' . __('Will be removed', 'castconductor'); ?></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <div class="postbox">
                <div class="postbox-header">
                    <h2><?php _e('🔄 Future: Backup & Restore', 'castconductor'); ?></h2>
                </div>
                <div class="inside">
                    <p><?php _e('Coming in a future update:', 'castconductor'); ?></p>
                    <ul>
                        <li><?php _e('✅ Export all CastConductor data to JSON backup file', 'castconductor'); ?></li>
                        <li><?php _e('✅ Import data from backup file', 'castconductor'); ?></li>
                        <li><?php _e('✅ Scheduled automatic backups', 'castconductor'); ?></li>
                        <li><?php _e('✅ Migration tools for upgrading between versions', 'castconductor'); ?></li>
                    </ul>
                </div>
            </div>
        </div>
        <?php
    }
    
    /**
     * CPT Manager page - Customize content type labels
     */
    public function cpt_manager_page() {
        // Handle form submissions
        if (isset($_POST['save_cpt_labels'])) {
            check_admin_referer('castconductor_cpt_manager');
            
            $labels = array();
            $cpt_types = array('cc_shoutout', 'cc_sponsor', 'cc_promo', 'cc_layer');
            
            foreach ($cpt_types as $cpt) {
                $labels[$cpt] = array(
                    'name' => sanitize_text_field($_POST[$cpt . '_name'] ?? ''),
                    'singular' => sanitize_text_field($_POST[$cpt . '_singular'] ?? ''),
                );
            }
            
            update_option('castconductor_cpt_labels', $labels);
            echo '<div class="notice notice-success"><p>' . __('Content type labels saved. Changes will take effect on the next page load.', 'castconductor') . '</p></div>';
        }
        
        // Handle reset to defaults
        if (isset($_POST['reset_cpt_labels'])) {
            check_admin_referer('castconductor_cpt_manager');
            delete_option('castconductor_cpt_labels');
            echo '<div class="notice notice-success"><p>' . __('Content type labels reset to defaults.', 'castconductor') . '</p></div>';
        }
        
        $labels = $this->get_cpt_labels();
        
        ?>
        <div class="wrap">
            <h1><?php _e('📦 Content Type Manager', 'castconductor'); ?></h1>
            
            <div class="notice notice-info">
                <p><strong><?php _e('Customize Your Content Types', 'castconductor'); ?></strong></p>
                <p><?php _e('Rename the built-in content types to match your workflow. For example, change "Shoutouts" to "Announcements" or "Sponsors" to "Partners".', 'castconductor'); ?></p>
            </div>
            
            <form method="post" action="">
                <?php wp_nonce_field('castconductor_cpt_manager'); ?>
                
                <div class="postbox">
                    <div class="postbox-header">
                        <h2><?php _e('Content Type Labels', 'castconductor'); ?></h2>
                    </div>
                    <div class="inside">
                        <table class="form-table">
                            <thead>
                                <tr>
                                    <th style="width: 150px;"><?php _e('Content Type', 'castconductor'); ?></th>
                                    <th><?php _e('Plural Name', 'castconductor'); ?></th>
                                    <th><?php _e('Singular Name', 'castconductor'); ?></th>
                                    <th><?php _e('Post Count', 'castconductor'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td><strong><?php _e('Shoutouts', 'castconductor'); ?></strong><br><code>cc_shoutout</code></td>
                                    <td>
                                        <input type="text" name="cc_shoutout_name" value="<?php echo esc_attr($labels['cc_shoutout']['name']); ?>" class="regular-text" placeholder="<?php esc_attr_e('Shoutouts', 'castconductor'); ?>" />
                                    </td>
                                    <td>
                                        <input type="text" name="cc_shoutout_singular" value="<?php echo esc_attr($labels['cc_shoutout']['singular']); ?>" class="regular-text" placeholder="<?php esc_attr_e('Shoutout', 'castconductor'); ?>" />
                                    </td>
                                    <td><?php echo esc_html(wp_count_posts('cc_shoutout')->publish ?? 0); ?></td>
                                </tr>
                                <tr>
                                    <td><strong><?php _e('Sponsors', 'castconductor'); ?></strong><br><code>cc_sponsor</code></td>
                                    <td>
                                        <input type="text" name="cc_sponsor_name" value="<?php echo esc_attr($labels['cc_sponsor']['name']); ?>" class="regular-text" placeholder="<?php esc_attr_e('Sponsors', 'castconductor'); ?>" />
                                    </td>
                                    <td>
                                        <input type="text" name="cc_sponsor_singular" value="<?php echo esc_attr($labels['cc_sponsor']['singular']); ?>" class="regular-text" placeholder="<?php esc_attr_e('Sponsor', 'castconductor'); ?>" />
                                    </td>
                                    <td><?php echo esc_html(wp_count_posts('cc_sponsor')->publish ?? 0); ?></td>
                                </tr>
                                <tr>
                                    <td><strong><?php _e('Promos', 'castconductor'); ?></strong><br><code>cc_promo</code></td>
                                    <td>
                                        <input type="text" name="cc_promo_name" value="<?php echo esc_attr($labels['cc_promo']['name']); ?>" class="regular-text" placeholder="<?php esc_attr_e('Promos', 'castconductor'); ?>" />
                                    </td>
                                    <td>
                                        <input type="text" name="cc_promo_singular" value="<?php echo esc_attr($labels['cc_promo']['singular']); ?>" class="regular-text" placeholder="<?php esc_attr_e('Promo', 'castconductor'); ?>" />
                                    </td>
                                    <td><?php echo esc_html(wp_count_posts('cc_promo')->publish ?? 0); ?></td>
                                </tr>
                                <tr>
                                    <td><strong><?php _e('Layers', 'castconductor'); ?></strong><br><code>cc_layer</code></td>
                                    <td>
                                        <input type="text" name="cc_layer_name" value="<?php echo esc_attr($labels['cc_layer']['name']); ?>" class="regular-text" placeholder="<?php esc_attr_e('Layers', 'castconductor'); ?>" />
                                    </td>
                                    <td>
                                        <input type="text" name="cc_layer_singular" value="<?php echo esc_attr($labels['cc_layer']['singular']); ?>" class="regular-text" placeholder="<?php esc_attr_e('Layer', 'castconductor'); ?>" />
                                    </td>
                                    <td><?php echo esc_html(wp_count_posts('cc_layer')->publish ?? 0); ?></td>
                                </tr>
                            </tbody>
                        </table>
                        
                        <p class="description">
                            <?php _e('Leave fields empty to use the default labels. The internal post type slug (shown in <code>monospace</code>) cannot be changed.', 'castconductor'); ?>
                        </p>
                    </div>
                </div>
                
                <p class="submit">
                    <input type="submit" name="save_cpt_labels" class="button button-primary" value="<?php esc_attr_e('Save Labels', 'castconductor'); ?>" />
                    <input type="submit" name="reset_cpt_labels" class="button" value="<?php esc_attr_e('Reset to Defaults', 'castconductor'); ?>" onclick="return confirm('<?php esc_attr_e('Are you sure you want to reset all labels to defaults?', 'castconductor'); ?>');" />
                </p>
            </form>
            
            <div class="postbox">
                <div class="postbox-header">
                    <h2><?php _e('🔄 Content Reassignment', 'castconductor'); ?></h2>
                </div>
                <div class="inside">
                    <p><?php _e('Need to move content between types? Each post now has a "Content Type" dropdown in the sidebar when editing.', 'castconductor'); ?></p>
                    <p><?php _e('Simply edit any Shoutout, Sponsor, Promo, or Layer and change its type from the sidebar.', 'castconductor'); ?></p>
                    <p><strong><?php _e('Example uses:', 'castconductor'); ?></strong></p>
                    <ul>
                        <li><?php _e('Convert a one-time Promo into a recurring Sponsor', 'castconductor'); ?></li>
                        <li><?php _e('Turn a Shoutout into a Layer for more control', 'castconductor'); ?></li>
                        <li><?php _e('Reorganize content as your needs evolve', 'castconductor'); ?></li>
                    </ul>
                </div>
            </div>
            
            <div class="postbox">
                <div class="postbox-header">
                    <h2><?php _e('ℹ️ About Content Types', 'castconductor'); ?></h2>
                </div>
                <div class="inside">
                    <table class="wp-list-table widefat fixed striped">
                        <thead>
                            <tr>
                                <th><?php _e('Type', 'castconductor'); ?></th>
                                <th><?php _e('Purpose', 'castconductor'); ?></th>
                                <th><?php _e('Best For', 'castconductor'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><strong><?php _e('Shoutouts', 'castconductor'); ?></strong></td>
                                <td><?php _e('Quick messages from viewers/listeners', 'castconductor'); ?></td>
                                <td><?php _e('Live interaction, thank you messages, birthday wishes', 'castconductor'); ?></td>
                            </tr>
                            <tr>
                                <td><strong><?php _e('Sponsors', 'castconductor'); ?></strong></td>
                                <td><?php _e('Scheduled promotional content with date ranges', 'castconductor'); ?></td>
                                <td><?php _e('Paid sponsorships, campaign-based ads, time-limited promotions', 'castconductor'); ?></td>
                            </tr>
                            <tr>
                                <td><strong><?php _e('Promos', 'castconductor'); ?></strong></td>
                                <td><?php _e('Flexible promotional content with scheduling', 'castconductor'); ?></td>
                                <td><?php _e('Self-promotion, upcoming events, social media plugs', 'castconductor'); ?></td>
                            </tr>
                            <tr>
                                <td><strong><?php _e('Layers', 'castconductor'); ?></strong></td>
                                <td><?php _e('Custom overlay content for the canvas', 'castconductor'); ?></td>
                                <td><?php _e('Advanced layouts, custom graphics, special effects', 'castconductor'); ?></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php
    }
}
