<?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 Advertising Manager
 * 
 * Manages Roku advertising integration settings.
 * Feature availability is gated by license plan:
 * - Business/Enterprise: Included
 * - Creator/Pro: Available as $29/mo add-on
 * 
 * @since 5.5.0
 */

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

class CastConductor_Advertising {
    
    /**
     * Singleton instance
     */
    private static $instance = null;
    
    /**
     * Plans that include advertising features
     * Note: 'master' is for internal/dev testing keys
     */
    const INCLUDED_PLANS = array('business', 'enterprise', 'master');
    
    /**
     * Plans that can purchase advertising add-on
     */
    const ADDON_ELIGIBLE_PLANS = array('creator', 'pro');
    
    /**
     * Get singleton instance
     */
    public static function instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        // Register admin menu
        add_action('admin_menu', array($this, 'register_admin_menu'));
        
        // Register settings
        add_action('admin_init', array($this, 'register_settings'));
        
        // AJAX handlers
        add_action('wp_ajax_castconductor_save_advertising_settings', array($this, 'ajax_save_settings'));
        add_action('wp_ajax_castconductor_test_vast_url', array($this, 'ajax_test_vast_url'));
    }
    
    /**
     * Check if advertising feature is available for current license
     * 
     * @return bool|array True if available, or array with upgrade info if not
     */
    public function is_feature_available() {
        $license_manager = CastConductor_License_Manager::instance();
        
        // No license = not available
        if (!$license_manager->is_license_valid()) {
            return array(
                'available' => false,
                'reason' => 'no_license',
                'message' => __('A valid CastConductor license is required to use advertising features.', 'castconductor'),
                'upgrade_url' => 'https://castconductor.com/pricing'
            );
        }
        
        $plan = strtolower($license_manager->get_plan());
        $features = $license_manager->get_features();
        
        // Check if plan includes advertising
        if (in_array($plan, self::INCLUDED_PLANS)) {
            return array('available' => true, 'included' => true);
        }
        
        // Check if advertising add-on is active
        if (!empty($features['advertising']) && $features['advertising'] === true) {
            return array('available' => true, 'addon' => true);
        }
        
        // Can purchase add-on?
        if (in_array($plan, self::ADDON_ELIGIBLE_PLANS)) {
            return array(
                'available' => false,
                'reason' => 'addon_required',
                'message' => sprintf(
                    __('Roku Ads integration requires the Advertising add-on ($29/month) or upgrade to Business plan. Your current plan: %s', 'castconductor'),
                    ucfirst($plan)
                ),
                'addon_url' => 'https://castconductor.com/addons/advertising',
                'upgrade_url' => 'https://castconductor.com/pricing'
            );
        }
        
        // Unknown plan
        return array(
            'available' => false,
            'reason' => 'unknown_plan',
            'message' => __('Unable to determine license plan. Please contact support.', 'castconductor'),
            'support_url' => 'https://kb.castconductor.com'
        );
    }
    
    /**
     * Check if advertising is enabled (feature available AND user has enabled it)
     */
    public function is_advertising_enabled() {
        $availability = $this->is_feature_available();
        if (!is_array($availability) || empty($availability['available'])) {
            return false;
        }
        
        return (bool) get_option('castconductor_advertising_enabled', false);
    }
    
    /**
     * Register admin menu
     */
    public function register_admin_menu() {
        add_submenu_page(
            'castconductor',
            __('Advertising', 'castconductor'),
            __('📺 Advertising', 'castconductor'),
            'manage_options',
            'castconductor-advertising',
            array($this, 'render_admin_page')
        );
    }
    
    /**
     * Register settings
     */
    public function register_settings() {
        // Main enable/disable
        register_setting('castconductor_advertising', 'castconductor_advertising_enabled', array(
            'type' => 'boolean',
            'default' => false,
            'sanitize_callback' => 'rest_sanitize_boolean'
        ));
        
        // Roku Publisher ID
        register_setting('castconductor_advertising', 'castconductor_roku_publisher_id', array(
            'type' => 'string',
            'default' => '',
            'sanitize_callback' => 'sanitize_text_field'
        ));
        
        // VAST tag URL
        register_setting('castconductor_advertising', 'castconductor_vast_url', array(
            'type' => 'string',
            'default' => '',
            'sanitize_callback' => 'esc_url_raw'
        ));
        
        // Fallback VAST URL
        register_setting('castconductor_advertising', 'castconductor_vast_url_fallback', array(
            'type' => 'string',
            'default' => '',
            'sanitize_callback' => 'esc_url_raw'
        ));
        
        // Pre-roll settings
        register_setting('castconductor_advertising', 'castconductor_preroll_enabled', array(
            'type' => 'boolean',
            'default' => true,
            'sanitize_callback' => 'rest_sanitize_boolean'
        ));
        
        register_setting('castconductor_advertising', 'castconductor_preroll_max_duration', array(
            'type' => 'integer',
            'default' => 30,
            'sanitize_callback' => 'absint'
        ));
        
        // Mid-roll settings
        register_setting('castconductor_advertising', 'castconductor_midroll_enabled', array(
            'type' => 'boolean',
            'default' => false,
            'sanitize_callback' => 'rest_sanitize_boolean'
        ));
        
        register_setting('castconductor_advertising', 'castconductor_midroll_interval', array(
            'type' => 'integer',
            'default' => 15,
            'sanitize_callback' => 'absint'
        ));
        
        register_setting('castconductor_advertising', 'castconductor_midroll_max_duration', array(
            'type' => 'integer',
            'default' => 30,
            'sanitize_callback' => 'absint'
        ));
        
        // Overlay settings
        register_setting('castconductor_advertising', 'castconductor_overlay_enabled', array(
            'type' => 'boolean',
            'default' => false,
            'sanitize_callback' => 'rest_sanitize_boolean'
        ));
        
        register_setting('castconductor_advertising', 'castconductor_overlay_position', array(
            'type' => 'string',
            'default' => 'lower_third',
            'sanitize_callback' => 'sanitize_text_field'
        ));
        
        register_setting('castconductor_advertising', 'castconductor_overlay_duration', array(
            'type' => 'integer',
            'default' => 10,
            'sanitize_callback' => 'absint'
        ));
        
        register_setting('castconductor_advertising', 'castconductor_overlay_interval', array(
            'type' => 'integer',
            'default' => 5,
            'sanitize_callback' => 'absint'
        ));
        
        register_setting('castconductor_advertising', 'castconductor_overlay_image_url', array(
            'type' => 'string',
            'default' => '',
            'sanitize_callback' => 'esc_url_raw'
        ));
        
        // Pause ads
        register_setting('castconductor_advertising', 'castconductor_pause_ads_enabled', array(
            'type' => 'boolean',
            'default' => false,
            'sanitize_callback' => 'rest_sanitize_boolean'
        ));
        
        // Frequency capping
        register_setting('castconductor_advertising', 'castconductor_frequency_cap_per_hour', array(
            'type' => 'integer',
            'default' => 4,
            'sanitize_callback' => 'absint'
        ));
        
        register_setting('castconductor_advertising', 'castconductor_min_ad_spacing', array(
            'type' => 'integer',
            'default' => 300,
            'sanitize_callback' => 'absint'
        ));
        
        // Ad-free hours
        register_setting('castconductor_advertising', 'castconductor_adfree_enabled', array(
            'type' => 'boolean',
            'default' => false,
            'sanitize_callback' => 'rest_sanitize_boolean'
        ));
        
        register_setting('castconductor_advertising', 'castconductor_adfree_start', array(
            'type' => 'string',
            'default' => '00:00',
            'sanitize_callback' => 'sanitize_text_field'
        ));
        
        register_setting('castconductor_advertising', 'castconductor_adfree_end', array(
            'type' => 'string',
            'default' => '06:00',
            'sanitize_callback' => 'sanitize_text_field'
        ));
    }
    
    /**
     * Get advertising configuration for API response
     * 
     * @return array|null Advertising config or null if not enabled
     */
    public function get_advertising_config() {
        // Check if feature is available and enabled
        if (!$this->is_advertising_enabled()) {
            return null;
        }
        
        $vast_url = get_option('castconductor_vast_url', '');
        
        // If no VAST URL configured, use Roku's default test ads (empty string triggers RAF default)
        // This allows testing without a real ad server
        $use_roku_default = empty($vast_url);
        
        return array(
            'enabled' => true,
            'use_roku_default' => $use_roku_default,
            'publisher_id' => get_option('castconductor_roku_publisher_id', ''),
            'vast_url' => $vast_url,
            'vast_url_fallback' => get_option('castconductor_vast_url_fallback', ''),
            'placements' => array(
                'preroll' => array(
                    'enabled' => (bool) get_option('castconductor_preroll_enabled', true),
                    'max_duration' => (int) get_option('castconductor_preroll_max_duration', 30)
                ),
                'midroll' => array(
                    'enabled' => (bool) get_option('castconductor_midroll_enabled', false),
                    'interval_minutes' => (int) get_option('castconductor_midroll_interval', 15),
                    'max_duration' => (int) get_option('castconductor_midroll_max_duration', 30)
                ),
                'overlay' => array(
                    'enabled' => (bool) get_option('castconductor_overlay_enabled', false),
                    'position' => get_option('castconductor_overlay_position', 'lower_third'),
                    'duration' => (int) get_option('castconductor_overlay_duration', 10),
                    'interval_minutes' => (int) get_option('castconductor_overlay_interval', 5),
                    'image_url' => get_option('castconductor_overlay_image_url', '')
                ),
                'pause' => array(
                    'enabled' => (bool) get_option('castconductor_pause_ads_enabled', false)
                )
            ),
            'frequency_cap' => array(
                'max_per_hour' => (int) get_option('castconductor_frequency_cap_per_hour', 4),
                'min_spacing_seconds' => (int) get_option('castconductor_min_ad_spacing', 300)
            ),
            'ad_free_hours' => array(
                'enabled' => (bool) get_option('castconductor_adfree_enabled', false),
                'start' => get_option('castconductor_adfree_start', '00:00'),
                'end' => get_option('castconductor_adfree_end', '06:00')
            )
        );
    }
    
    /**
     * Render admin page
     */
    public function render_admin_page() {
        $availability = $this->is_feature_available();
        $is_available = is_array($availability) && !empty($availability['available']);
        
        ?>
        <div class="wrap castconductor-advertising-page">
            <h1><?php _e('📺 Roku Advertising', 'castconductor'); ?></h1>
            
            <?php if (!$is_available): ?>
                <!-- Feature Not Available -->
                <div class="notice notice-warning">
                    <h2><?php _e('🔒 Advertising Feature Locked', 'castconductor'); ?></h2>
                    <p><?php echo esc_html($availability['message']); ?></p>
                    <?php if (!empty($availability['addon_url'])): ?>
                        <p>
                            <a href="<?php echo esc_url($availability['addon_url']); ?>" class="button button-primary" target="_blank">
                                <?php _e('Purchase Advertising Add-on ($29/mo)', 'castconductor'); ?>
                            </a>
                            <a href="<?php echo esc_url($availability['upgrade_url']); ?>" class="button" target="_blank">
                                <?php _e('Upgrade to Business Plan', 'castconductor'); ?>
                            </a>
                        </p>
                    <?php elseif (!empty($availability['upgrade_url'])): ?>
                        <p>
                            <a href="<?php echo esc_url($availability['upgrade_url']); ?>" class="button button-primary" target="_blank">
                                <?php _e('View Pricing', 'castconductor'); ?>
                            </a>
                        </p>
                    <?php endif; ?>
                </div>
                
                <!-- Feature Preview (read-only) -->
                <div class="card" style="opacity: 0.6; pointer-events: none;">
                    <h2><?php _e('Feature Preview', 'castconductor'); ?></h2>
                    <p><?php _e('With Roku Ads integration, you can monetize your channel with:', 'castconductor'); ?></p>
                    <ul style="list-style: disc; margin-left: 20px;">
                        <li><?php _e('Pre-roll video ads before content', 'castconductor'); ?></li>
                        <li><?php _e('Mid-roll ads at timed intervals', 'castconductor'); ?></li>
                        <li><?php _e('Overlay banner ads', 'castconductor'); ?></li>
                        <li><?php _e('Pause ads when viewers pause', 'castconductor'); ?></li>
                        <li><?php _e('Frequency capping controls', 'castconductor'); ?></li>
                        <li><?php _e('Ad-free hours configuration', 'castconductor'); ?></li>
                    </ul>
                    <p><strong><?php _e('CastConductor takes no cut of your Roku ad revenue!', 'castconductor'); ?></strong></p>
                </div>
                
            <?php else: ?>
                <!-- Feature Available -->
                <form method="post" action="options.php" id="castconductor-advertising-form">
                    <?php settings_fields('castconductor_advertising'); ?>
                    
                    <!-- Status Card -->
                    <div class="card">
                        <h2><?php _e('📊 Advertising Status', 'castconductor'); ?></h2>
                        <table class="form-table">
                            <tr>
                                <th scope="row"><?php _e('Feature Access', 'castconductor'); ?></th>
                                <td>
                                    <span style="color: green;">✅ <?php 
                                        if (!empty($availability['included'])) {
                                            _e('Included in your plan', 'castconductor');
                                        } else {
                                            _e('Active via add-on', 'castconductor');
                                        }
                                    ?></span>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php _e('Enable Advertising', 'castconductor'); ?></th>
                                <td>
                                    <label>
                                        <input type="checkbox" name="castconductor_advertising_enabled" value="1" 
                                            <?php checked(get_option('castconductor_advertising_enabled', false)); ?> />
                                        <?php _e('Enable Roku ads on my channel', 'castconductor'); ?>
                                    </label>
                                    <p class="description"><?php _e('When enabled, ads will be served to viewers based on your configuration below.', 'castconductor'); ?></p>
                                </td>
                            </tr>
                        </table>
                    </div>
                    
                    <!-- VAST Configuration -->
                    <div class="card">
                        <h2><?php _e('🎯 Roku Ads API Setup', 'castconductor'); ?></h2>
                        
                        <!-- OAuth Callback URL (read-only, auto-generated) -->
                        <div style="background: #f5f5f5; padding: 15px; border-radius: 4px; margin-bottom: 20px;">
                            <h3 style="margin-top: 0; margin-bottom: 10px; font-size: 14px;"><?php _e('📋 Your OAuth Callback URL', 'castconductor'); ?></h3>
                            <p style="margin-bottom: 8px; color: #666; font-size: 13px;">
                                <?php _e('Copy this URL to your Roku Ads API application settings:', 'castconductor'); ?>
                            </p>
                            <div style="display: flex; gap: 10px; align-items: center;">
                                <input type="text" 
                                    id="roku_callback_url" 
                                    value="<?php echo esc_url(rest_url('castconductor/v5/roku-ads/callback')); ?>" 
                                    class="regular-text" 
                                    readonly 
                                    style="background: white; flex: 1;" />
                                <button type="button" class="button" onclick="copyCallbackUrl()">
                                    <?php _e('Copy', 'castconductor'); ?>
                                </button>
                            </div>
                            <p style="margin-top: 8px; color: #666; font-size: 12px;">
                                <?php _e('This URL is auto-generated based on your WordPress installation.', 'castconductor'); ?>
                            </p>
                        </div>
                        
                        <table class="form-table">
                            <tr>
                                <th scope="row">
                                    <label for="castconductor_roku_publisher_id"><?php _e('Publisher ID', 'castconductor'); ?></label>
                                </th>
                                <td>
                                    <input type="text" id="castconductor_roku_publisher_id" name="castconductor_roku_publisher_id" 
                                        value="<?php echo esc_attr(get_option('castconductor_roku_publisher_id', '')); ?>" 
                                        class="regular-text" placeholder="pub-xxxxxxxx" />
                                    <p class="description"><?php _e('Your Roku Publisher ID from the Roku Ads dashboard.', 'castconductor'); ?></p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="castconductor_vast_url"><?php _e('VAST Tag URL', 'castconductor'); ?></label>
                                </th>
                                <td>
                                    <input type="url" id="castconductor_vast_url" name="castconductor_vast_url" 
                                        value="<?php echo esc_url(get_option('castconductor_vast_url', '')); ?>" 
                                        class="regular-text" placeholder="https://ads.roku.com/v1/vast/..." />
                                    <button type="button" class="button" id="test-vast-url"><?php _e('Test URL', 'castconductor'); ?></button>
                                    <p class="description">
                                        <?php _e('Your VAST tag URL from your ad server. <strong>Leave empty to use Roku\'s default test ads</strong> for development testing.', 'castconductor'); ?>
                                    </p>
                                    <details style="margin-top: 10px;">
                                        <summary style="cursor: pointer; color: #0073aa;"><?php _e('🧪 Test VAST URLs (for development)', 'castconductor'); ?></summary>
                                        <div style="margin-top: 10px; padding: 10px; background: #f5f5f5; border-radius: 4px;">
                                            <p><strong><?php _e('Option 1: Leave URL empty', 'castconductor'); ?></strong></p>
                                            <p style="margin: 5px 0 10px 0; color: #666;"><?php _e('RAF will use Roku\'s built-in test ad - simplest way to verify your integration works.', 'castconductor'); ?></p>
                                            
                                            <p><strong><?php _e('Option 2: Google IMA Sample Tags:', 'castconductor'); ?></strong></p>
                                            <ul style="margin: 5px 0 0 20px; list-style: disc;">
                                                <li><code style="font-size: 11px;">https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/single_preroll_skippable&sz=640x480&ciu_szs=300x250&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&correlator=</code></li>
                                            </ul>
                                            
                                            <p style="margin-top: 10px;"><strong><?php _e('Option 3: Roku Dev Tools Sample Tags:', 'castconductor'); ?></strong></p>
                                            <ul style="margin: 5px 0 0 20px; list-style: disc;">
                                                <li><code style="font-size: 11px;">https://devtools.web.roku.com/rafVAST/samples/singleInline.xml</code></li>
                                            </ul>
                                            
                                            <p style="margin-top: 15px; padding: 10px; background: #fff3cd; border-radius: 4px;">
                                                <strong>📧 <?php _e('Need a real ad server?', 'castconductor'); ?></strong><br>
                                                <?php _e('Contact <a href="mailto:adsupport@roku.com">adsupport@roku.com</a> for recommendations on ad servers and Roku backfill options.', 'castconductor'); ?>
                                            </p>
                                        </div>
                                    </details>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="castconductor_vast_url_fallback"><?php _e('Fallback VAST URL', 'castconductor'); ?></label>
                                </th>
                                <td>
                                    <input type="url" id="castconductor_vast_url_fallback" name="castconductor_vast_url_fallback" 
                                        value="<?php echo esc_url(get_option('castconductor_vast_url_fallback', '')); ?>" 
                                        class="regular-text" placeholder="https://..." />
                                    <p class="description"><?php _e('Optional: Used if primary VAST tag fails to return ads.', 'castconductor'); ?></p>
                                </td>
                            </tr>
                        </table>
                    </div>
                    
                    <!-- Ad Placements -->
                    <div class="card">
                        <h2><?php _e('📍 Ad Placements', 'castconductor'); ?></h2>
                        
                        <!-- Pre-roll -->
                        <h3><?php _e('Pre-roll Ads', 'castconductor'); ?></h3>
                        <table class="form-table">
                            <tr>
                                <th scope="row"><?php _e('Enable Pre-roll', 'castconductor'); ?></th>
                                <td>
                                    <label>
                                        <input type="checkbox" name="castconductor_preroll_enabled" value="1" 
                                            <?php checked(get_option('castconductor_preroll_enabled', true)); ?> />
                                        <?php _e('Show ads before content starts', 'castconductor'); ?>
                                    </label>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="castconductor_preroll_max_duration"><?php _e('Max Duration', 'castconductor'); ?></label>
                                </th>
                                <td>
                                    <input type="number" id="castconductor_preroll_max_duration" name="castconductor_preroll_max_duration" 
                                        value="<?php echo esc_attr(get_option('castconductor_preroll_max_duration', 30)); ?>" 
                                        min="5" max="120" step="5" /> <?php _e('seconds', 'castconductor'); ?>
                                </td>
                            </tr>
                        </table>
                        
                        <!-- Mid-roll -->
                        <h3><?php _e('Mid-roll Ads', 'castconductor'); ?></h3>
                        <table class="form-table">
                            <tr>
                                <th scope="row"><?php _e('Enable Mid-roll', 'castconductor'); ?></th>
                                <td>
                                    <label>
                                        <input type="checkbox" name="castconductor_midroll_enabled" value="1" 
                                            <?php checked(get_option('castconductor_midroll_enabled', false)); ?> />
                                        <?php _e('Show ads during content at intervals', 'castconductor'); ?>
                                    </label>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="castconductor_midroll_interval"><?php _e('Interval', 'castconductor'); ?></label>
                                </th>
                                <td>
                                    <input type="number" id="castconductor_midroll_interval" name="castconductor_midroll_interval" 
                                        value="<?php echo esc_attr(get_option('castconductor_midroll_interval', 15)); ?>" 
                                        min="1" max="60" step="1" /> <?php _e('minutes', 'castconductor'); ?>
                                    <p class="description"><?php _e('For testing, you can set to 1 minute. Recommended: 15-30 minutes for production.', 'castconductor'); ?></p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="castconductor_midroll_max_duration"><?php _e('Max Duration', 'castconductor'); ?></label>
                                </th>
                                <td>
                                    <input type="number" id="castconductor_midroll_max_duration" name="castconductor_midroll_max_duration" 
                                        value="<?php echo esc_attr(get_option('castconductor_midroll_max_duration', 30)); ?>" 
                                        min="5" max="120" step="5" /> <?php _e('seconds', 'castconductor'); ?>
                                </td>
                            </tr>
                        </table>
                        
                        <!-- Overlay -->
                        <h3><?php _e('Overlay Ads', 'castconductor'); ?></h3>
                        <table class="form-table">
                            <tr>
                                <th scope="row"><?php _e('Enable Overlay', 'castconductor'); ?></th>
                                <td>
                                    <label>
                                        <input type="checkbox" name="castconductor_overlay_enabled" value="1" 
                                            <?php checked(get_option('castconductor_overlay_enabled', false)); ?> />
                                        <?php _e('Show banner ads over content', 'castconductor'); ?>
                                    </label>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="castconductor_overlay_position"><?php _e('Position', 'castconductor'); ?></label>
                                </th>
                                <td>
                                    <select id="castconductor_overlay_position" name="castconductor_overlay_position">
                                        <option value="top" <?php selected(get_option('castconductor_overlay_position', 'lower_third'), 'top'); ?>><?php _e('Top', 'castconductor'); ?></option>
                                        <option value="bottom" <?php selected(get_option('castconductor_overlay_position', 'lower_third'), 'bottom'); ?>><?php _e('Bottom', 'castconductor'); ?></option>
                                        <option value="lower_third" <?php selected(get_option('castconductor_overlay_position', 'lower_third'), 'lower_third'); ?>><?php _e('Lower Third (Safe Zone)', 'castconductor'); ?></option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="castconductor_overlay_duration"><?php _e('Duration', 'castconductor'); ?></label>
                                </th>
                                <td>
                                    <input type="number" id="castconductor_overlay_duration" name="castconductor_overlay_duration" 
                                        value="<?php echo esc_attr(get_option('castconductor_overlay_duration', 10)); ?>" 
                                        min="5" max="30" step="1" /> <?php _e('seconds', 'castconductor'); ?>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="castconductor_overlay_interval"><?php _e('Interval', 'castconductor'); ?></label>
                                </th>
                                <td>
                                    <input type="number" id="castconductor_overlay_interval" name="castconductor_overlay_interval" 
                                        value="<?php echo esc_attr(get_option('castconductor_overlay_interval', 5)); ?>" 
                                        min="1" max="30" step="1" /> <?php _e('minutes', 'castconductor'); ?>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="castconductor_overlay_image_url"><?php _e('Image URL', 'castconductor'); ?></label>
                                </th>
                                <td>
                                    <input type="url" id="castconductor_overlay_image_url" name="castconductor_overlay_image_url" 
                                        value="<?php echo esc_attr(get_option('castconductor_overlay_image_url', '')); ?>" 
                                        class="regular-text" placeholder="https://example.com/banner-728x90.png" />
                                    <p class="description"><?php _e('Direct URL to banner image (728x90 recommended for lower third). Leave empty to use VAST companion ads or sponsor rotation.', 'castconductor'); ?></p>
                                </td>
                            </tr>
                        </table>
                        
                        <!-- Pause Ads -->
                        <h3><?php _e('Pause Ads', 'castconductor'); ?></h3>
                        <table class="form-table">
                            <tr>
                                <th scope="row"><?php _e('Enable Pause Ads', 'castconductor'); ?></th>
                                <td>
                                    <label>
                                        <input type="checkbox" name="castconductor_pause_ads_enabled" value="1" 
                                            <?php checked(get_option('castconductor_pause_ads_enabled', false)); ?> />
                                        <?php _e('Show ads when viewer pauses content', 'castconductor'); ?>
                                    </label>
                                </td>
                            </tr>
                        </table>
                    </div>
                    
                    <!-- Frequency Capping -->
                    <div class="card">
                        <h2><?php _e('⏱️ Frequency Capping', 'castconductor'); ?></h2>
                        <table class="form-table">
                            <tr>
                                <th scope="row">
                                    <label for="castconductor_frequency_cap_per_hour"><?php _e('Max Ads Per Hour', 'castconductor'); ?></label>
                                </th>
                                <td>
                                    <input type="number" id="castconductor_frequency_cap_per_hour" name="castconductor_frequency_cap_per_hour" 
                                        value="<?php echo esc_attr(get_option('castconductor_frequency_cap_per_hour', 4)); ?>" 
                                        min="1" max="20" step="1" />
                                    <p class="description"><?php _e('Maximum number of ads shown to a viewer per hour.', 'castconductor'); ?></p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="castconductor_min_ad_spacing"><?php _e('Minimum Ad Spacing', 'castconductor'); ?></label>
                                </th>
                                <td>
                                    <input type="number" id="castconductor_min_ad_spacing" name="castconductor_min_ad_spacing" 
                                        value="<?php echo esc_attr(get_option('castconductor_min_ad_spacing', 300)); ?>" 
                                        min="60" max="1800" step="60" /> <?php _e('seconds', 'castconductor'); ?>
                                    <p class="description"><?php _e('Minimum time between ads (default: 5 minutes).', 'castconductor'); ?></p>
                                </td>
                            </tr>
                        </table>
                    </div>
                    
                    <!-- Ad-Free Hours -->
                    <div class="card">
                        <h2><?php _e('🌙 Ad-Free Hours', 'castconductor'); ?></h2>
                        <table class="form-table">
                            <tr>
                                <th scope="row"><?php _e('Enable Ad-Free Window', 'castconductor'); ?></th>
                                <td>
                                    <label>
                                        <input type="checkbox" name="castconductor_adfree_enabled" value="1" 
                                            <?php checked(get_option('castconductor_adfree_enabled', false)); ?> />
                                        <?php _e('Disable ads during specified hours', 'castconductor'); ?>
                                    </label>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php _e('Ad-Free Window', 'castconductor'); ?></th>
                                <td>
                                    <label>
                                        <?php _e('From:', 'castconductor'); ?>
                                        <input type="time" name="castconductor_adfree_start" 
                                            value="<?php echo esc_attr(get_option('castconductor_adfree_start', '00:00')); ?>" />
                                    </label>
                                    <label style="margin-left: 20px;">
                                        <?php _e('To:', 'castconductor'); ?>
                                        <input type="time" name="castconductor_adfree_end" 
                                            value="<?php echo esc_attr(get_option('castconductor_adfree_end', '06:00')); ?>" />
                                    </label>
                                    <p class="description"><?php _e('Times are based on the viewer\'s local timezone.', 'castconductor'); ?></p>
                                </td>
                            </tr>
                        </table>
                    </div>
                    
                    <!-- Revenue Info -->
                    <div class="card" style="background: #f0f9ff; border-left: 4px solid #0073aa;">
                        <h2><?php _e('💰 Revenue Information', 'castconductor'); ?></h2>
                        <p><strong><?php _e('CastConductor takes no cut of your ad revenue!', 'castconductor'); ?></strong></p>
                        <p><?php _e('Your ad revenue is split between you and Roku according to their standard publisher terms. CastConductor does not take any portion of your share.', 'castconductor'); ?></p>
                        <p>
                            <a href="https://ads.roku.com" target="_blank" class="button"><?php _e('Open Roku Ads Manager', 'castconductor'); ?></a>
                            <a href="https://kb.castconductor.com/roku-ads-setup" target="_blank" class="button"><?php _e('Setup Guide', 'castconductor'); ?></a>
                        </p>
                    </div>
                    
                    <?php submit_button(__('Save Advertising Settings', 'castconductor')); ?>
                </form>
                
                <script>
                function copyCallbackUrl() {
                    var input = document.getElementById('roku_callback_url');
                    input.select();
                    input.setSelectionRange(0, 99999);
                    navigator.clipboard.writeText(input.value).then(function() {
                        alert('<?php _e('Callback URL copied to clipboard!', 'castconductor'); ?>');
                    }).catch(function() {
                        document.execCommand('copy');
                        alert('<?php _e('Callback URL copied to clipboard!', 'castconductor'); ?>');
                    });
                }
                
                jQuery(document).ready(function($) {
                    $('#test-vast-url').on('click', function() {
                        var vastUrl = $('#castconductor_vast_url').val();
                        if (!vastUrl) {
                            alert('<?php _e('Please enter a VAST URL first.', 'castconductor'); ?>');
                            return;
                        }
                        
                        var $btn = $(this);
                        $btn.prop('disabled', true).text('<?php _e('Testing...', 'castconductor'); ?>');
                        
                        $.post(ajaxurl, {
                            action: 'castconductor_test_vast_url',
                            vast_url: vastUrl,
                            nonce: '<?php echo wp_create_nonce('castconductor_advertising'); ?>'
                        }, function(response) {
                            $btn.prop('disabled', false).text('<?php _e('Test URL', 'castconductor'); ?>');
                            if (response.success) {
                                alert('<?php _e('✅ VAST URL is valid and returned ads!', 'castconductor'); ?>');
                            } else {
                                alert('<?php _e('❌ VAST URL test failed: ', 'castconductor'); ?>' + response.data);
                            }
                        }).fail(function() {
                            $btn.prop('disabled', false).text('<?php _e('Test URL', 'castconductor'); ?>');
                            alert('<?php _e('Network error. Please try again.', 'castconductor'); ?>');
                        });
                    });
                });
                </script>
            <?php endif; ?>
        </div>
        
        <style>
        .castconductor-advertising-page .card {
            max-width: 800px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .castconductor-advertising-page h3 {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #ddd;
        }
        .castconductor-advertising-page h3:first-of-type {
            margin-top: 0;
            padding-top: 0;
            border-top: none;
        }
        </style>
        <?php
    }
    
    /**
     * AJAX: Test VAST URL
     */
    public function ajax_test_vast_url() {
        check_ajax_referer('castconductor_advertising', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized');
        }
        
        $vast_url = esc_url_raw($_POST['vast_url'] ?? '');
        if (empty($vast_url)) {
            wp_send_json_error('No URL provided');
        }
        
        // Fetch the VAST URL
        $response = wp_remote_get($vast_url, array(
            'timeout' => 10,
            'headers' => array(
                'Accept' => 'application/xml'
            )
        ));
        
        if (is_wp_error($response)) {
            wp_send_json_error($response->get_error_message());
        }
        
        $status_code = wp_remote_retrieve_response_code($response);
        if ($status_code !== 200) {
            wp_send_json_error('HTTP ' . $status_code);
        }
        
        $body = wp_remote_retrieve_body($response);
        
        // Basic VAST validation - check for VAST root element
        if (strpos($body, '<VAST') === false && strpos($body, '<vast') === false) {
            wp_send_json_error('Response is not valid VAST XML');
        }
        
        wp_send_json_success();
    }
    
    /**
     * AJAX: Save settings
     */
    public function ajax_save_settings() {
        check_ajax_referer('castconductor_advertising', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized');
        }
        
        // Settings are saved via standard WordPress options API
        wp_send_json_success();
    }
}
