<?php
// If this file is called directly, abort.
if (!defined('ABSPATH')) {
    exit;
}

// Check if user has required capabilities
if (!current_user_can('manage_options')) {
    wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'text-to-speech-tts'));
}

// Process form submission
if (isset($_POST['mementor_tts_save_advanced_settings']) && check_admin_referer('mementor_tts_advanced_settings')) {
    // Frontend Behavior
    update_option('mementor_tts_lazy_load_player', isset($_POST['mementor_tts_lazy_load_player']) ? '1' : '0');

    // Debug Settings
    update_option('mementor_tts_debug_mode', isset($_POST['mementor_tts_debug_mode']) ? '1' : '0');
    update_option('mementor_tts_remote_debug_enabled', isset($_POST['mementor_tts_remote_debug_enabled']) ? '1' : '0');
    update_option('mementor_tts_remote_debug_include_content', isset($_POST['mementor_tts_remote_debug_include_content']) ? '1' : '0');

    // Compatibility Settings
    update_option('mementor_tts_compatibility_mode', isset($_POST['mementor_tts_compatibility_mode']) ? '1' : '0');

    // Data Management
    update_option('mementor_tts_delete_data', isset($_POST['mementor_tts_delete_data']) ? '1' : '0');

    // Custom CSS
    if (isset($_POST['mementor_tts_custom_css'])) {
        update_option('mementor_tts_custom_css', wp_strip_all_tags(wp_unslash($_POST['mementor_tts_custom_css'])));
    }

    $advanced_saved = true;
}

// Include plugin.php to use is_plugin_active function
if (!function_exists('is_plugin_active')) {
    include_once(ABSPATH . 'wp-admin/includes/plugin.php');
}

// Check if user has a paid plan via SaaS
$is_pro_active = ttswp_has_paid_plan();
?>

<?php
$tts_page_title = __('Advanced', 'text-to-speech-tts');
$tts_topbar_actions = '<button type="button" id="mementor_tts_export_settings" class="tts-btn" title="' . esc_attr__('Download settings backup', 'text-to-speech-tts') . '">&darr; ' . esc_html__('Export', 'text-to-speech-tts') . '</button>'
    . '<button type="button" id="mementor_tts_import_settings" class="tts-btn" title="' . esc_attr__('Restore settings from file', 'text-to-speech-tts') . '">&uarr; ' . esc_html__('Import', 'text-to-speech-tts') . '</button>'
    . '<input type="file" id="mementor_tts_import_file" style="display: none;" accept=".json">'
    . '<button type="submit" form="mementor-tts-advanced-settings-form" class="tts-btn tts-btn-primary">' . esc_html__('Save settings', 'text-to-speech-tts') . '</button>';
$tts_requires_connection = true; // gate page behind SaaS connection

include MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/layout-open.php';
?>
<?php include(MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/navigation.php'); ?>

            <form method="post" action="" id="mementor-tts-advanced-settings-form">
                <?php wp_nonce_field('mementor_tts_advanced_settings'); ?>

                <!-- Frontend Behavior -->
                <div class="tts-card">
                    <div class="tts-card-header tts-card-header-inline">
                        <h3 class="tts-card-title"><?php esc_html_e('Frontend Behavior', 'text-to-speech-tts'); ?></h3>
                        <p class="tts-card-desc"><?php esc_html_e('Control how the player renders for visitors', 'text-to-speech-tts'); ?></p>
                    </div>

                    <div class="tts-setting-row">
                        <div>
                            <div class="tts-setting-label"><?php esc_html_e('Lazy Load Player', 'text-to-speech-tts'); ?></div>
                            <div class="tts-setting-hint"><?php esc_html_e('Only initialize the audio player when it scrolls into view. Improves page load performance.', 'text-to-speech-tts'); ?></div>
                        </div>
                        <label class="tts-toggle">
                            <input type="checkbox" name="mementor_tts_lazy_load_player" value="1" <?php checked(get_option('mementor_tts_lazy_load_player', '0'), '1'); ?>>
                            <span class="tts-toggle-slider"></span>
                        </label>
                    </div>
                </div>

                <!-- Debug & Data -->
                <div class="tts-card">
                    <div class="tts-card-header tts-card-header-inline">
                        <h3 class="tts-card-title"><?php esc_html_e('Debug & Data', 'text-to-speech-tts'); ?></h3>
                        <p class="tts-card-desc"><?php esc_html_e('Diagnostics and data management', 'text-to-speech-tts'); ?></p>
                    </div>

                    <div class="tts-setting-row">
                        <div>
                            <div class="tts-setting-label"><?php esc_html_e('Debug Mode', 'text-to-speech-tts'); ?></div>
                            <div class="tts-setting-hint"><?php esc_html_e('Logs detailed information for troubleshooting. Only for development or support.', 'text-to-speech-tts'); ?></div>
                        </div>
                        <label class="tts-toggle">
                            <input type="checkbox" name="mementor_tts_debug_mode" value="1" <?php checked(get_option('mementor_tts_debug_mode', '0'), '1'); ?>>
                            <span class="tts-toggle-slider"></span>
                        </label>
                    </div>

                    <div class="tts-setting-row">
                        <div>
                            <div class="tts-setting-label"><?php esc_html_e('Remote Debug Logging', 'text-to-speech-tts'); ?></div>
                            <div class="tts-setting-hint"><?php esc_html_e('Send diagnostic events to TTSWP support so they can troubleshoot generation issues without needing access to your wp-admin or server. No content is sent unless you also enable "Include Content Samples" below.', 'text-to-speech-tts'); ?></div>
                            <?php
                            $tts_last_remote_event = get_transient('mementor_tts_remote_debug_last_event');
                            if ($tts_last_remote_event && get_option('mementor_tts_remote_debug_enabled', '0') === '1') {
                                echo '<div class="tts-setting-hint" style="color:#0F6E56;margin-top:6px;">'
                                    . sprintf(
                                        /* translators: %s: human-readable time ago */
                                        esc_html__('Last event sent: %s ago', 'text-to-speech-tts'),
                                        esc_html(human_time_diff((int) $tts_last_remote_event))
                                    )
                                    . '</div>';
                            }
                            ?>
                        </div>
                        <label class="tts-toggle">
                            <input type="checkbox" name="mementor_tts_remote_debug_enabled" value="1" <?php checked(get_option('mementor_tts_remote_debug_enabled', '0'), '1'); ?>>
                            <span class="tts-toggle-slider"></span>
                        </label>
                    </div>

                    <div class="tts-setting-row">
                        <div>
                            <div class="tts-setting-label"><?php esc_html_e('Include Content Samples', 'text-to-speech-tts'); ?></div>
                            <div class="tts-setting-hint"><?php esc_html_e('When on, short samples of post content are attached to debug events. Useful for diagnosing content-extraction issues. Leave off if your posts contain sensitive data.', 'text-to-speech-tts'); ?></div>
                        </div>
                        <label class="tts-toggle">
                            <input type="checkbox" name="mementor_tts_remote_debug_include_content" value="1" <?php checked(get_option('mementor_tts_remote_debug_include_content', '0'), '1'); ?>>
                            <span class="tts-toggle-slider"></span>
                        </label>
                    </div>

                    <div class="tts-setting-row">
                        <div>
                            <div class="tts-setting-label"><?php esc_html_e('Compatibility Mode', 'text-to-speech-tts'); ?></div>
                            <div class="tts-setting-hint"><?php esc_html_e('Prevents conflicts with quiz plugins, form builders, and tooltips. Enable if you have issues with TutorLMS, Elementor, etc.', 'text-to-speech-tts'); ?></div>
                        </div>
                        <label class="tts-toggle">
                            <input type="checkbox" name="mementor_tts_compatibility_mode" value="1" <?php checked(get_option('mementor_tts_compatibility_mode', '0'), '1'); ?>>
                            <span class="tts-toggle-slider"></span>
                        </label>
                    </div>

                    <div class="tts-setting-row">
                        <div>
                            <div class="tts-setting-label"><?php esc_html_e('Delete Data on Uninstall', 'text-to-speech-tts'); ?></div>
                            <div class="tts-setting-hint"><?php esc_html_e('Removes all plugin data from the database when uninstalled. Cannot be undone.', 'text-to-speech-tts'); ?></div>
                        </div>
                        <label class="tts-toggle">
                            <input type="checkbox" name="mementor_tts_delete_data" value="1" <?php checked(get_option('mementor_tts_delete_data', '1'), '1'); ?>>
                            <span class="tts-toggle-slider"></span>
                        </label>
                    </div>

                    <div class="tts-setting-row">
                        <div>
                            <div class="tts-setting-label"><?php esc_html_e('Clear Transients', 'text-to-speech-tts'); ?></div>
                            <div class="tts-setting-hint"><?php esc_html_e('Deletes all cached data (voice lists, API validation, usage stats, CSS cache).', 'text-to-speech-tts'); ?></div>
                        </div>
                        <div class="tts-adv-clear-wrap">
                            <button type="button" id="mementor_tts_clear_transients" class="tts-btn">
                                <?php esc_html_e('Clear', 'text-to-speech-tts'); ?>
                            </button>
                            <span id="mementor_tts_clear_transients_status" class="tts-adv-status" style="display: none;"></span>
                        </div>
                    </div>
                </div>

                <!-- Developer -->
                <div class="tts-card">
                    <div class="tts-card-header tts-card-header-inline">
                        <h3 class="tts-card-title"><?php esc_html_e('Developer', 'text-to-speech-tts'); ?></h3>
                        <p class="tts-card-desc"><?php esc_html_e('Custom overrides for advanced users', 'text-to-speech-tts'); ?></p>
                    </div>

                    <div class="tts-setting-row" style="flex-direction: column; align-items: stretch;">
                        <div>
                            <div class="tts-setting-label"><?php esc_html_e('Custom CSS', 'text-to-speech-tts'); ?></div>
                            <div class="tts-setting-hint"><?php esc_html_e('Add custom CSS to style the audio player. Applied on all pages where the player renders.', 'text-to-speech-tts'); ?></div>
                            <div class="tts-setting-hint" style="margin-top: 4px; font-family: monospace; font-size: 11px; line-height: 1.6;">
                                <code>.mementor-tts-player-container</code> —
                                <code>.mementor-tts-player</code> —
                                <code>.mementor-tts-play-btn</code> —
                                <code>.mementor-tts-progress-bar</code> —
                                <code>.mementor-tts-time</code> —
                                <code>.mementor-tts-volume</code> —
                                <code>.mementor-tts-speed</code>
                            </div>
                        </div>
                        <textarea name="mementor_tts_custom_css" rows="6" style="margin-top: 8px; font-family: monospace; font-size: 13px; width: 100%; resize: vertical; padding: 10px 12px; border: 1px solid var(--tts-border-color); border-radius: var(--tts-radius-md); background: var(--tts-bg-primary);" placeholder=".mementor-tts-player-container {
    max-width: 600px;
    margin: 0 auto;
}"><?php echo esc_textarea(get_option('mementor_tts_custom_css', '')); ?></textarea>
                    </div>
                </div>

                <input type="hidden" name="mementor_tts_save_advanced_settings" value="1">

                <?php
                /**
                 * Hook for PRO plugin to add additional sections to the Advanced page
                 *
                 * @since 1.0.0
                 */
                do_action('mementor_tts_advanced_page_after');
                ?>
            </form>

            <style>
            /* Grid cell with toggle */
            .tts-adv-toggle-cell {
                display: flex;
                justify-content: space-between;
                align-items: center;
            }

            /* Spacing above field inputs in grid */
            .tts-adv-field-spacing {
                margin-top: 8px;
            }

            /* Toggle switch */
            .tts-toggle {
                position: relative;
                display: inline-block;
                width: 36px;
                height: 20px;
                cursor: pointer;
                flex-shrink: 0;
            }

            .tts-toggle input {
                opacity: 0;
                width: 0;
                height: 0;
                position: absolute;
            }

            .tts-toggle-slider {
                position: absolute;
                inset: 0;
                background-color: #cbd5e1;
                border-radius: 20px;
                transition: background-color 0.2s;
            }

            .tts-toggle-slider::before {
                content: "";
                position: absolute;
                height: 14px;
                width: 14px;
                left: 3px;
                bottom: 3px;
                background-color: #fff;
                border-radius: 50%;
                transition: transform 0.2s;
            }

            .tts-toggle input:checked + .tts-toggle-slider {
                background-color: var(--tts-purple, #7c3aed);
            }

            .tts-toggle input:checked + .tts-toggle-slider::before {
                transform: translateX(16px);
            }

            /* Number inputs */
            .tts-adv-number {
                width: 64px !important;
                padding: 4px 8px;
                border: var(--tts-border);
                border-radius: var(--tts-radius-sm);
                font-size: 13px;
                text-align: center;
            }

            .tts-adv-number:focus {
                outline: none;
                border-color: var(--tts-purple);
                box-shadow: 0 0 0 2px var(--tts-purple-bg);
            }

            .tts-adv-number-wrap {
                display: inline-flex;
                align-items: center;
                gap: 4px;
            }

            .tts-adv-unit {
                font-size: 12px;
                color: var(--tts-text-secondary, #757575);
            }

            /* Clear transients */
            .tts-adv-clear-wrap {
                display: flex;
                align-items: center;
                gap: 8px;
            }

            .tts-adv-status {
                font-size: 13px;
            }
            </style>

<?php include MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/layout-close.php'; ?>

<script>
<?php if (!empty($advanced_saved)) : ?>
if (typeof mementorTTSShowNotification === 'function') {
    mementorTTSShowNotification('<?php echo esc_js(__('Settings saved successfully.', 'text-to-speech-tts')); ?>', 'success');
}
<?php endif; ?>
jQuery(document).ready(function($) {
    // Export settings
    $('#mementor_tts_export_settings').on('click', function() {
        var $btn = $(this);
        $btn.prop('disabled', true).html('&darr; <?php echo esc_js(__('Exporting...', 'text-to-speech-tts')); ?>');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'mementor_tts_export_settings',
                nonce: '<?php echo esc_js(wp_create_nonce('mementor_tts_advanced_nonce')); ?>'
            },
            success: function(response) {
                $btn.prop('disabled', false).html('&darr; <?php echo esc_js(__('Export', 'text-to-speech-tts')); ?>');
                if (response.success) {
                    var blob = new Blob([response.data.data], { type: 'application/json' });
                    var url = URL.createObjectURL(blob);
                    var link = document.createElement('a');
                    link.href = url;
                    link.download = response.data.filename;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    URL.revokeObjectURL(url);
                } else {
                    alert(response.data.message || '<?php echo esc_js(__('Export failed.', 'text-to-speech-tts')); ?>');
                }
            },
            error: function() {
                $btn.prop('disabled', false).html('&darr; <?php echo esc_js(__('Export', 'text-to-speech-tts')); ?>');
                alert('<?php echo esc_js(__('Export request failed.', 'text-to-speech-tts')); ?>');
            }
        });
    });

    // Import settings - trigger file picker
    $('#mementor_tts_import_settings').on('click', function() {
        $('#mementor_tts_import_file').trigger('click');
    });

    // Import settings - handle file selection
    $('#mementor_tts_import_file').on('change', function() {
        var file = this.files[0];
        if (!file) return;

        if (!confirm('<?php echo esc_js(__('Are you sure you want to import settings? This will overwrite your current settings.', 'text-to-speech-tts')); ?>')) {
            $(this).val('');
            return;
        }

        var reader = new FileReader();
        reader.onload = function(e) {
            var $btn = $('#mementor_tts_import_settings');
            $btn.prop('disabled', true).html('&uarr; <?php echo esc_js(__('Importing...', 'text-to-speech-tts')); ?>');

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'mementor_tts_import_settings',
                    nonce: '<?php echo esc_js(wp_create_nonce('mementor_tts_advanced_nonce')); ?>',
                    settings_data: e.target.result
                },
                success: function(response) {
                    $btn.prop('disabled', false).html('&uarr; <?php echo esc_js(__('Import', 'text-to-speech-tts')); ?>');
                    if (response.success) {
                        alert(response.data);
                        location.reload();
                    } else {
                        alert(response.data || '<?php echo esc_js(__('Import failed.', 'text-to-speech-tts')); ?>');
                    }
                },
                error: function() {
                    $btn.prop('disabled', false).html('&uarr; <?php echo esc_js(__('Import', 'text-to-speech-tts')); ?>');
                    alert('<?php echo esc_js(__('Import request failed.', 'text-to-speech-tts')); ?>');
                }
            });
        };
        reader.readAsText(file);
        $(this).val('');
    });

    // Clear transients
    $('#mementor_tts_clear_transients').on('click', function() {
        var $btn = $(this);
        var $status = $('#mementor_tts_clear_transients_status');

        $btn.prop('disabled', true).text('<?php echo esc_js(__('Clearing...', 'text-to-speech-tts')); ?>');
        $status.hide();

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'mementor_tts_clear_transients',
                nonce: '<?php echo esc_js(wp_create_nonce('mementor_tts_nonce')); ?>'
            },
            success: function(response) {
                $btn.prop('disabled', false).text('<?php echo esc_js(__('Clear', 'text-to-speech-tts')); ?>');
                if (response.success) {
                    $status.text(response.data.message).css('color', '#0F6E56').show();
                } else {
                    $status.text(response.data.message || '<?php echo esc_js(__('Error clearing transients.', 'text-to-speech-tts')); ?>').css('color', '#dc2626').show();
                }
                setTimeout(function() { $status.fadeOut(); }, 4000);
            },
            error: function() {
                $btn.prop('disabled', false).text('<?php echo esc_js(__('Clear', 'text-to-speech-tts')); ?>');
                $status.text('<?php echo esc_js(__('Request failed.', 'text-to-speech-tts')); ?>').css('color', '#dc2626').show();
                setTimeout(function() { $status.fadeOut(); }, 4000);
            }
        });
    });
});
</script>
