<?php
/**
 * Name: Coming Soon Page
 * Description: Display beautiful coming soon page with countdown timer, email subscription form, and social links while site is under construction but admins access normally
 * Category: Utilities
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Add Useful Functionality",
 *     "description": "Extend WordPress with helpful tools that make site management easier."
 *   },
 *   {
 *     "title": "Save Time",
 *     "description": "Automate or simplify tasks that would otherwise require manual work or additional tools."
 *   }
 * ]
 * Added: 2025-06-10
 * Tags: coming-soon, launch, pre-launch, countdown, subscribe
 * WhereToFind: {
 *   "location": "Frontend (Logged Out)",
 *   "url": "/",
 *   "instructions": "Visit site while logged out - coming soon page displays",
 *   "newTab": true
 * }
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardComingSoon {

    public function __construct() {
        add_action('template_redirect', [$this, 'show_coming_soon_page']);
        add_action('admin_bar_menu', [$this, 'add_admin_bar_notice'], 100);
        add_action('wp_ajax_nopriv_switchboard_subscribe', [$this, 'handle_subscription']);
        add_action('wp_ajax_switchboard_subscribe', [$this, 'handle_subscription']);
    }

    /**
     * Register data locations for this module
     */
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_coming-soon_settings',
                'switchboard_coming_soon_subscribers'
            ]
        ];
    }
    
    /**
     * Render settings panel for Coming Soon Page
     *
     * Displays comprehensive settings interface for coming soon/pre-launch page with:
     * - Prominent enable/disable checkbox with informational styling
     * - Logo upload capability using WordPress media uploader
     * - Main title and subtitle text inputs for page headline
     * - Launch date picker with countdown timer functionality
     * - Background type selector (solid color vs image)
     * - Color picker for solid background option
     * - Background image upload via media uploader
     * - Email subscription form toggle
     * - Social media links section (Facebook, Twitter, Instagram, LinkedIn)
     * - Email subscribers list with copy-to-clipboard functionality
     * - Dynamic display of subscriber count and emails in textarea
     *
     * The interface provides extensive customization for creating an attractive pre-launch
     * page. The logo and background image uploaders integrate with wp.media for native
     * WordPress experience. Conditional display logic shows/hides the remove buttons based
     * on whether media is selected. The background type dropdown allows switching between
     * color or image backgrounds. The subscription section displays all collected email
     * addresses in a readonly textarea with a copy button for easy export to email marketing
     * platforms. Social media fields accept full URLs for linking to social profiles. The
     * countdown timer automatically calculates and displays time remaining until launch date.
     * This module is perfect for generating buzz before site launch, collecting early
     * subscribers, and maintaining brand presence during development.
     *
     * @param array $settings Current module settings with 'enabled', 'title', 'subtitle', 'logo_id', 'launch_date', 'show_subscribe', 'bg_type', 'bg_color', 'bg_image_id', 'social_facebook', 'social_twitter', 'social_instagram', 'social_linkedin' keys
     * @return void Outputs HTML directly
     */
    public function render_settings($settings = []) {
        // Get settings from JSON structure
        $enabled = isset($settings['enabled']) ? $settings['enabled'] : 0;
        $title = isset($settings['title']) ? $settings['title'] : 'Something Amazing is Coming';
        $subtitle = isset($settings['subtitle']) ? wp_unslash($settings['subtitle']) : "We're working hard to bring you something special. Stay tuned!";
        $logo_id = isset($settings['logo_id']) ? $settings['logo_id'] : '';
        $logo_url = $logo_id ? wp_get_attachment_url($logo_id) : '';
        $launch_date = isset($settings['launch_date']) ? $settings['launch_date'] : '';
        $show_subscribe = isset($settings['show_subscribe']) ? $settings['show_subscribe'] : 1;
        $bg_type = isset($settings['bg_type']) ? $settings['bg_type'] : 'color';
        $bg_color = !empty($settings['bg_color']) ? $settings['bg_color'] : '#2563eb';
        $bg_image_id = isset($settings['bg_image_id']) ? $settings['bg_image_id'] : '';
        $bg_image_url = $bg_image_id ? wp_get_attachment_url($bg_image_id) : '';
        $social_facebook = isset($settings['social_facebook']) ? $settings['social_facebook'] : '';
        $social_twitter = isset($settings['social_twitter']) ? $settings['social_twitter'] : '';
        $social_instagram = isset($settings['social_instagram']) ? $settings['social_instagram'] : '';
        $social_linkedin = isset($settings['social_linkedin']) ? $settings['social_linkedin'] : '';
        $auto_disable = isset($settings['auto_disable']) ? $settings['auto_disable'] : 1; // Default to auto-disable

        $html = '
            <input type="hidden" name="module" value="coming-soon">

            <div class="sb-sp-group" style="margin-bottom: 24px;">
                <h3 class="sb-sp-heading">' . esc_html__('Coming Soon Page', 'wpswitchboard') . '</h3>
                <p class="sb-sp-description">' . esc_html__('Display a beautiful coming soon page with countdown timer, email subscription form, and social links while your site is under construction.', 'wpswitchboard') . '</p>
            </div>

            <input type="hidden" name="setting_enabled" value="0">
            <div class="sb-module-option-item sb-module-toggle-item" style="margin-bottom: 24px;">
                <div class="sb-module-option-content">
                    <div class="sb-module-toggle-header">
                        <strong class="sb-module-option-title">' . esc_html__('Enable Coming Soon Mode', 'wpswitchboard') . '</strong>
                        <label class="sb-module-toggle">
                            <input type="checkbox" name="setting_enabled" value="1" ' . checked($enabled, 1, false) . '>
                            <span class="sb-module-toggle-slider"></span>
                        </label>
                    </div>
                    <p class="sb-module-option-text">' . esc_html__('Visitors will see the coming soon page. Admins can still access the site normally.', 'wpswitchboard') . '</p>
                </div>
            </div>

            <div class="sb-sp-divider" style="margin: 24px 0;"></div>

            <div class="sb-sp-group" style="margin-bottom: 24px;">
                <label class="sb-sp-label">' . esc_html__('Logo', 'wpswitchboard') . '</label>
                <div id="coming-soon-logo-preview" style="margin-bottom: 12px;">';
            
        if ($logo_url) {
            $html .= '<img src="' . esc_url($logo_url) . '" style="max-width: 200px; height: auto; border-radius: 8px; display: block; border: 1px solid #e5e7eb; padding: 8px; background: #ffffff;">';
        }
        
        $html .= '</div>
                <div class="sb-sp-button-group" style="justify-content: flex-start; gap: 8px;">
                    <button type="button" class="button button-secondary button-small upload-logo-btn" data-target="coming-soon">' . esc_html__('Select Logo', 'wpswitchboard') . '</button>';
        if ($logo_id) {
            $html .= '<button type="button" class="button button-small remove-logo-btn" data-target="coming-soon">' . esc_html__('Remove Logo', 'wpswitchboard') . '</button>';
        }
        $html .= '</div>
                <input type="hidden" id="setting_logo" name="setting_logo" value="' . esc_attr($logo_id) . '">
            </div>

            <div class="sb-sp-group" style="margin-bottom: 24px;">
                <label for="setting_title" class="sb-sp-label">' . esc_html__('Main Title', 'wpswitchboard') . '</label>
                <input type="text" name="setting_title" id="setting_title" value="' . esc_attr($title) . '" class="sb-sp-input sb-sp-w-full">
                <p class="sb-sp-description">' . esc_html__('The main headline displayed on the coming soon page', 'wpswitchboard') . '</p>
            </div>

            <div class="sb-sp-group" style="margin-bottom: 24px;">
                <label for="setting_subtitle" class="sb-sp-label">' . esc_html__('Subtitle', 'wpswitchboard') . '</label>
                <textarea name="setting_subtitle" id="setting_subtitle" rows="3" class="sb-sp-textarea sb-sp-w-full">' . esc_textarea($subtitle) . '</textarea>
                <p class="sb-sp-description">' . esc_html__('Supporting text displayed below the main title', 'wpswitchboard') . '</p>
            </div>

            <div class="sb-sp-group" style="margin-bottom: 24px;">
                <label for="setting_launch_date" class="sb-sp-label">' . esc_html__('Launch Date', 'wpswitchboard') . '</label>
                <input type="datetime-local" name="setting_launch_date" id="setting_launch_date" value="' . esc_attr($launch_date) . '" class="sb-sp-input" style="max-width: 300px;">
                <p class="sb-sp-description">' . esc_html__('When will you launch? A countdown timer will be displayed on the coming soon page.', 'wpswitchboard') . '</p>
            </div>

            <input type="hidden" name="setting_auto_disable" value="0">
            <div class="sb-module-option-item sb-module-toggle-item" style="margin-bottom: 24px;">
                <div class="sb-module-option-content">
                    <div class="sb-module-toggle-header">
                        <strong class="sb-module-option-title">' . esc_html__('Auto-disable when countdown ends', 'wpswitchboard') . '</strong>
                        <label class="sb-module-toggle">
                            <input type="checkbox" name="setting_auto_disable" value="1" ' . checked($auto_disable, 1, false) . '>
                            <span class="sb-module-toggle-slider"></span>
                        </label>
                    </div>
                    <p class="sb-module-option-text">' . esc_html__('Automatically disable coming soon mode when the countdown reaches zero. If unchecked, visitors will see "We\'re Live!" but the page will remain active.', 'wpswitchboard') . '</p>
                </div>
            </div>

            <div class="sb-sp-divider" style="margin: 24px 0;"></div>

            <div class="sb-sp-group" style="margin-bottom: 16px;">
                <h3 class="sb-sp-heading">' . esc_html__('Background Settings', 'wpswitchboard') . '</h3>
                <p class="sb-sp-description">' . esc_html__('Choose between a solid color or background image for your coming soon page', 'wpswitchboard') . '</p>
            </div>

            <div class="switchboard-bg-type-tabs">
                <label class="switchboard-bg-tab ' . ($bg_type === 'color' ? 'active' : '') . '" data-type="color">
                    <input type="radio" name="setting_bg_type" value="color" ' . checked($bg_type, 'color', false) . '>
                    <span>' . esc_html__('Color', 'wpswitchboard') . '</span>
                </label>
                <label class="switchboard-bg-tab ' . ($bg_type === 'image' ? 'active' : '') . '" data-type="image">
                    <input type="radio" name="setting_bg_type" value="image" ' . checked($bg_type, 'image', false) . '>
                    <span>' . esc_html__('Image', 'wpswitchboard') . '</span>
                </label>
            </div>

            <div id="color-settings" class="switchboard-bg-settings" style="display: ' . ($bg_type === 'color' ? 'block' : 'none') . ';">
                <label for="setting_bg_color" class="sb-sp-label">' . esc_html__('Background Color', 'wpswitchboard') . '</label>
                <div class="sb-sp-flex sb-sp-gap">
                    <input type="color" name="setting_bg_color" id="setting_bg_color" value="' . esc_attr($bg_color) . '" data-default="#1e293b" style="width: 80px; height: 40px; border: 2px solid #ddd; border-radius: 8px; cursor: pointer;">
                    <input type="text" id="setting_bg_color_hex" value="' . esc_attr($bg_color) . '" readonly class="sb-sp-input sb-sp-col">
                </div>
            </div>

            <div id="image-settings" class="switchboard-bg-settings" style="display: ' . ($bg_type === 'image' ? 'block' : 'none') . ';">
                <label class="sb-sp-label">' . esc_html__('Background Image', 'wpswitchboard') . '</label>
                <div id="coming-soon-bg-preview" class="switchboard-image-preview">';

        if ($bg_image_url) {
            $html .= '<img src="' . esc_url($bg_image_url) . '" alt="Background preview">';
        } else {
            $html .= '<div class="switchboard-image-placeholder">
                        <span class="dashicons dashicons-format-image" style="font-size: 48px; opacity: 0.3;"></span>
                        <p>' . esc_html__('No image selected', 'wpswitchboard') . '</p>
                      </div>';
        }

        $html .= '</div>
                <input type="hidden" id="setting_bg_image" name="setting_bg_image" value="' . esc_attr($bg_image_id) . '">
                <div class="switchboard-image-actions">
                    <button type="button" class="button button-primary upload-bg-btn" data-target="coming-soon">
                        <span class="dashicons dashicons-upload sb-sp-mt-xs"></span>
                        ' . esc_html__('Select Image', 'wpswitchboard') . '
                    </button>
                    <button type="button" class="button remove-bg-btn" data-target="coming-soon" style="display:' . ($bg_image_id ? 'inline-flex' : 'none') . ';">
                        <span class="dashicons dashicons-no-alt sb-sp-mt-xs"></span>
                        ' . esc_html__('Remove', 'wpswitchboard') . '
                    </button>
                </div>
            </div>

            <div class="sb-sp-divider" style="margin: 24px 0;"></div>

            <input type="hidden" name="setting_show_subscribe" value="0">
            <div class="sb-module-option-item sb-module-toggle-item" style="margin-bottom: 24px;">
                <div class="sb-module-option-content">
                    <div class="sb-module-toggle-header">
                        <strong class="sb-module-option-title">' . esc_html__('Show Email Subscription Form', 'wpswitchboard') . '</strong>
                        <label class="sb-module-toggle">
                            <input type="checkbox" name="setting_show_subscribe" value="1" ' . checked($show_subscribe, 1, false) . '>
                            <span class="sb-module-toggle-slider"></span>
                        </label>
                    </div>
                    <p class="sb-module-option-text">' . esc_html__('Display an email subscription form on the coming soon page to collect visitor emails', 'wpswitchboard') . '</p>
                </div>
            </div>

            <div class="sb-sp-divider" style="margin: 24px 0;"></div>

            <div class="sb-sp-group" style="margin-bottom: 16px;">
                <h3 class="sb-sp-heading">' . esc_html__('Social Links', 'wpswitchboard') . '</h3>
                <p class="sb-sp-description">' . esc_html__('Add links to your social media profiles (optional)', 'wpswitchboard') . '</p>
            </div>

            <div class="switchboard-social-links-grid">
                <div class="switchboard-social-field">
                    <label for="setting_facebook" class="sb-sp-label">' . esc_html__('Facebook URL', 'wpswitchboard') . '</label>
                    <input type="url" name="setting_facebook" id="setting_facebook" value="' . esc_attr($social_facebook) . '" class="sb-sp-input">
                </div>

                <div class="switchboard-social-field">
                    <label for="setting_twitter" class="sb-sp-label">' . esc_html__('Twitter/X URL', 'wpswitchboard') . '</label>
                    <input type="url" name="setting_twitter" id="setting_twitter" value="' . esc_attr($social_twitter) . '" class="sb-sp-input">
                </div>

                <div class="switchboard-social-field">
                    <label for="setting_instagram" class="sb-sp-label">' . esc_html__('Instagram URL', 'wpswitchboard') . '</label>
                    <input type="url" name="setting_instagram" id="setting_instagram" value="' . esc_attr($social_instagram) . '" class="sb-sp-input">
                </div>

                <div class="switchboard-social-field">
                    <label for="setting_linkedin" class="sb-sp-label">' . esc_html__('LinkedIn URL', 'wpswitchboard') . '</label>
                    <input type="url" name="setting_linkedin" id="setting_linkedin" value="' . esc_attr($social_linkedin) . '" class="sb-sp-input">
                </div>
            </div>

            <div class="sb-sp-divider" style="margin: 24px 0;"></div>

            <div class="sb-sp-group" style="margin-bottom: 16px;">
                <h3 class="sb-sp-heading">' . esc_html__('Email Subscriptions', 'wpswitchboard') . '</h3>
                <p class="sb-sp-description">' . esc_html__('View and export email addresses collected from the subscription form', 'wpswitchboard') . '</p>
            </div>';

        // Get subscribers
        $subscribers = get_option('switchboard_coming_soon_subscribers', []);

        if (!empty($subscribers)) {
            $html .= '<div class="sb-sp-card sb-sp-p-4">
                <div class="sb-sp-flex sb-sp-items-center sb-sp-justify-between sb-sp-mb-3">
                    <h4 class="sb-sp-heading-sm">' . sprintf(esc_html__('%d subscriber(s)', 'wpswitchboard'), count($subscribers)) . '</h4>
                    <button type="button" class="button button-small button-secondary" id="copy-subscribers-btn">
                        <span class="dashicons dashicons-admin-page" style="margin-top: 3px;"></span> ' . esc_html__('Copy All', 'wpswitchboard') . '
                    </button>
                </div>
                <textarea readonly id="coming-soon-subscribers" class="sb-sp-textarea sb-sp-w-full" rows="8" style="font-family: \'Courier New\', monospace; font-size: 13px;">';
            foreach ($subscribers as $email) {
                $html .= esc_html($email) . "\n";
            }
            $html .= '</textarea>
                <p class="sb-sp-description" style="margin-top: 12px; margin-bottom: 0;">' . esc_html__('Click "Copy All" to copy all email addresses to your clipboard.', 'wpswitchboard') . '</p>
            </div>';
        } else {
            $html .= '<div class="sb-sp-info-box sb-sp-info-box-info">
                <p class="sb-sp-description" style="margin: 0;">' . esc_html__('No subscriptions yet. Email addresses will appear here once visitors subscribe through the coming soon page.', 'wpswitchboard') . '</p>
            </div>';
        }

        $html .= '
        <style>
            /* Background Type Tabs */
            .switchboard-bg-type-tabs {
                display: flex;
                gap: 0;
                margin-bottom: 0;
                border: 1px solid var(--primary-100);
                border-radius: 8px 8px 0 0;
                overflow: hidden;
                background: #f8fafc;
            }

            .switchboard-bg-tab {
                flex: 1;
                cursor: pointer;
                position: relative;
            }

            .switchboard-bg-tab input[type="radio"] {
                position: absolute;
                opacity: 0;
                pointer-events: none;
            }

            .switchboard-bg-tab span {
                display: block;
                padding: 12px 16px;
                text-align: center;
                font-size: 13px;
                font-weight: 500;
                color: #64748b;
                background: transparent;
                transition: all 0.15s ease;
                border-right: 1px solid var(--primary-100);
            }

            .switchboard-bg-tab:last-child span {
                border-right: none;
            }

            .switchboard-bg-tab:hover:not(.active) span {
                background: white;
                color: var(--primary-900);
            }

            .switchboard-bg-tab.active span {
                background: white;
                color: var(--primary-500);
                font-weight: 600;
                position: relative;
            }

            .switchboard-bg-tab.active span::after {
                content: "";
                position: absolute;
                bottom: 0;
                left: 0;
                right: 0;
                height: 2px;
                background: var(--primary-500);
            }

            /* Background Settings Sections - Tab Content Style */
            .switchboard-bg-settings {
                background: white;
                border: 1px solid var(--primary-100);
                border-top: none;
                border-radius: 0 0 8px 8px;
                padding: 20px;
                margin-bottom: 20px;
            }

            .switchboard-bg-settings label {
                display: block;
                margin: 0 0 8px 0;
                font-weight: 500;
                font-size: 13px;
                color: var(--primary-900);
            }

            /* Image Preview */
            .switchboard-image-preview {
                background: #f8fafc;
                border: 2px dashed var(--primary-100);
                border-radius: 6px;
                padding: 0;
                margin-bottom: 16px;
                height: 140px;
                display: flex;
                align-items: center;
                justify-content: center;
                overflow: hidden;
                position: relative;
            }

            .switchboard-image-preview img {
                width: 100%;
                height: 100%;
                border-radius: 6px;
                object-fit: cover;
                object-position: center;
            }

            .switchboard-image-placeholder {
                text-align: center;
                color: #94a3b8;
                padding: 20px;
            }

            .switchboard-image-placeholder .dashicons {
                opacity: 0.3;
                color: var(--primary-200);
            }

            .switchboard-image-placeholder p {
                margin: 8px 0 0 0;
                font-size: 12px;
                color: #94a3b8;
            }

            /* Image Actions - 3-Tier Button System */
            .switchboard-image-actions {
                display: flex;
                gap: 8px;
            }

            .switchboard-image-actions .button {
                display: inline-flex;
                align-items: center;
                gap: 6px;
                font-weight: 500;
                font-size: 14px;
                padding: 6px 12px;
                border-radius: 8px;
                transition: all 0.15s ease;
                box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
                cursor: pointer;
                line-height: 1.4;
            }

            /* Primary Button (Blue) */
            .switchboard-image-actions .button-primary {
                background: var(--primary-500);
                color: white;
                border: 1px solid var(--primary-500);
            }

            .switchboard-image-actions .button-primary:hover {
                background: var(--primary-600);
                border-color: var(--primary-600);
                box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            }

            /* Secondary Button (White with border) */
            .switchboard-image-actions .button:not(.button-primary) {
                background: white;
                color: var(--primary-900);
                border: 1px solid var(--primary-100);
            }

            .switchboard-image-actions .button:not(.button-primary):hover {
                background: var(--primary-50);
                border-color: var(--primary-200);
                color: var(--primary-700);
                box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.06);
            }

            .switchboard-image-actions .button:active {
                transform: scale(0.98);
            }

            /* Social Links Grid */
            .switchboard-social-links-grid {
                display: grid;
                grid-template-columns: repeat(2, 1fr);
                gap: 16px;
                margin-top: 12px;
            }

            .switchboard-social-field label {
                display: block;
                margin-bottom: 4px;
                font-weight: 500;
                font-size: 13px;
            }

            .switchboard-social-field input {
                width: 100%;
            }
        </style>

        <script>
            jQuery(document).ready(function($) {
                // Handle background type tab selection
                $(\'.switchboard-bg-tab\').on(\'click\', function() {
                    var type = $(this).data(\'type\');

                    // Update active state
                    $(\'.switchboard-bg-tab\').removeClass(\'active\');
                    $(this).addClass(\'active\');

                    // Update radio button
                    $(this).find(\'input[type="radio"]\').prop(\'checked\', true);

                    // Show/hide relevant settings
                    if (type === \'color\') {
                        $(\'#color-settings\').show();
                        $(\'#image-settings\').hide();
                    } else {
                        $(\'#color-settings\').hide();
                        $(\'#image-settings\').show();
                    }
                });

                // Sync color picker with hex input
                $(\'#setting_bg_color\').on(\'input\', function() {
                    $(\'#setting_bg_color_hex\').val($(this).val());
                });

                // Handle image upload
                $(\'.upload-bg-btn\').on(\'click\', function(e) {
                    e.preventDefault();
                    var button = $(this);
                    var target = button.data(\'target\');

                    var uploader = wp.media({
                        title: \'Select Background Image\',
                        button: { text: \'Use this image\' },
                        multiple: false
                    }).on(\'select\', function() {
                        var attachment = uploader.state().get(\'selection\').first().toJSON();
                        $(\'#setting_bg_image\').val(attachment.id);
                        $(\'#coming-soon-bg-preview\').html(\'<img src=\"\' + attachment.url + \'\" alt=\"Background preview\">\');
                        $(\'.remove-bg-btn[data-target=\"\' + target + \'\"]\').show();
                    }).open();
                });

                // Handle image removal
                $(\'.remove-bg-btn\').on(\'click\', function(e) {
                    e.preventDefault();
                    var target = $(this).data(\'target\');

                    $(\'#setting_bg_image\').val(\'\');
                    $(\'#coming-soon-bg-preview\').html(\'<div class=\"switchboard-image-placeholder\"><span class=\"dashicons dashicons-format-image\" style=\"font-size: 48px; opacity: 0.3;\"></span><p>No image selected</p></div>\');
                    $(this).hide();
                });

                // Handle logo upload
                $(\'.upload-logo-btn\').on(\'click\', function(e) {
                    e.preventDefault();
                    var button = $(this);
                    var target = button.data(\'target\');

                    var uploader = wp.media({
                        title: \'Select Logo\',
                        button: { text: \'Use this logo\' },
                        multiple: false
                    }).on(\'select\', function() {
                        var attachment = uploader.state().get(\'selection\').first().toJSON();
                        $(\'#setting_logo\').val(attachment.id);
                        $(\'#coming-soon-logo-preview\').html(\'<img src=\"\' + attachment.url + \'\" style=\"max-width: 200px; height: auto; border-radius: 8px; display: block; margin-bottom: 10px;\">\');
                        $(\'.remove-logo-btn[data-target=\"\' + target + \'\"]\').show();
                    }).open();
                });

                // Handle logo removal
                $(\'.remove-logo-btn\').on(\'click\', function(e) {
                    e.preventDefault();
                    $(\'#setting_logo\').val(\'\');
                    $(\'#coming-soon-logo-preview\').html(\'\');
                    $(this).hide();
                });

                // Copy subscribers to clipboard
                $(\'#copy-subscribers-btn\').on(\'click\', function() {
                    var textarea = document.getElementById(\'coming-soon-subscribers\');
                    textarea.select();
                    document.execCommand(\'copy\');

                    var btn = $(this);
                    var originalText = btn.text();
                    btn.text(\'Copied!\');
                    setTimeout(function() {
                        btn.text(originalText);
                    }, 2000);
                });
            });
        </script>
        ';
        echo $html;
    }

    public function show_coming_soon_page() {
        // Get settings from new JSON structure
        $settings = get_option('switchboard_coming-soon_settings', []);

        $enabled = isset($settings['enabled']) ? $settings['enabled'] : 0;
        if (!$enabled) {
            return;
        }

        // Check if countdown has ended and auto-disable is enabled
        $launch_date = isset($settings['launch_date']) ? $settings['launch_date'] : '';
        $auto_disable = isset($settings['auto_disable']) ? $settings['auto_disable'] : 1;

        if (!empty($launch_date) && $auto_disable) {
            // Parse launch date - datetime-local format is "YYYY-MM-DDTHH:MM"
            // Interpret as WordPress site timezone for consistency
            $wp_timezone = wp_timezone();

            try {
                $launch_datetime = new DateTime($launch_date, $wp_timezone);
                $launch_timestamp = $launch_datetime->getTimestamp();
                $current_timestamp = current_time('timestamp');

                if ($launch_timestamp <= $current_timestamp) {
                    // Launch time has passed - disable coming soon mode and clear settings
                    $settings['enabled'] = 0;
                    $settings['launch_date'] = '';
                    update_option('switchboard_coming-soon_settings', $settings);
                    return; // Allow normal site access
                }
            } catch (Exception $e) {
                // Invalid date format, continue showing coming soon page
            }
        }

        if (current_user_can('manage_options')) {
            return;
        }

        $title = isset($settings['title']) ? wp_unslash($settings['title']) : 'Something Amazing is Coming';
        $subtitle = isset($settings['subtitle']) ? wp_unslash($settings['subtitle']) : "We're working hard to bring you something special. Stay tuned!";
        $logo_id = isset($settings['logo_id']) ? $settings['logo_id'] : '';
        $logo_url = $logo_id ? wp_get_attachment_url($logo_id) : '';
        $launch_date = isset($settings['launch_date']) ? $settings['launch_date'] : '';
        $show_subscribe = isset($settings['show_subscribe']) ? $settings['show_subscribe'] : 1;
        $bg_type = isset($settings['bg_type']) ? $settings['bg_type'] : 'color';
        $bg_color = isset($settings['bg_color']) ? $settings['bg_color'] : '#2563eb';
        $bg_image_id = isset($settings['bg_image_id']) ? $settings['bg_image_id'] : '';
        $bg_image_url = $bg_image_id ? wp_get_attachment_url($bg_image_id) : '';
        $social_facebook = isset($settings['social_facebook']) ? $settings['social_facebook'] : '';
        $social_twitter = isset($settings['social_twitter']) ? $settings['social_twitter'] : '';
        $social_instagram = isset($settings['social_instagram']) ? $settings['social_instagram'] : '';
        $social_linkedin = isset($settings['social_linkedin']) ? $settings['social_linkedin'] : '';
        
        // Determine background style
        if ($bg_type === 'image' && $bg_image_url) {
            $bg_style = "background: url('" . esc_url($bg_image_url) . "') center/cover; position: relative;";
            $overlay = '<div style="position: absolute; inset: 0; background: rgba(0,0,0,0.6);"></div>';
        } else {
            $bg_style = "background: " . esc_attr($bg_color) . ";";
            $overlay = '';
        }
        
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title><?php echo esc_html($title); ?></title>
            <style>
                * { margin: 0; padding: 0; box-sizing: border-box; }
                body {
                    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
                    <?php echo $bg_style; ?>
                    color: white;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    min-height: 100vh;
                    text-align: center;
                    padding: 20px;
                }
                .container {
                    max-width: 800px;
                    position: relative;
                    z-index: 1;
                    animation: fadeIn 1s ease-out;
                }
                @keyframes fadeIn {
                    from { opacity: 0; transform: translateY(40px); }
                    to { opacity: 1; transform: translateY(0); }
                }
                .logo {
                    margin-bottom: 50px;
                }
                .logo img {
                    max-width: 280px;
                    height: auto;
                    border-radius: 20px;
                    box-shadow: 0 25px 80px rgba(0,0,0,0.3);
                }
                .icon {
                    font-size: 100px;
                    margin-bottom: 40px;
                    animation: float 3s ease-in-out infinite;
                }
                @keyframes float {
                    0%, 100% { transform: translateY(0); }
                    50% { transform: translateY(-20px); }
                }
                h1 {
                    font-size: 64px;
                    margin-bottom: 20px;
                    font-weight: 800;
                    line-height: 1.1;
                    text-shadow: 0 4px 20px rgba(0,0,0,0.2);
                }
                .subtitle {
                    font-size: 24px;
                    line-height: 1.6;
                    opacity: 0.95;
                    margin-bottom: 60px;
                    font-weight: 300;
                }
                .countdown {
                    display: flex;
                    justify-content: center;
                    gap: 30px;
                    margin-bottom: 60px;
                }
                .countdown-item {
                    background: rgba(255,255,255,0.15);
                    padding: 30px 40px;
                    border-radius: 16px;
                    backdrop-filter: blur(20px);
                    border: 1px solid rgba(255,255,255,0.2);
                    transition: transform 0.3s;
                }
                .countdown-item:hover {
                    transform: translateY(-5px);
                }
                .countdown-value {
                    font-size: 56px;
                    font-weight: 800;
                    display: block;
                    line-height: 1;
                }
                .countdown-label {
                    font-size: 14px;
                    opacity: 0.8;
                    text-transform: uppercase;
                    letter-spacing: 2px;
                    margin-top: 12px;
                    font-weight: 600;
                }
                .subscribe-form {
                    max-width: 500px;
                    margin: 0 auto 50px;
                }
                .subscribe-form form {
                    display: flex;
                    gap: 12px;
                }
                .subscribe-form input[type="email"] {
                    flex: 1;
                    padding: 18px 24px;
                    border: 2px solid rgba(255,255,255,0.3);
                    border-radius: 50px;
                    background: rgba(255,255,255,0.1);
                    color: white;
                    font-size: 16px;
                    backdrop-filter: blur(10px);
                    transition: all 0.3s;
                }
                .subscribe-form input[type="email"]::placeholder {
                    color: rgba(255,255,255,0.6);
                }
                .subscribe-form input[type="email"]:focus {
                    outline: none;
                    border-color: rgba(255,255,255,0.6);
                    background: rgba(255,255,255,0.15);
                }
                .subscribe-form button {
                    padding: 18px 36px;
                    background: white;
                    color: #1e293b;
                    border: none;
                    border-radius: 50px;
                    font-size: 16px;
                    font-weight: 700;
                    cursor: pointer;
                    transition: all 0.3s;
                    text-transform: uppercase;
                    letter-spacing: 1px;
                }
                .subscribe-form button:hover {
                    transform: translateY(-2px);
                    box-shadow: 0 10px 30px rgba(0,0,0,0.2);
                }
                .social-links {
                    display: flex;
                    justify-content: center;
                    gap: 20px;
                }
                .social-links a {
                    width: 50px;
                    height: 50px;
                    background: rgba(255,255,255,0.15);
                    border-radius: 50%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    color: white;
                    text-decoration: none;
                    font-size: 20px;
                    backdrop-filter: blur(10px);
                    border: 1px solid rgba(255,255,255,0.2);
                    transition: all 0.3s;
                }
                .social-links a:hover {
                    background: rgba(255,255,255,0.3);
                    transform: translateY(-3px);
                }
                .message {
                    margin-top: 20px;
                    padding: 12px 24px;
                    border-radius: 8px;
                    display: none;
                }
                .message.success {
                    background: rgba(34, 197, 94, 0.2);
                    border: 1px solid rgba(34, 197, 94, 0.4);
                }
                .message.error {
                    background: rgba(239, 68, 68, 0.2);
                    border: 1px solid rgba(239, 68, 68, 0.4);
                }
                @media (max-width: 768px) {
                    h1 { font-size: 42px; }
                    .subtitle { font-size: 18px; }
                    .countdown { flex-wrap: wrap; gap: 15px; }
                    .countdown-item { padding: 20px 25px; }
                    .countdown-value { font-size: 40px; }
                    .subscribe-form form { flex-direction: column; }
                    .icon { font-size: 70px; }
                }
            </style>
        </head>
        <body>
            <?php echo $overlay; ?>
            <div class="container">
                <?php if ($logo_url): ?>
                    <div class="logo">
                        <img src="<?php echo esc_url($logo_url); ?>" alt="Logo">
                    </div>
                <?php else: ?>
                    <div class="icon"></div>
                <?php endif; ?>
                
                <h1><?php echo esc_html($title); ?></h1>
                <p class="subtitle"><?php echo nl2br(esc_html($subtitle)); ?></p>
                
                <?php if ($launch_date): ?>
                    <div class="countdown" id="countdown">
                        <div class="countdown-item">
                            <span class="countdown-value" id="days">00</span>
                            <span class="countdown-label">Days</span>
                        </div>
                        <div class="countdown-item">
                            <span class="countdown-value" id="hours">00</span>
                            <span class="countdown-label">Hours</span>
                        </div>
                        <div class="countdown-item">
                            <span class="countdown-value" id="minutes">00</span>
                            <span class="countdown-label">Minutes</span>
                        </div>
                        <div class="countdown-item">
                            <span class="countdown-value" id="seconds">00</span>
                            <span class="countdown-label">Seconds</span>
                        </div>
                    </div>
                    
                    <script>
                    <?php
                    // Convert launch_date to UTC timestamp for JavaScript
                    // This ensures both PHP and JS use the exact same moment in time
                    $wp_timezone = wp_timezone();
                    $launch_timestamp_ms = 0;
                    try {
                        $launch_datetime = new DateTime($launch_date, $wp_timezone);
                        $launch_timestamp_ms = $launch_datetime->getTimestamp() * 1000; // Convert to milliseconds for JS
                    } catch (Exception $e) {
                        $launch_timestamp_ms = 0;
                    }
                    ?>
                    const launchTimeMs = <?php echo intval($launch_timestamp_ms); ?>;

                    if (launchTimeMs > 0) {
                        function updateCountdown() {
                            const now = Date.now();
                            const distance = launchTimeMs - now;

                            if (distance < 0) {
                                document.getElementById('countdown').innerHTML = '<div style="background: rgba(255,255,255,0.2); padding: 30px; border-radius: 16px; backdrop-filter: blur(10px);"><p style="font-size: 42px; font-weight: 800; margin: 0;">We\'re Live! Redirecting...</p></div>';
                                // Auto-refresh to allow normal site access
                                setTimeout(function() {
                                    window.location.reload();
                                }, 1500);
                                return;
                            }

                            const days = Math.floor(distance / (1000 * 60 * 60 * 24));
                            const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                            const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                            const seconds = Math.floor((distance % (1000 * 60)) / 1000);

                            const daysEl = document.getElementById('days');
                            const hoursEl = document.getElementById('hours');
                            const minutesEl = document.getElementById('minutes');
                            const secondsEl = document.getElementById('seconds');

                            if (daysEl) daysEl.textContent = String(days).padStart(2, '0');
                            if (hoursEl) hoursEl.textContent = String(hours).padStart(2, '0');
                            if (minutesEl) minutesEl.textContent = String(minutes).padStart(2, '0');
                            if (secondsEl) secondsEl.textContent = String(seconds).padStart(2, '0');
                        }

                        updateCountdown();
                        setInterval(updateCountdown, 1000);
                    } else {
                        document.getElementById('countdown').innerHTML = '<p style="opacity: 0.7;">Countdown will appear when launch date is set</p>';
                    }
                    </script>
                <?php endif; ?>
                
                <?php if ($show_subscribe): ?>
                    <div class="subscribe-form">
                        <form id="subscribe-form">
                            <input type="email" name="email" placeholder="Enter your email" required class="sb-sp-input">
                            <button type="submit">Notify Me</button>
                        </form>
                        <div class="message" id="message"></div>
                    </div>
                    
                    <script>
                    document.getElementById('subscribe-form').addEventListener('submit', function(e) {
                        e.preventDefault();
                        const form = this;
                        const email = form.querySelector('input[name="email"]').value;
                        const message = document.getElementById('message');
                        const button = form.querySelector('button');
                        
                        button.disabled = true;
                        button.textContent = 'Subscribing...';
                        
                        fetch('<?php echo esc_url(admin_url('admin-ajax.php')); ?>', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                            body: 'action=switchboard_subscribe&nonce=<?php echo wp_create_nonce('coming_soon_subscribe'); ?>&email=' + encodeURIComponent(email)
                        })
                        .then(response => response.json())
                        .then(data => {
                            message.textContent = data.data.message;
                            message.className = 'message ' + (data.success ? 'success' : 'error');
                            message.style.display = 'block';
                            
                            if (data.success) {
                                form.reset();
                            }
                            
                            button.disabled = false;
                            button.textContent = 'Notify Me';
                        });
                    });
                    </script>
                <?php endif; ?>
                
                <?php if ($social_facebook || $social_twitter || $social_instagram || $social_linkedin): ?>
                    <div class="social-links">
                        <?php if ($social_facebook): ?>
                            <a href="<?php echo esc_url($social_facebook); ?>" target="_blank" rel="noopener" aria-label="Facebook">
                                <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>
                            </a>
                        <?php endif; ?>
                        <?php if ($social_twitter): ?>
                            <a href="<?php echo esc_url($social_twitter); ?>" target="_blank" rel="noopener" aria-label="X (Twitter)">
                                <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>
                            </a>
                        <?php endif; ?>
                        <?php if ($social_instagram): ?>
                            <a href="<?php echo esc_url($social_instagram); ?>" target="_blank" rel="noopener" aria-label="Instagram">
                                <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zm0-2.163c-3.259 0-3.667.014-4.947.072-4.358.2-6.78 2.618-6.98 6.98-.059 1.281-.073 1.689-.073 4.948 0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98 1.281.058 1.689.072 4.948.072 3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98-1.281-.059-1.69-.073-4.949-.073zm0 5.838c-3.403 0-6.162 2.759-6.162 6.162s2.759 6.163 6.162 6.163 6.162-2.759 6.162-6.163c0-3.403-2.759-6.162-6.162-6.162zm0 10.162c-2.209 0-4-1.79-4-4 0-2.209 1.791-4 4-4s4 1.791 4 4c0 2.21-1.791 4-4 4zm6.406-11.845c-.796 0-1.441.645-1.441 1.44s.645 1.44 1.441 1.44c.795 0 1.439-.645 1.439-1.44s-.644-1.44-1.439-1.44z"/></svg>
                            </a>
                        <?php endif; ?>
                        <?php if ($social_linkedin): ?>
                            <a href="<?php echo esc_url($social_linkedin); ?>" target="_blank" rel="noopener" aria-label="LinkedIn">
                                <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg>
                            </a>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </body>
        </html>
        <?php
        exit;
    }
    
    public function handle_subscription() {
        // Verify nonce for security
        check_ajax_referer('coming_soon_subscribe', 'nonce');

        $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';

        if (!is_email($email)) {
            wp_send_json_error(['message' => 'Please enter a valid email address.']);
        }

        // Get current subscribers from separate option
        $subscribers = get_option('switchboard_coming_soon_subscribers', []);

        if (in_array($email, $subscribers)) {
            wp_send_json_error(['message' => "You're already subscribed!"]);
        }

        // Add subscriber
        $subscribers[] = $email;
        update_option('switchboard_coming_soon_subscribers', $subscribers);

        wp_send_json_success(['message' => "Thanks! We'll notify you when we launch."]);
    }

    public function add_admin_bar_notice($wp_admin_bar) {
        $settings = get_option('switchboard_coming-soon_settings', []);
        $enabled = isset($settings['enabled']) ? $settings['enabled'] : 0;

        if (!$enabled) {
            return;
        }

        $wp_admin_bar->add_node([
            'id' => 'coming-soon-mode',
            'title' => 'Coming Soon Mode Active',
            'href' => admin_url('admin.php?page=switchboard')
        ]);
    }

}

$switchboard_instance = new SwitchboardComingSoon();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
