<?php
/**
 * Admin settings page for managing logs and plugin settings.
 *
 * @package email-gated-downloads
 */

defined('ABSPATH') || exit;

// Register settings
add_action('admin_init', 'spdfed_register_settings');
/**
 * Register admin settings.
 */
function spdfed_register_settings() {
    register_setting(
        'spdfed_settings', 
        'spdfed_disable_styles',
        [
            'type'              => 'integer',
            'sanitize_callback' => 'absint',
            'default'           => 0,
        ]
    );
    
    // Free tier single file settings
    register_setting(
        'spdfed_free_file_settings',
        'spdfed_free_file_name',
        [
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default'           => '',
        ]
    );
    
    register_setting(
        'spdfed_free_file_settings',
        'spdfed_free_storage_filename',
        [
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default'           => '',
        ]
    );
    
    register_setting(
        'spdfed_free_file_settings',
        'spdfed_free_mime_type',
        [
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default'           => '',
        ]
    );
    
    register_setting(
        'spdfed_free_file_settings',
        'spdfed_free_enable_name_field',
        [
            'type'              => 'integer',
            'sanitize_callback' => 'absint',
            'default'           => 0,
        ]
    );
    
    register_setting(
        'spdfed_free_file_settings',
        'spdfed_free_name_field_required',
        [
            'type'              => 'integer',
            'sanitize_callback' => 'absint',
            'default'           => 0,
        ]
    );
    
    register_setting(
        'spdfed_free_file_settings',
        'spdfed_free_enable_gdpr',
        [
            'type'              => 'integer',
            'sanitize_callback' => 'absint',
            'default'           => 1,
        ]
    );
    
    register_setting(
        'spdfed_free_file_settings',
        'spdfed_free_gdpr_message',
        [
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_textarea_field',
            'default'           => __('I consent to my email being stored for the purposes of this download.', 'email-gated-downloads'),
        ]
    );
    
    // Note: Premium users can add additional premium-only global settings here if needed in the future
    // Example:
    // if (function_exists('sped_fs') && sped_fs()->can_use_premium_code__premium_only()) {
    //     register_setting('spdfed_premium_settings', 'spdfed_premium_only_option', [...]);
    // }
}

// Add admin menu
add_action('admin_menu', 'spdfed_admin_menu');

// Enqueue admin styles
add_action('admin_enqueue_scripts', 'spdfed_enqueue_admin_styles');
/**
 * Add admin menu page.
 */
function spdfed_admin_menu() {
    add_options_page(
        __('Email Gated Downloads Settings', 'email-gated-downloads'),
        __('Email Gated Downloads', 'email-gated-downloads'),
        'manage_options',
        'spdfed-settings',
        'spdfed_admin_page'
    );
}

/**
 * Enqueue admin styles for plugin pages.
 */
function spdfed_enqueue_admin_styles($hook) {
    // Only load on our plugin pages
    $plugin_pages = [
        'settings_page_spdfed-settings',                    // Settings page
        'spdfed_secure_file_page_spdfed-analytics',        // Analytics page
        'edit.php',                                         // CPT list page
        'post.php',                                         // CPT edit page
        'post-new.php'                                      // CPT add new page
    ];
    
    // Check if we're on a CPT page
    $screen = get_current_screen();
    $is_cpt_page = ($screen && $screen->post_type === 'spdfed_secure_file');
    
    // Load admin styles if we're on a plugin page or CPT page
    if (in_array($hook, $plugin_pages, true) || $is_cpt_page) {
        wp_enqueue_style(
            'spdfed-admin-styles',
            plugins_url('assets/css/admin.css', dirname(__FILE__)),
            [],
            '1.0.0'
        );
        
        // Enqueue jQuery for admin functionality
        wp_enqueue_script('jquery');
        
        // Add inline script for repair functionality (only on settings page)
        if ($hook === 'settings_page_spdfed-settings') {
            wp_add_inline_script('jquery', '
                jQuery(document).ready(function($) {
                    $("#repair-file-metadata").click(function() {
                        var button = $(this);
                        var resultsDiv = $("#repair-results");
                        
                        button.prop("disabled", true).text("Repairing...");
                        resultsDiv.html("<p>Processing...</p>");
                        
                        $.post(ajaxurl, {
                            action: "spdfed_repair_file_metadata",
                            nonce: "' . wp_create_nonce('spdfed_repair_files') . '"
                        }, function(response) {
                            if (response.success) {
                                var html = "<div style=\"padding: 10px; background: #d4edda; border: 1px solid #c3e6cb; color: #155724;\">";
                                html += "<h4>Repair Complete!</h4>";
                                html += "<p>Checked: " + response.data.total_checked + " files</p>";
                                html += "<p>Repaired: " + response.data.repaired.length + " files</p>";
                                
                                if (response.data.repaired.length > 0) {
                                    html += "<h5>Files that were repaired:</h5><ul>";
                                    response.data.repaired.forEach(function(file) {
                                        html += "<li>" + file.post_title + " (ID: " + file.post_id + ")</li>";
                                    });
                                    html += "</ul>";
                                }
                                html += "</div>";
                                resultsDiv.html(html);
                            } else {
                                resultsDiv.html("<div style=\"padding: 10px; background: #f8d7da; border: 1px solid #f5c6cb; color: #721c24;\">Error: " + response.data + "</div>");
                            }
                        }).fail(function() {
                            resultsDiv.html("<div style=\"padding: 10px; background: #f8d7da; border: 1px solid #f5c6cb; color: #721c24;\">AJAX request failed</div>");
                        }).always(function() {
                            button.prop("disabled", false).text("Repair File Metadata");
                        });
                    });
                });
            ');
        }
    }
}

// Render admin page
function spdfed_admin_page() {
    // Check if user has premium features
    $is_premium = function_exists('sped_fs') && sped_fs()->can_use_premium_code__premium_only();
    
    // Handle orphaned file cleanup
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if (isset($_POST['action']) && $_POST['action'] === 'spdfed_cleanup_orphaned' && current_user_can('manage_options')) {
        if (!isset($_POST['spdfed_cleanup_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['spdfed_cleanup_nonce'])), 'spdfed_cleanup_orphaned')) {
            add_settings_error('spdfed_settings', 'cleanup_nonce_failed', __('Security check failed.', 'email-gated-downloads'));
        } else {
            $cleanup_result = SPDFED_File_Manager::cleanup_orphaned_files();
            if (count($cleanup_result['deleted']) > 0) {
                add_settings_error('spdfed_settings', 'cleanup_success', 
                    /* translators: %d: number of deleted files */
                    sprintf(__('Successfully deleted %d orphaned files.', 'email-gated-downloads'), count($cleanup_result['deleted'])), 
                    'updated'
                );
            } elseif (count($cleanup_result['failed']) > 0) {
                add_settings_error('spdfed_settings', 'cleanup_partial', 
                    /* translators: %d: number of files that failed to delete */
                    sprintf(__('Failed to delete %d orphaned files.', 'email-gated-downloads'), count($cleanup_result['failed']))
                );
            } else {
                add_settings_error('spdfed_settings', 'cleanup_none', __('No orphaned files to clean up.', 'email-gated-downloads'), 'updated');
            }
        }
    }

    // Check for default post file removal notice
    $file_removed_post_id = get_option('spdfed_default_post_file_removed', 0);
    if ($file_removed_post_id && current_user_can('manage_options')) {
        $post_title = get_the_title($file_removed_post_id);
        echo '<div class="notice notice-warning is-dismissible">';
        echo '<p><strong>' . esc_html__('Default Shortcode File Removed', 'email-gated-downloads') . '</strong></p>';
        echo '<p>' . sprintf(
            /* translators: %s: name of the post/file that was removed */
            esc_html__('You removed the file from "%s" which is linked to your [pdf_download_form] shortcode. The shortcode will not work until you upload a new file to this post.', 'email-gated-downloads'),
            esc_html($post_title)
        ) . '</p>';
        echo '<p>';
        echo '<a href="' . esc_url(admin_url('post.php?post=' . $file_removed_post_id . '&action=edit')) . '" class="button button-primary">' . 
             esc_html__('Upload New File', 'email-gated-downloads') . '</a> ';
        echo '<a href="' . esc_url(add_query_arg('spdfed_clear_default_notice', '1')) . '" class="button button-secondary">' . 
             esc_html__('Dismiss Notice', 'email-gated-downloads') . '</a>';
        echo '</p>';
        echo '</div>';
    }
    
    // Handle notice dismissal
    if (isset($_GET['spdfed_clear_default_notice']) && current_user_can('manage_options')) {
        delete_option('spdfed_default_post_file_removed');
        wp_redirect(admin_url('options-general.php?page=spdfed-settings'));
        exit;
    }
    
    settings_errors('spdfed_settings');
    settings_errors('spdfed_free_file_settings');
    ?>
    <div class="wrap">
        <h1><?php esc_html_e('Email Gated Downloads Settings', 'email-gated-downloads'); ?></h1>
        
        <?php if (!$is_premium): ?>
            <!-- FREE VERSION CONTENT -->
            <?php spdfed_render_free_file_section(); ?>
            <hr>
        <?php else: ?>
            <!-- PREMIUM USER MIGRATION CONTENT -->
            <?php spdfed_render_premium_migration_section(); ?>
            
            <!-- PREMIUM GLOBAL SETTINGS -->
            <?php spdfed_render_premium_global_settings(); ?>
            <hr>
        <?php endif; ?>

        <form method="post" action="options.php"> 
            <?php settings_fields('spdfed_settings'); ?>

            <h2><?php esc_html_e('Styling', 'email-gated-downloads'); ?></h2>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row"><?php esc_html_e('Disable Plugin Stylesheet', 'email-gated-downloads'); ?></th>
                    <td>
                        <label for="spdfed_disable_styles">
                            <input type="checkbox" id="spdfed_disable_styles" name="spdfed_disable_styles" value="1" <?php checked(get_option('spdfed_disable_styles'), 1); ?> />
                            <?php esc_html_e('Check this box to prevent the default form styles from loading. This is useful if you want to style the form entirely within your theme.', 'email-gated-downloads'); ?>
                        </label>
                </tr>
            </table>
            <?php submit_button(esc_html__('Save Styling Settings', 'email-gated-downloads'), 'primary', 'submit_styling_settings'); ?>

            <details class="spdfed-help-panel">
                <summary><?php esc_html_e('How to customize form styles', 'email-gated-downloads'); ?></summary>
                <div class="spdfed-help-content">
                    <p><?php esc_html_e("You can easily change the form's appearance by overriding its CSS variables. Copy the example below into your theme's style.css file or the 'Additional CSS' section of the WordPress Customizer.", 'email-gated-downloads'); ?></p>
                    
                    <p><strong><?php esc_html_e('Example:', 'email-gated-downloads'); ?></strong></p>
                    <pre class="spdfed-code-example"><code>/* Custom Styles for PDF Form */
.spdfed-form-wrapper {
    --spdfed-button-bg-color: #e67e22;
    --spdfed-border-radius: 4px;
    --spdfed-text-color: #555;
}</code></pre>

                    <p><strong><?php esc_html_e('Available Variables:', 'email-gated-downloads'); ?></strong></p>
                    <ul class="spdfed-variable-list">
                        <li><code>--spdfed-max-width</code>: The maximum width of the form container.</li>
                        <li><code>--spdfed-margin</code>: The margin around the form container.</li>
                        <li><code>--spdfed-border-color</code>: The color of borders on the form and inputs.</li>
                        <li><code>--spdfed-border-radius</code>: The roundness of corners for the form, inputs, and button.</li>
                        <li><code>--spdfed-padding</code>: The main padding inside the form container.</li>
                        <li><code>--spdfed-input-padding</code>: The padding inside text inputs and the button.</li>
                        <li><code>--spdfed-text-color</code>: The main text color.</li>
                        <li><code>--spdfed-button-bg-color</code>: The background color of the submit button.</li>
                        <li><code>--spdfed-button-bg-color-hover</code>: The background color of the submit button on hover or focus.</li>
                        <li><code>--spdfed-button-text-color</code>: The text color of the submit button.</li>
                        <li><code>--spdfed-button-text-color-hover</code>: The text color of the submit button on hover or focus.</li>
                        <li><code>--spdfed-button-transition</code>: The CSS transition for the button's hover effects.</li>
                        <li><code>--spdfed-error-text-color</code>: The text color for error messages.</li>
                        <li><code>--spdfed-error-bg-color</code>: The background color for error messages.</li>
                    </ul>
                </div>
            </details>
        </form>

        <hr>
        <h2 id="spdfed-download-logs"><?php esc_html_e('Download Logs', 'email-gated-downloads'); ?></h2>
        <?php
        // Pagination for logs
        $per_page_logs = filter_input(INPUT_GET, 'spdfed_per_page_logs', FILTER_VALIDATE_INT, 
            ['options' => ['default' => 20, 'min_range' => 1, 'max_range' => 100]]);
        $paged_logs = filter_input(INPUT_GET, 'paged_logs', FILTER_VALIDATE_INT, 
            ['options' => ['default' => 1, 'min_range' => 1]]);

        // Filtering for logs.
        // Nonce is disabled for this GET request as it's only for filtering and not a state-changing operation.
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $filter_file_log = isset($_GET['spdfed_filter_file_log']) ? sanitize_text_field(wp_unslash($_GET['spdfed_filter_file_log'])) : '';


        // Get logs and counts using our new functions
        $log_results     = spdfed_get_logs($filter_file_log, $per_page_logs, $paged_logs);
        $total_rows_logs = spdfed_get_logs_count($filter_file_log);
        ?>
        <form method="get" class="spdfed-logs-filters">
            <input type="hidden" name="page" value="spdfed-settings">
            <select name="spdfed_filter_file_log">
                <option value=""><?php esc_html_e('All Files', 'email-gated-downloads'); ?></option>
                <?php
                $log_files = spdfed_get_distinct_log_files();
                foreach ($log_files as $lf) {
                    echo "<option value='" . esc_attr($lf) . "' " . selected($filter_file_log, $lf, false) . ">" . esc_html($lf) . "</option>";
                }
                ?>
            </select>
            <select name="spdfed_per_page_logs" onchange="this.form.submit();">
                <option value="20" <?php selected($per_page_logs, 20); ?>>20 <?php esc_html_e('per page', 'email-gated-downloads'); ?></option>
                <option value="50" <?php selected($per_page_logs, 50); ?>>50 <?php esc_html_e('per page', 'email-gated-downloads'); ?></option>
                <option value="100" <?php selected($per_page_logs, 100); ?>>100 <?php esc_html_e('per page', 'email-gated-downloads'); ?></option>
            </select>
            <button type="submit" class="button"><?php esc_html_e('Filter Logs', 'email-gated-downloads'); ?></button>
            
            <?php 
            // Nonce for export action, matching what export.php expects in $_GET['_wpnonce']
            wp_nonce_field('spdfed_export_nonce', '_wpnonce'); 
            ?>
            <button type="submit" name="spdfed_export" value="1" class="button button-primary"><?php esc_html_e('Export Logs as CSV', 'email-gated-downloads'); ?></button>
        </form>

        <table class="widefat striped">
            <thead>
                <tr>
                    <th><?php esc_html_e('Name', 'email-gated-downloads'); ?></th>
                    <th><?php esc_html_e('Email', 'email-gated-downloads'); ?></th>
                    <th><?php esc_html_e('File', 'email-gated-downloads'); ?></th>
                    <th><?php esc_html_e('Date', 'email-gated-downloads'); ?></th>
                </tr>
            </thead>
            <tbody>
            <?php
            if ($log_results) {
                foreach ($log_results as $row) {
                    echo '<tr>';
                    echo '<td>' . (isset($row->submitter_name) ? esc_html($row->submitter_name) : '-') . '</td>';
                    echo '<td>' . esc_html($row->email) . '</td>';
                    echo '<td>' . esc_html($row->file_name) . '</td>';
                    echo '<td>' . esc_html($row->downloaded_at) . '</td>';
                    echo '</tr>';
                }
            } else {
                echo '<tr><td colspan="4">' . esc_html__('No download logs found.', 'email-gated-downloads') . '</td></tr>';
            }
            ?>
            </tbody>
        </table>

        <?php
		// Pagination display for logs.
        $total_pages_logs = ceil( $total_rows_logs / $per_page_logs );

        if ($total_pages_logs > 1) {
            $pagination_links = paginate_links([
                'base'      => add_query_arg(
                    [
                        'paged_logs'             => '%#%',
                        'spdfed_filter_file_log' => $filter_file_log,
                        'spdfed_per_page_logs'   => $per_page_logs,
                    ]
                ) . '#spdfed-download-logs',
                'format'    => '',
                'prev_text' => __('&laquo;', 'email-gated-downloads'),
                'next_text' => __('&raquo;', 'email-gated-downloads'),
                'total'     => $total_pages_logs,
                'current'   => $paged_logs,
            ]);

            if ($pagination_links) {
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                echo '<div class="tablenav spdfed-logs-pagination"><div class="tablenav-pages">' . $pagination_links . '</div></div>';
            }
        }
        ?>
        
        <!-- File Management Section for Admins -->
        <?php if (current_user_can('manage_options')): ?>
        <hr>
        <h2><?php esc_html_e('File Management', 'email-gated-downloads'); ?></h2>
        <div class="spdfed-file-management">
            <table class="form-table">
                <tr>
                    <th scope="row"><?php esc_html_e('Orphaned Files', 'email-gated-downloads'); ?></th>
                    <td>
                        <?php
                        $orphaned_files = SPDFED_File_Manager::find_orphaned_files();
                        $orphaned_count = count($orphaned_files);
                        ?>
                        <p class="description">
                            <?php
                            if ($orphaned_count === 0) {
                                echo '<span class="spdfed-text-success">' . esc_html__('No orphaned files found.', 'email-gated-downloads') . '</span>';
                            } else {
                                printf(
                                    '<span class="spdfed-text-warning">' . 
                                    /* translators: %d: number of orphaned files found */
                                    esc_html(_n('%d orphaned file found', '%d orphaned files found', $orphaned_count, 'email-gated-downloads')) . 
                                    '</span>',
                                    absint($orphaned_count)
                                );
                            }
                            ?>
                        </p>
                        <?php if ($orphaned_count > 0): ?>
                            <details style="margin-top: 10px;">
                                <summary><?php esc_html_e('Show orphaned files', 'email-gated-downloads'); ?></summary>
                                <ul style="margin: 10px 0; padding-left: 20px;">
                                    <?php foreach ($orphaned_files as $filename): ?>
                                        <li><code><?php echo esc_html($filename); ?></code></li>
                                    <?php endforeach; ?>
                                </ul>
                            </details>
                            <form method="post" style="margin-top: 10px;">
                                <?php wp_nonce_field('spdfed_cleanup_orphaned', 'spdfed_cleanup_nonce'); ?>
                                <input type="hidden" name="action" value="spdfed_cleanup_orphaned">
                                <button type="submit" class="button button-secondary" onclick="return confirm('<?php esc_attr_e('Are you sure you want to delete all orphaned files? This action cannot be undone.', 'email-gated-downloads'); ?>')">
                                    <?php esc_html_e('Clean Up Orphaned Files', 'email-gated-downloads'); ?>
                                </button>
                            </form>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php /* File Statistics section hidden */ /*
                <tr>
                    <th scope="row"><?php esc_html_e('File Statistics', 'email-gated-downloads'); ?></th>
                    <td>
                        <?php
                        $free_file = SPDFED_File_Manager::get_free_file_info();
                        
                        // Get CPT files count with caching
                        $cache_key = 'spdfed_cpt_files_count';
                        $cpt_files_count = wp_cache_get($cache_key);
                        
                        if (false === $cpt_files_count) {
                            global $wpdb;
                            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
                            $cpt_files_count = $wpdb->get_var(
                                $wpdb->prepare(
                                    "SELECT COUNT(*) FROM {$wpdb->postmeta} 
                                     WHERE meta_key = %s 
                                     AND meta_value != %s",
                                    '_spdfed_storage_filename',
                                    ''
                                )
                            );
                            wp_cache_set($cache_key, $cpt_files_count, '', 300); // Cache for 5 minutes
                        }
                        ?>
                        <p>
                            <strong><?php esc_html_e('Free tier file:', 'email-gated-downloads'); ?></strong>
                            <?php if ($free_file): ?>
                                <span class="spdfed-text-success">
                                    <?php echo esc_html($free_file['original_filename']); ?>
                                    <?php if (!$free_file['exists']): ?>
                                        <span class="spdfed-text-error"> (<?php esc_html_e('missing from disk', 'email-gated-downloads'); ?>)</span>
                                    <?php endif; ?>
                                </span>
                            <?php else: ?>
                                <span class="spdfed-text-muted"><?php esc_html_e('None', 'email-gated-downloads'); ?></span>
                            <?php endif; ?>
                        </p>
                        <p>
                            <strong><?php esc_html_e('Premium CPT files:', 'email-gated-downloads'); ?></strong>
                            <span><?php 
                            /* translators: %d: number of files */
                            printf(esc_html__('%d files', 'email-gated-downloads'), absint($cpt_files_count)); ?></span>
                        </p>
                        <?php 
                        $default_post_id = absint(get_option('spdfed_premium_default_post_id', 0));
                        if ($default_post_id):
                            $default_post_title = get_the_title($default_post_id);
                            $default_post_file = get_post_meta($default_post_id, '_spdfed_file_name', true);
                        ?>
                        <p>
                            <strong><?php esc_html_e('Default for [pdf_download_form]:', 'email-gated-downloads'); ?></strong>
                            <?php if ($default_post_file): ?>
                                <span class="spdfed-text-success">
                                    <a href="<?php echo esc_url(admin_url('post.php?post=' . $default_post_id . '&action=edit')); ?>">
                                        <?php echo esc_html($default_post_title); ?>
                                    </a>
                                </span>
                            <?php else: ?>
                                <span class="spdfed-text-warning">
                                    <a href="<?php echo esc_url(admin_url('post.php?post=' . $default_post_id . '&action=edit')); ?>">
                                        <?php echo esc_html($default_post_title); ?>
                                    </a>
                                    (<?php esc_html_e('no file uploaded', 'email-gated-downloads'); ?>)
                                </span>
                            <?php endif; ?>
                        </p>
                        <?php endif; ?>
                        
                        <!-- File Metadata Repair Tool -->
                        <div style="margin-top: 20px; padding: 15px; background: #f9f9f9; border: 1px solid #ddd;">
                            <h4><?php esc_html_e('File Metadata Repair', 'email-gated-downloads'); ?></h4>
                            <p style="margin: 10px 0;"><?php esc_html_e('If you have existing files that are showing UUID names instead of original names, use this repair tool.', 'email-gated-downloads'); ?></p>
                            <button type="button" id="repair-file-metadata" class="button">
                                <?php esc_html_e('Repair File Metadata', 'email-gated-downloads'); ?>
                                </button>
                            <div id="repair-results" style="margin-top: 10px;"></div>
                        </div>
                        
                    </td>
                </tr>
            </table>
        </div>
        <?php endif; ?>
        
        <!-- JavaScript for dismissible notices and smooth scrolling -->
        <script type="text/javascript">
        jQuery(document).ready(function($) {
            // Dismissible notices
            $('.notice.is-dismissible[data-dismiss-option]').on('click', '.notice-dismiss', function(e) {
                e.preventDefault();
                var $notice = $(this).closest('.notice');
                var dismissOption = $notice.data('dismiss-option');
                
                if (dismissOption) {
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'spdfed_dismiss_notice',
                            option: dismissOption,
                            nonce: '<?php echo esc_attr(wp_create_nonce('spdfed_dismiss_notice')); ?>'
                        },
                        success: function() {
                            $notice.fadeOut();
                        }
                    });
                }
            });
            
            // Smooth scroll to logs section if hash is present
            if (window.location.hash === '#spdfed-download-logs') {
                setTimeout(function() {
                    $('html, body').animate({
                        scrollTop: $('#spdfed-download-logs').offset().top - 50
                    }, 500);
                }, 100);
            }
            
            // Add smooth scrolling to pagination links
            $('.spdfed-logs-pagination a').on('click', function(e) {
                // Let the normal navigation happen, but store that we want to scroll
                sessionStorage.setItem('spdfed_scroll_to_logs', 'true');
            });
            
            // Check if we need to scroll after page load (from pagination)
            if (sessionStorage.getItem('spdfed_scroll_to_logs') === 'true') {
                sessionStorage.removeItem('spdfed_scroll_to_logs');
                setTimeout(function() {
                    $('html, body').animate({
                        scrollTop: $('#spdfed-download-logs').offset().top - 50
                    }, 500);
                }, 100);
            }
        });
        </script>
    </div> 
    <?php
}

/**
 * Render the free file upload section for non-premium users.
 */
function spdfed_render_free_file_section() {
    $current_file = get_option('spdfed_free_file_name');
    $enable_name_field = get_option('spdfed_free_enable_name_field');
    $name_field_required = get_option('spdfed_free_name_field_required');
    $enable_gdpr = get_option('spdfed_free_enable_gdpr', 1);
    $gdpr_message = get_option('spdfed_free_gdpr_message', __('I consent to my email being stored for the purposes of this download.', 'email-gated-downloads'));
    ?>
    <div class="spdfed-free-tier-notice">
        <h2><?php esc_html_e('Your Download File', 'email-gated-downloads'); ?></h2>
        <div class="notice notice-info inline">
            <p>
                <?php esc_html_e('Free version: Upload one PDF or ZIP file for secure download.', 'email-gated-downloads'); ?>
                <?php if (function_exists('sped_fs')): ?>
                    <a href="<?php echo esc_url(sped_fs()->get_upgrade_url()); ?>" class="button button-primary" style="margin-left: 10px;">
                        <?php esc_html_e('Upgrade for Unlimited Downloads', 'email-gated-downloads'); ?>
                    </a>
                <?php endif; ?>
            </p>
        </div>
        
        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" enctype="multipart/form-data">
            <?php wp_nonce_field('spdfed_free_file_upload', 'spdfed_free_file_nonce'); ?>
            <input type="hidden" name="action" value="spdfed_handle_free_file_upload">
            
            <table class="form-table">
                <tr valign="top">
                    <th scope="row"><?php esc_html_e('Upload PDF or ZIP File', 'email-gated-downloads'); ?></th>
                    <td>
                        <input type="file" name="spdfed_free_file" accept=".pdf,.zip">
                        <?php if ($current_file): ?>
                            <p><strong><?php esc_html_e('Current file:', 'email-gated-downloads'); ?></strong> <?php echo esc_html($current_file); ?></p>
                            <label>
                                <input type="checkbox" name="spdfed_remove_free_file" value="1">
                                <?php esc_html_e('Remove current file', 'email-gated-downloads'); ?>
                            </label>
                        <?php else: ?>
                            <p class="description"><?php esc_html_e('No file uploaded yet.', 'email-gated-downloads'); ?></p>
                        <?php endif; ?>
                    </td>
                </tr>
            </table>
            
            <h3><?php esc_html_e('Form Settings', 'email-gated-downloads'); ?></h3>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row"><?php esc_html_e('Enable Full Name Field', 'email-gated-downloads'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="spdfed_free_enable_name_field" value="1" <?php checked($enable_name_field, 1); ?> />
                            <?php esc_html_e('Add a "Full Name" field to the download form.', 'email-gated-downloads'); ?>
                        </label>
                    </td>
                </tr>
                <tr valign="top" id="spdfed_free_name_field_required_row" class="<?php echo $enable_name_field ? '' : 'spdfed-hidden'; ?>">
                    <th scope="row"><?php esc_html_e('Make Full Name Field Required', 'email-gated-downloads'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="spdfed_free_name_field_required" value="1" <?php checked($name_field_required, 1); ?> />
                            <?php esc_html_e('If checked, the full name field will be mandatory.', 'email-gated-downloads'); ?>
                        </label>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row"><?php esc_html_e('Enable GDPR Consent Box', 'email-gated-downloads'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="spdfed_free_enable_gdpr" value="1" <?php checked($enable_gdpr, 1); ?> />
                            <?php esc_html_e('Show a GDPR consent checkbox on the form.', 'email-gated-downloads'); ?>
                        </label>
                    </td>
                </tr>
                <tr valign="top" id="spdfed_free_gdpr_message_row" class="<?php echo $enable_gdpr ? '' : 'spdfed-hidden'; ?>">
                    <th scope="row">
                        <label for="spdfed_free_gdpr_message"><?php esc_html_e('GDPR Message', 'email-gated-downloads'); ?></label>
                    </th>
                    <td>
                        <textarea name="spdfed_free_gdpr_message" id="spdfed_free_gdpr_message" rows="3" class="widefat"><?php echo esc_textarea($gdpr_message); ?></textarea>
                    </td>
                </tr>
            </table>
            
            <?php submit_button(__('Save File & Settings', 'email-gated-downloads'), 'primary'); ?>
        </form>
        
        <?php if ($current_file): ?>
            <div class="spdfed-shortcode-section">
                <h3><?php esc_html_e('Your Shortcode', 'email-gated-downloads'); ?></h3>
                <p><?php esc_html_e('Use the following shortcode to display the download form on your posts or pages:', 'email-gated-downloads'); ?></p>
                <div class="spdfed-shortcode-container">
                    <div class="spdfed-shortcode-input-wrapper">
                        <input type="text" id="spdfed-free-shortcode-text" value="[pdf_download_form]" readonly class="spdfed-shortcode-input">
                        <button type="button" class="button button-primary spdfed-copy-button" data-clipboard-target="#spdfed-free-shortcode-text">
                            <span class="dashicons dashicons-clipboard"></span>
                            <?php esc_html_e('Copy', 'email-gated-downloads'); ?>
                        </button>
                    </div>
                    <p class="spdfed-copy-feedback" style="font-size: 0.9em; color: #46b450; margin-top: 5px; height: 1.2em; font-weight: 500;"></p>
                </div>
                <div class="spdfed-shortcode-examples">
                    <p><strong><?php esc_html_e('Examples:', 'email-gated-downloads'); ?></strong></p>
                    <div class="spdfed-example-codes">
                        <div class="spdfed-example">
                            <code>[pdf_download_form]</code>
                            <span class="spdfed-example-desc"><?php esc_html_e('Default button text', 'email-gated-downloads'); ?></span>
                        </div>
                        <div class="spdfed-example">
                            <code>[pdf_download_form label="Get Your Free Guide"]</code>
                            <span class="spdfed-example-desc"><?php esc_html_e('Custom button text', 'email-gated-downloads'); ?></span>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
        
        <style>
            .spdfed-hidden { display: none; }
            
            /* Shortcode Section Styling */
            .spdfed-shortcode-section {
                background: #f8f9fa;
                border: 1px solid #e1e1e1;
                border-radius: 6px;
                padding: 20px;
                margin-top: 20px;
            }
            
            .spdfed-shortcode-section h3 {
                margin-top: 0;
                color: #0073aa;
                font-size: 1.1em;
            }
            
            .spdfed-shortcode-container {
                margin: 15px 0;
            }
            
            .spdfed-shortcode-input-wrapper {
                display: flex;
                gap: 8px;
                align-items: center;
                margin-bottom: 5px;
            }
            
            .spdfed-shortcode-input {
                flex-grow: 1;
                padding: 8px 12px;
                font-family: Consolas, Monaco, monospace;
                font-size: 14px;
                background: #fff;
                border: 1px solid #ddd;
                border-radius: 4px;
                color: #0073aa;
                font-weight: 500;
            }
            
            .spdfed-copy-button {
                display: flex;
                align-items: center;
                gap: 5px;
                white-space: nowrap;
            }
            
            .spdfed-copy-button .dashicons {
                font-size: 16px;
                width: 16px;
                height: 16px;
            }
            
            .spdfed-shortcode-examples {
                background: #fff;
                border: 1px solid #e1e1e1;
                border-radius: 4px;
                padding: 15px;
                margin-top: 15px;
            }
            
            .spdfed-example-codes {
                margin-top: 10px;
            }
            
            .spdfed-example {
                display: flex;
                align-items: center;
                gap: 15px;
                margin-bottom: 8px;
                padding: 5px 0;
            }
            
            .spdfed-example code {
                background: #f1f1f1;
                padding: 4px 8px;
                border-radius: 3px;
                font-family: Consolas, Monaco, monospace;
                color: #0073aa;
                min-width: 200px;
            }
            
            .spdfed-example-desc {
                color: #666;
                font-style: italic;
                font-size: 0.9em;
            }
        </style>
        <script>
            jQuery(document).ready(function($) {
                function toggleNameRequiredOption() {
                    $('#spdfed_free_name_field_required_row').toggleClass('spdfed-hidden', !$('input[name="spdfed_free_enable_name_field"]').is(':checked'));
                }
                function toggleGdprMessageOption() {
                    $('#spdfed_free_gdpr_message_row').toggleClass('spdfed-hidden', !$('input[name="spdfed_free_enable_gdpr"]').is(':checked'));
                }
                $('input[name="spdfed_free_enable_name_field"]').on('change', toggleNameRequiredOption);
                $('input[name="spdfed_free_enable_gdpr"]').on('change', toggleGdprMessageOption);
                toggleNameRequiredOption();
                toggleGdprMessageOption();
                
                // Copy shortcode functionality
                $(document).on('click', '.spdfed-copy-button', function(e) {
                    e.preventDefault();
                    
                    const button = $(this);
                    const targetSelector = button.data('clipboard-target');
                    const textToCopy = $(targetSelector);
                    const feedbackElement = button.closest('.spdfed-shortcode-input-wrapper').next('.spdfed-copy-feedback');
                    
                    if (textToCopy.length) {
                        textToCopy.select();
                        textToCopy[0].setSelectionRange(0, 99999); // For mobile devices

                        try {
                            const successful = document.execCommand('copy');
                            if (feedbackElement.length) {
                                feedbackElement.text(successful ? 'Shortcode copied to clipboard!' : 'Copy failed.');
                            }
                        } catch (err) {
                            if (feedbackElement.length) {
                                feedbackElement.text('Oops, unable to copy.');
                            }
                        }

                        // Clear the feedback message after 3 seconds
                        if (feedbackElement.length) {
                            setTimeout(function() {
                                feedbackElement.text('');
                            }, 3000);
                        }

                        // Deselect the text
                        window.getSelection().removeAllRanges();
                    }
                });
            });
        </script>
    </div>
    <?php
}

/**
 * Render premium global settings section.
 * Premium users use the same global settings as free users, but with better labeling.
 * These can be overridden on a per-file basis in the CPT.
 */
function spdfed_render_premium_global_settings() {
    // Reuse the free settings as global defaults
    $enable_name_field = get_option('spdfed_free_enable_name_field', 0);
    $name_field_required = get_option('spdfed_free_name_field_required', 0);
    $enable_gdpr = get_option('spdfed_free_enable_gdpr', 1);
    $gdpr_message = get_option('spdfed_free_gdpr_message', __('I consent to my email being stored for the purposes of this download.', 'email-gated-downloads'));
    ?>
    <div class="spdfed-premium-global-settings">
        <h2><?php esc_html_e('Global Form Settings', 'email-gated-downloads'); ?></h2>
        <div class="notice notice-info inline">
            <p>
                <strong><?php esc_html_e('Default Settings:', 'email-gated-downloads'); ?></strong>
                <?php esc_html_e('These are the default form settings for all your secure downloads. You can override them on individual files if needed.', 'email-gated-downloads'); ?>
            </p>
        </div>
        
        <form method="post" action="options.php">
            <?php settings_fields('spdfed_free_file_settings'); ?>
            
            <table class="form-table">
                <tr valign="top">
                    <th scope="row"><?php esc_html_e('Enable Full Name Field', 'email-gated-downloads'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" id="spdfed_free_enable_name_field" name="spdfed_free_enable_name_field" value="1" <?php checked($enable_name_field, 1); ?> />
                            <?php esc_html_e('Add a "Full Name" field to the download form by default.', 'email-gated-downloads'); ?>
                        </label>
                    </td>
                </tr>
                <tr valign="top" id="spdfed_free_name_field_required_row" class="<?php echo $enable_name_field ? '' : 'spdfed-hidden'; ?>">
                    <th scope="row"><?php esc_html_e('Make Full Name Field Required', 'email-gated-downloads'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="spdfed_free_name_field_required" value="1" <?php checked($name_field_required, 1); ?> />
                            <?php esc_html_e('If checked, the full name field will be mandatory by default.', 'email-gated-downloads'); ?>
                        </label>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row"><?php esc_html_e('Enable GDPR Consent Box', 'email-gated-downloads'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" id="spdfed_free_enable_gdpr" name="spdfed_free_enable_gdpr" value="1" <?php checked($enable_gdpr, 1); ?> />
                            <?php esc_html_e('Show a GDPR consent checkbox on the form by default.', 'email-gated-downloads'); ?>
                        </label>
                    </td>
                </tr>
                <tr valign="top" id="spdfed_free_gdpr_message_row" class="<?php echo $enable_gdpr ? '' : 'spdfed-hidden'; ?>">
                    <th scope="row">
                        <label for="spdfed_free_gdpr_message"><?php esc_html_e('GDPR Message', 'email-gated-downloads'); ?></label>
                    </th>
                    <td>
                        <textarea name="spdfed_free_gdpr_message" id="spdfed_free_gdpr_message" rows="3" class="widefat"><?php echo esc_textarea($gdpr_message); ?></textarea>
                        <p class="description"><?php esc_html_e('This message will be displayed next to the GDPR consent checkbox by default.', 'email-gated-downloads'); ?></p>
                    </td>
                </tr>
            </table>
            
            <?php submit_button(__('Save Global Settings', 'email-gated-downloads'), 'primary'); ?>
        </form>
        
        <script type="text/javascript">
            jQuery(document).ready(function($) {
                function toggleNameRequiredOption() {
                    $('#spdfed_free_name_field_required_row').toggleClass('spdfed-hidden', !$('#spdfed_free_enable_name_field').is(':checked'));
                }
                function toggleGdprMessageOption() {
                    $('#spdfed_free_gdpr_message_row').toggleClass('spdfed-hidden', !$('#spdfed_free_enable_gdpr').is(':checked'));
                }
                $('#spdfed_free_enable_name_field').on('change', toggleNameRequiredOption);
                $('#spdfed_free_enable_gdpr').on('change', toggleGdprMessageOption);
                toggleNameRequiredOption();
                toggleGdprMessageOption();
            });
        </script>
    </div>
    <?php
}

// Handle free file upload
add_action('admin_post_spdfed_handle_free_file_upload', 'spdfed_handle_free_file_upload');
/**
 * Handle file upload for free tier users.
 */
function spdfed_handle_free_file_upload() {
    // Check nonce
    if (!isset($_POST['spdfed_free_file_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['spdfed_free_file_nonce'])), 'spdfed_free_file_upload')) {
        wp_die(esc_html__('Security check failed.', 'email-gated-downloads'));
    }
    
    // Check user permissions
    if (!current_user_can('manage_options')) {
        wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'email-gated-downloads'));
    }
    
    $private_dir = WP_CONTENT_DIR . '/private-uploads/';
    
    // Handle file removal
    if (!empty($_POST['spdfed_remove_free_file'])) {
        SPDFED_File_Manager::delete_free_file();
        add_settings_error('spdfed_free_file_settings', 'file_removed', __('File removed successfully.', 'email-gated-downloads'), 'updated');
    }
    
    // Handle file upload
    $file_upload = null;
    if (isset($_FILES['spdfed_free_file']) && is_array($_FILES['spdfed_free_file'])) {
        // Sanitize file upload data
        $file_upload = [
            'name'     => isset($_FILES['spdfed_free_file']['name']) ? sanitize_file_name($_FILES['spdfed_free_file']['name']) : '',
            'type'     => isset($_FILES['spdfed_free_file']['type']) ? sanitize_text_field($_FILES['spdfed_free_file']['type']) : '',
            'tmp_name' => isset($_FILES['spdfed_free_file']['tmp_name']) ? sanitize_text_field($_FILES['spdfed_free_file']['tmp_name']) : '',
            'error'    => isset($_FILES['spdfed_free_file']['error']) ? (int) $_FILES['spdfed_free_file']['error'] : UPLOAD_ERR_NO_FILE,
            'size'     => isset($_FILES['spdfed_free_file']['size']) ? (int) $_FILES['spdfed_free_file']['size'] : 0,
        ];
    }
    
    if ($file_upload && isset($file_upload['error']) && UPLOAD_ERR_OK === $file_upload['error']) {
        // Use centralized file manager
        $result = SPDFED_File_Manager::upload_free_file($file_upload);
        
        if ($result['success']) {
            add_settings_error('spdfed_free_file_settings', 'file_uploaded', $result['message'], 'updated');
        } else {
            add_settings_error('spdfed_free_file_settings', 'file_upload_error', $result['message']);
        }
    } elseif ($file_upload && isset($file_upload['error']) && UPLOAD_ERR_NO_FILE !== $file_upload['error']) {
        $error_message = SPDFED_File_Manager::get_upload_error_message((int) $file_upload['error']);
        /* translators: %s: error message describing the file upload problem */
        add_settings_error('spdfed_free_file_settings', 'file_upload_error', sprintf(__('File upload error: %s', 'email-gated-downloads'), $error_message));
    }
    
    // Save form settings
    update_option('spdfed_free_enable_name_field', isset($_POST['spdfed_free_enable_name_field']) ? 1 : 0);
    update_option('spdfed_free_name_field_required', isset($_POST['spdfed_free_name_field_required']) ? 1 : 0);
    update_option('spdfed_free_enable_gdpr', isset($_POST['spdfed_free_enable_gdpr']) ? 1 : 0);
    
    if (isset($_POST['spdfed_free_gdpr_message'])) {
        update_option('spdfed_free_gdpr_message', sanitize_textarea_field(wp_unslash($_POST['spdfed_free_gdpr_message'])));
    }
    
    // Redirect back to settings page
    wp_redirect(admin_url('options-general.php?page=spdfed-settings'));
    exit;
}

/**
 * Render the premium user migration section.
 * Shows migration options for users who upgraded from free to premium.
 */
function spdfed_render_premium_migration_section() {
    $free_file = get_option('spdfed_free_storage_filename');
    $free_file_name = get_option('spdfed_free_file_name');
    $has_migrated = get_option('spdfed_has_migrated', false);
    
    if (!$free_file && !$has_migrated && !get_option('spdfed_premium_welcome_dismissed', false)) {
        // No free file configured, hasn't migrated, and hasn't dismissed = brand new premium user, show welcome message
        ?>
        <div class="spdfed-premium-welcome">
            <h2><?php esc_html_e('Welcome to Secure PDF Premium!', 'email-gated-downloads'); ?></h2>
            <div class="notice notice-success inline is-dismissible" data-dismiss-option="spdfed_premium_welcome_dismissed">
                <p>
                    <strong><?php esc_html_e('You\'re now premium!', 'email-gated-downloads'); ?></strong>
                    <?php esc_html_e('You can now create unlimited secure downloads using the "Secure Files" menu in your admin.', 'email-gated-downloads'); ?>
                </p>
                <p>
                    <a href="<?php echo esc_url(admin_url('edit.php?post_type=spdfed_secure_file')); ?>" class="button button-primary">
                        <?php esc_html_e('Create Your First Secure Download', 'email-gated-downloads'); ?>
                    </a>
                    <a href="<?php echo esc_url(admin_url('post-new.php?post_type=spdfed_secure_file')); ?>" class="button button-secondary">
                        <?php esc_html_e('Add New Secure File', 'email-gated-downloads'); ?>
                    </a>
                </p>
            </div>
        </div>
        <hr>
        <?php
    } elseif (!$free_file && $has_migrated) {
        // User has already migrated, show minimal post-migration message
        ?>
        <div class="spdfed-post-migration">
            <div class="notice notice-success inline">
                <p>
                    <strong><?php esc_html_e('Migration Complete!', 'email-gated-downloads'); ?></strong>
                    <?php esc_html_e('Your file has been successfully migrated to the CPT system.', 'email-gated-downloads'); ?>
                    <a href="<?php echo esc_url(admin_url('edit.php?post_type=spdfed_secure_file')); ?>"><?php esc_html_e('Manage your secure files', 'email-gated-downloads'); ?></a>
                    <?php esc_html_e('or', 'email-gated-downloads'); ?>
                    <a href="<?php echo esc_url(admin_url('post-new.php?post_type=spdfed_secure_file')); ?>"><?php esc_html_e('add a new one', 'email-gated-downloads'); ?></a>.
                </p>
            </div>
        </div>
        <hr>
        <?php
    } else {
        // User has a free file configured, offer migration
        ?>
        <div class="spdfed-migration-section">
            <h2><?php esc_html_e('Free File Migration', 'email-gated-downloads'); ?></h2>
            <div class="notice notice-info inline">
                <p>
                    <strong><?php esc_html_e('You have a file from the free version:', 'email-gated-downloads'); ?></strong>
                    <?php echo esc_html($free_file_name); ?>
                </p>
                <p><?php esc_html_e('As a premium user, you can now create unlimited secure downloads. Choose what to do with your existing file:', 'email-gated-downloads'); ?></p>
            </div>
            
            <div class="spdfed-migration-options">
                <div class="migration-option">
                    <h3><?php esc_html_e('Option 1: Migrate to CPT (Recommended)', 'email-gated-downloads'); ?></h3>
                    <p><?php esc_html_e('Convert your free file into a proper secure download CPT. This gives you more control and allows you to create additional downloads.', 'email-gated-downloads'); ?></p>
                    <p><strong><?php esc_html_e('Note:', 'email-gated-downloads'); ?></strong> <?php esc_html_e('Your existing [pdf_download_form] shortcodes will continue to work without modification!', 'email-gated-downloads'); ?></p>
                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                        <?php wp_nonce_field('spdfed_migrate_free_file', 'spdfed_migrate_nonce'); ?>
                        <input type="hidden" name="action" value="spdfed_migrate_free_to_cpt">
                        <button type="submit" class="button button-primary">
                            <?php esc_html_e('Migrate File to CPT', 'email-gated-downloads'); ?>
                        </button>
                    </form>
                </div>
                
                <div class="migration-option">
                    <h3><?php esc_html_e('Option 2: Keep Free File', 'email-gated-downloads'); ?></h3>
                    <p><?php esc_html_e('Keep using your existing file with [pdf_download_form] shortcode (no ID needed). You can still create additional downloads via CPT.', 'email-gated-downloads'); ?></p>
                    <p><strong><?php esc_html_e('Current shortcode:', 'email-gated-downloads'); ?></strong> <code>[pdf_download_form]</code></p>
                </div>
                
                <div class="migration-option">
                    <h3><?php esc_html_e('Option 3: Remove Free File', 'email-gated-downloads'); ?></h3>
                    <p><?php esc_html_e('Delete your free file and start fresh with CPT-based downloads only.', 'email-gated-downloads'); ?></p>
                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                        <?php wp_nonce_field('spdfed_remove_free_file', 'spdfed_remove_nonce'); ?>
                        <input type="hidden" name="action" value="spdfed_remove_free_file">
                        <button type="submit" class="button button-secondary" onclick="return confirm('<?php esc_attr_e('Are you sure you want to delete your free file? This action cannot be undone.', 'email-gated-downloads'); ?>')">
                            <?php esc_html_e('Remove Free File', 'email-gated-downloads'); ?>
                        </button>
                    </form>
                </div>
            </div>
            
        </div>
        <hr>
        <?php
    }
}

// Handle migration actions
add_action('admin_post_spdfed_migrate_free_to_cpt', 'spdfed_handle_migrate_free_to_cpt');
add_action('admin_post_spdfed_remove_free_file', 'spdfed_handle_remove_free_file');

/**
 * Handle migration of free file to CPT.
 */
function spdfed_handle_migrate_free_to_cpt() {
    global $wpdb;
    
    // Check nonce
    if (!isset($_POST['spdfed_migrate_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['spdfed_migrate_nonce'])), 'spdfed_migrate_free_file')) {
        wp_die(esc_html__('Security check failed.', 'email-gated-downloads'));
    }
    
    // Check permissions
    if (!current_user_can('manage_options')) {
        wp_die(esc_html__('You do not have sufficient permissions.', 'email-gated-downloads'));
    }
    
    // Get free file data
    $storage_filename = get_option('spdfed_free_storage_filename');
    $file_name = get_option('spdfed_free_file_name');
    $mime_type = get_option('spdfed_free_mime_type');
    $enable_name_field = get_option('spdfed_free_enable_name_field');
    $name_field_required = get_option('spdfed_free_name_field_required');
    $enable_gdpr = get_option('spdfed_free_enable_gdpr', 1);
    $gdpr_message = get_option('spdfed_free_gdpr_message', __('I consent to my email being stored for the purposes of this download.', 'email-gated-downloads'));
    
    if (!$storage_filename || !$file_name) {
        add_settings_error('spdfed_settings', 'migration_error', __('No free file found to migrate.', 'email-gated-downloads'));
        wp_redirect(admin_url('options-general.php?page=spdfed-settings'));
        exit;
    }
    
    // Create new CPT post
    $post_data = [
        'post_title'   => sanitize_text_field($file_name),
        'post_type'    => 'spdfed_secure_file',
        'post_status'  => 'publish',
        'post_content' => __('Migrated from free version', 'email-gated-downloads'),
    ];
    
    $post_id = wp_insert_post($post_data);
    
    if (is_wp_error($post_id)) {
        add_settings_error('spdfed_settings', 'migration_error', __('Failed to create CPT post.', 'email-gated-downloads'));
        wp_redirect(admin_url('options-general.php?page=spdfed-settings'));
        exit;
    }
    
    // Copy file data to post meta
    update_post_meta($post_id, '_spdfed_storage_filename', $storage_filename);
    update_post_meta($post_id, '_spdfed_file_name', $file_name);
    update_post_meta($post_id, '_spdfed_original_file_name', $file_name);
    update_post_meta($post_id, '_spdfed_mime_type', $mime_type);
    update_post_meta($post_id, '_spdfed_enable_name_field', $enable_name_field ? '1' : '0');
    update_post_meta($post_id, '_spdfed_name_field_required', $name_field_required ? '1' : '0');
    update_post_meta($post_id, '_spdfed_enable_gdpr', $enable_gdpr ? '1' : '0');
    update_post_meta($post_id, '_spdfed_gdpr_message', $gdpr_message);
    
    // Store the migrated post ID as default for premium users using [pdf_download_form] without ID
    update_option('spdfed_premium_default_post_id', $post_id);
    
    // Mark that user has completed migration (prevents showing welcome message)
    update_option('spdfed_has_migrated', true);
    
    // Remove free file settings
    delete_option('spdfed_free_storage_filename');
    delete_option('spdfed_free_file_name');
    delete_option('spdfed_free_mime_type');
    delete_option('spdfed_free_enable_name_field');
    delete_option('spdfed_free_name_field_required');
    delete_option('spdfed_free_enable_gdpr');
    delete_option('spdfed_free_gdpr_message');
    
    // Redirect to edit the new post
    wp_redirect(admin_url('post.php?post=' . $post_id . '&action=edit&message=1'));
    exit;
}

/**
 * Handle removal of free file.
 */
function spdfed_handle_remove_free_file() {
    // Check nonce
    if (!isset($_POST['spdfed_remove_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['spdfed_remove_nonce'])), 'spdfed_remove_free_file')) {
        wp_die(esc_html__('Security check failed.', 'email-gated-downloads'));
    }
    
    // Check permissions
    if (!current_user_can('manage_options')) {
        wp_die(esc_html__('You do not have sufficient permissions.', 'email-gated-downloads'));
    }
    
    // Delete physical file
    $storage_filename = get_option('spdfed_free_storage_filename');
    if ($storage_filename) {
        $private_dir = WP_CONTENT_DIR . '/private-uploads/';
        $file_path = $private_dir . $storage_filename;
        if (file_exists($file_path) && strpos(realpath($file_path), realpath($private_dir)) === 0) {
            wp_delete_file($file_path);
        }
    }
    
    // Mark that user has interacted with migration system
    update_option('spdfed_has_migrated', true);
    
    // Use centralized file manager to clean up
    SPDFED_File_Manager::delete_free_file();
    
    // Remove additional settings and default post ID (clean slate)
    delete_option('spdfed_free_enable_name_field');
    delete_option('spdfed_free_name_field_required');
    delete_option('spdfed_free_enable_gdpr');
    delete_option('spdfed_free_gdpr_message');
    delete_option('spdfed_premium_default_post_id');
    
    add_settings_error('spdfed_settings', 'file_removed', __('Free file removed successfully. You can now create new secure downloads via CPT.', 'email-gated-downloads'), 'updated');
    wp_redirect(admin_url('options-general.php?page=spdfed-settings'));
    exit;
}

// AJAX handler for dismissing notices
add_action('wp_ajax_spdfed_dismiss_notice', 'spdfed_handle_dismiss_notice');

/**
 * Handle AJAX request to dismiss admin notices.
 */
function spdfed_handle_dismiss_notice() {
    // Check nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'spdfed_dismiss_notice')) {
        wp_die(esc_html__('Security check failed.', 'email-gated-downloads'));
    }
    
    // Check permissions
    if (!current_user_can('manage_options')) {
        wp_die(esc_html__('You do not have sufficient permissions.', 'email-gated-downloads'));
    }
    
    // Get and sanitize the option name
    $option = isset($_POST['option']) ? sanitize_key($_POST['option']) : '';
    
    if (empty($option)) {
        wp_die(esc_html__('Invalid option.', 'email-gated-downloads'));
    }
    
    // Whitelist allowed dismiss options for security
    $allowed_options = [
        'spdfed_premium_welcome_dismissed'
    ];
    
    if (!in_array($option, $allowed_options, true)) {
        wp_die(esc_html__('Invalid dismiss option.', 'email-gated-downloads'));
    }
    
    // Save the dismissal
    update_option($option, true);
    
    wp_die(); // This is required to terminate immediately and return a proper response
}

// AJAX handler for repairing file metadata
add_action('wp_ajax_spdfed_repair_file_metadata', 'spdfed_handle_repair_file_metadata');

/**
 * Handle AJAX request to repair file metadata.
 */
function spdfed_handle_repair_file_metadata() {
    // Verify nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'spdfed_repair_files')) {
        wp_send_json_error('Invalid nonce');
    }
    
    // Check user capabilities
    if (!current_user_can('manage_options')) {
        wp_send_json_error('Insufficient permissions');
    }
    
    try {
        // Run the repair function
        $result = SPDFED_File_Manager::repair_file_metadata();
        wp_send_json_success($result);
    } catch (Exception $e) {
        wp_send_json_error($e->getMessage());
    }
}

/**
 * Helper function to add custom admin CSS.
 * 
 * Usage:
 * spdfed_add_admin_css('.spdfed-migration-options { background: #f0f0f0; }');
 * 
 * @param string $css CSS rules to add
 */
function spdfed_add_admin_css($css) {
    add_action('admin_head', function() use ($css) {
        echo '<style type="text/css">' . esc_html(wp_strip_all_tags($css)) . '</style>';
    });
} 