<?php
// Security: Prevent direct access to plugin files.
defined( 'ABSPATH' ) || exit;

class IOTC_Admin {

    public function __construct() {
        add_action( 'admin_menu', array( $this, 'add_plugin_page' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
    }

    public function enqueue_scripts( $hook ) {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only page-slug check for conditional asset loading, no state change.
        if ( ! isset( $_GET['page'] ) || ( 'intouch-orphan-table-cleaner' !== $_GET['page'] && 'intouch_orphan_table_cleaner' !== $_GET['page'] ) ) {
            return;
        }

        $is_pro = defined( 'IOTC_IS_PRO' ) && IOTC_IS_PRO;

        wp_enqueue_style( 'iotc-admin-css', plugins_url( 'assets/css/admin.css', dirname( dirname( __FILE__ ) ) . '/intouch-orphan-table-cleaner.php' ), array(), IOTC_VERSION );
        wp_enqueue_script( 'iotc-admin-js', plugins_url( 'assets/js/admin.js', dirname( dirname( __FILE__ ) ) . '/intouch-orphan-table-cleaner.php' ), array( 'jquery' ), IOTC_VERSION, true );

        $recovery_url = admin_url( 'admin-ajax.php?action=iotc_emergency_restore&token=' . rawurlencode( (string) get_option( 'iotc_recovery_token', '' ) ) );

        wp_localize_script( 'iotc-admin-js', 'iotc_admin_vars', array(
            'confirmTrashMsg' => __( "We will now open the Emergency Recovery page in a new tab. Keep it open while you test the site!\n\nAre you sure you want to suspend this table?", 'intouch-orphan-table-cleaner' ),
            'confirmDeleteMsg' => __( "Are you sure you want to permanently delete this table? This action CANNOT be undone.", 'intouch-orphan-table-cleaner' ),
            'ajaxTrashNonce' => wp_create_nonce( 'ajax_trash_table_nonce' ),
            'ajaxRestoreNonce' => wp_create_nonce( 'ajax_restore_table_nonce' ),
            'ajaxForceNonce' => wp_create_nonce( 'ajax_force_delete_table_nonce' ),
            'ajaxOptimizeNonce' => wp_create_nonce( 'ajax_optimize_database_nonce' ),
            'ajaxSaveCronNonce' => wp_create_nonce( 'ajax_save_cron_nonce' ),
            'recoveryUrl' => $recovery_url,
            'alertSelectMsg' => __( "Please select at least one table.", 'intouch-orphan-table-cleaner' ),
            'optimizingMsg' => __( "Optimizing...", 'intouch-orphan-table-cleaner' ),
            'optimizeDbMsg' => __( "Optimize Database", 'intouch-orphan-table-cleaner' ),
            'suspendedMsg' => __( "Suspended!", 'intouch-orphan-table-cleaner' ),
            'restoredMsg' => __( "Restored!", 'intouch-orphan-table-cleaner' ),
            'deletedMsg' => __( "Deleted!", 'intouch-orphan-table-cleaner' ),
            'isPro' => $is_pro
        ) );
    }

    /**
     * Create the top-level menu.
     */
    public function add_plugin_page() {
        add_menu_page(
            __( 'WP Intouch Orphan Table Cleaner', 'intouch-orphan-table-cleaner' ), // Page title
            __( 'Intouch Orphan Table Cleaner', 'intouch-orphan-table-cleaner' ),    // Menu title
            'manage_options',                                 // Required capability
            'intouch-orphan-table-cleaner',                   // Slug
            array( $this, 'render_admin_page' ),              // Callback
            'dashicons-database',                             // Icon
            80                                                // Position
        );
    }

    /**
     * User Interface and Matching Logic: display the table.
     */
    public function render_admin_page() {
        $is_pro      = defined( 'IOTC_IS_PRO' ) && IOTC_IS_PRO;
        $upgrade_url = 'https://dev.intouchdesign.it/plugin/intouch-orphan-table-cleaner/';

        $orphan_tables = IOTC_Scanner::get_orphan_tables();
        $trashed_tables = IOTC_Scanner::get_trashed_tables();
        $ignored_tables = get_option( 'iotc_ignored_tables', array() );
        $reset_url = wp_nonce_url( admin_url( 'admin.php?page=intouch-orphan-table-cleaner&action=reset_ignored' ), 'reset_ignored_nonce' );

        // Calculate stats
        $total_orphans = count( $orphan_tables );
        $total_mb = 0;
        foreach ( $orphan_tables as $ot ) {
            $total_mb += $ot['size_mb'];
        }

        // Ensure emergency token exists
        $recovery_token = get_option( 'iotc_recovery_token' );
        if ( ! $recovery_token ) {
            $recovery_token = wp_generate_password( 20, false );
            update_option( 'iotc_recovery_token', $recovery_token );
        }
        $recovery_url = admin_url( 'admin-ajax.php?action=iotc_emergency_restore&token=' . rawurlencode( $recovery_token ) );

        $overhead_data = IOTC_Scanner::get_database_overhead();
        $overhead_class = ( $overhead_data['overhead_mb'] > 0 ) ? 'wpdd-overhead-value--warn' : 'wpdd-overhead-value--ok';

        $cron_settings = get_option( 'iotc_cron_settings', array(
            'enabled'         => 'no',
            'frequency'       => 'monthly',
            'days'            => 7,
            'report_frequency' => 'monthly',
            'report_days'      => 30
        ) );

        ?>
        <div class="wrap">
            <h1 class="wp-heading-inline"><?php esc_html_e( 'Find Orphan Tables', 'intouch-orphan-table-cleaner' ); ?></h1>
            <p><?php esc_html_e( 'This tool analyzes the database to find tables created by plugins that are no longer installed.', 'intouch-orphan-table-cleaner' ); ?></p>

            <h2 class="nav-tab-wrapper wpdd-nav-tabs">
                <a href="#wpdd-tab-scanner" class="nav-tab nav-tab-active"><?php esc_html_e( 'Scanner', 'intouch-orphan-table-cleaner' ); ?></a>
                <a href="#wpdd-tab-trash" class="nav-tab">
                    <?php esc_html_e( 'Suspended', 'intouch-orphan-table-cleaner' ); ?>
                    <?php if ( ! empty( $trashed_tables ) ) echo '<span class="update-plugins count-' . absint( count( $trashed_tables ) ) . '"><span class="plugin-count">' . absint( count( $trashed_tables ) ) . '</span></span>'; ?>
                </a>
                <a href="#wpdd-tab-settings" class="nav-tab"><?php esc_html_e( 'Settings', 'intouch-orphan-table-cleaner' ); ?></a>
            </h2>
            <br>

            <?php if ( ! $is_pro ) : ?>
            <!-- Slim Pro reminder — visible above every tab, jumps down to the full Pro box in Settings -->
            <div class="wpdd-pro-strip">
                <span class="wpdd-pro-strip__icon" aria-hidden="true">★</span>
                <span class="wpdd-pro-strip__text"><?php esc_html_e( 'Unlock the full potential of Intouch Orphan Table Cleaner.', 'intouch-orphan-table-cleaner' ); ?></span>
                <a href="#wpdd-tab-settings" class="wpdd-pro-strip__link" data-tab-target="#wpdd-tab-settings"><?php esc_html_e( 'See Pro features', 'intouch-orphan-table-cleaner' ); ?></a>
            </div>
            <?php endif; ?>

            <div id="wpdd-tab-scanner" class="wpdd-tab-content wpdd-tab-content-active">
            <div class="card wpdd-card-full wpdd-card-full--info">
                <h2 class="wpdd-heading-help wpdd-help-toggle">
                    <span class="dashicons dashicons-editor-help wpdd-icon-align-2"></span> <?php esc_html_e( 'How to use WP Intouch Orphan Table Cleaner (Click to expand)', 'intouch-orphan-table-cleaner' ); ?>
                    <span class="dashicons dashicons-arrow-down-alt2 wpdd-help-arrow wpdd-icon-align-2"></span>
                </h2>
                <div id="wpdd-help-content" class="wpdd-hidden wpdd-help-body">
                    <ol class="wpdd-help-list">
                        <li><strong><?php esc_html_e( 'Review:', 'intouch-orphan-table-cleaner' ); ?></strong> <?php esc_html_e( 'Check the list of identified orphan tables below. If you are unsure about a table, click "Search Info" to look it up on Google.', 'intouch-orphan-table-cleaner' ); ?></li>
                        <li><strong><?php esc_html_e( 'Backup (Optional):', 'intouch-orphan-table-cleaner' ); ?></strong> <?php esc_html_e( 'Click the "Backup" button next to a table to download a .sql export of that single table before making any changes.', 'intouch-orphan-table-cleaner' ); ?></li>
                        <li><strong><?php esc_html_e( 'Suspend (Dry Run):', 'intouch-orphan-table-cleaner' ); ?></strong> <?php esc_html_e( 'Click "Suspend" to safely rename the table. This makes it inactive without deleting its data. An Emergency Recovery tab will open so you can restore everything if your site breaks.', 'intouch-orphan-table-cleaner' ); ?></li>
                        <li><strong><?php esc_html_e( 'Verify:', 'intouch-orphan-table-cleaner' ); ?></strong> <?php esc_html_e( 'Browse your site to confirm everything still works. If something breaks, use the Emergency Recovery link or click "Restore" in the Suspended tab.', 'intouch-orphan-table-cleaner' ); ?></li>
                        <li><strong><?php esc_html_e( 'Delete Permanently:', 'intouch-orphan-table-cleaner' ); ?></strong> <?php esc_html_e( 'Once you are confident the table is not needed, click "Delete Permanently" from the Suspended Tables tab to free up database space.', 'intouch-orphan-table-cleaner' ); ?></li>
                        <li><strong><?php esc_html_e( 'Optimize:', 'intouch-orphan-table-cleaner' ); ?></strong> <?php esc_html_e( 'Use the "Optimize Database" button in the Database Health card to reclaim fragmented overhead space after deletions.', 'intouch-orphan-table-cleaner' ); ?></li>
                    </ol>
                </div>
            </div>

            <div class="notice notice-warning inline wpdd-notice-warning">
                <p>
                    <strong><?php esc_html_e( 'Disclaimer:', 'intouch-orphan-table-cleaner' ); ?></strong>
                    <?php esc_html_e( 'We assume no responsibility for any data loss. Modifying or deleting database tables is a highly critical action. We strongly recommend downloading a Full Backup of your database before proceeding with any deletion.', 'intouch-orphan-table-cleaner' ); ?>
                </p>
            </div>

            <?php settings_errors( 'iotc_messages' ); ?>

            <?php if ( ! empty( $ignored_tables ) ) : ?>
                <div class="notice notice-info inline wpdd-notice-info">
                    <p>
                        <?php /* translators: %d: number of ignored tables */ ?>
                        <?php printf( esc_html__( 'You have %d ignored tables.', 'intouch-orphan-table-cleaner' ), count( $ignored_tables ) ); ?>
                        <a href="<?php echo esc_url( $reset_url ); ?>" class="button button-small wpdd-btn-reset">
                            <?php esc_html_e( 'Reset Ignored List', 'intouch-orphan-table-cleaner' ); ?>
                        </a>
                    </p>
                </div>
            <?php endif; ?>

            <?php
            $historical_tables = (int) get_option( 'iotc_total_tables_deleted', 0 );
            $historical_mb     = (float) get_option( 'iotc_total_space_freed_mb', 0 );
            ?>
            <div class="wpdd-flex-row">
                <div class="card wpdd-card-flex wpdd-card-flex--green">
                    <h2 class="wpdd-heading-flush"><span class="dashicons dashicons-chart-area wpdd-icon-align-2"></span> <?php esc_html_e( 'Statistics', 'intouch-orphan-table-cleaner' ); ?></h2>

                    <h3 class="wpdd-subheading"><?php esc_html_e( 'Current Status', 'intouch-orphan-table-cleaner' ); ?></h3>
                    <p class="wpdd-stat-line">
                        <strong><?php esc_html_e( 'Orphan Tables:', 'intouch-orphan-table-cleaner' ); ?></strong> <span id="stat-total-tables"><?php echo esc_html( $total_orphans ); ?></span><br>
                        <strong><?php esc_html_e( 'Space to Recover:', 'intouch-orphan-table-cleaner' ); ?></strong> <span id="stat-total-mb"><?php echo esc_html( round($total_mb, 2) ); ?></span> MB
                    </p>

                    <h3 class="wpdd-subheading-spaced"><?php esc_html_e( 'Historical Data', 'intouch-orphan-table-cleaner' ); ?></h3>
                    <p class="wpdd-stat-line">
                        <strong><?php esc_html_e( 'Tables Deleted:', 'intouch-orphan-table-cleaner' ); ?></strong> <?php echo esc_html( $historical_tables ); ?><br>
                        <strong><?php esc_html_e( 'Total Space Freed:', 'intouch-orphan-table-cleaner' ); ?></strong> <?php echo esc_html( round($historical_mb, 2) ); ?> MB
                    </p>
                </div>

                <?php if ( $is_pro ) : ?>
                <div class="card wpdd-card-flex wpdd-card-flex--blue">
                    <h2 class="wpdd-heading-flush"><?php esc_html_e( 'Database Maintenance', 'intouch-orphan-table-cleaner' ); ?></h2>
                    <p class="wpdd-text-14">
                        <?php esc_html_e( 'You can download a .sql backup of any individual table directly from the table row in the Scanner below. Click the "Backup" button next to any table to export it instantly.', 'intouch-orphan-table-cleaner' ); ?>
                    </p>
                    <?php
                    $backup_full_url = wp_nonce_url(
                        admin_url( 'admin.php?page=intouch-orphan-table-cleaner&action=backup_full_db' ),
                        'backup_full_db_nonce'
                    );
                    ?>
                    <a href="<?php echo esc_url( $backup_full_url ); ?>" class="button button-primary wpdd-btn-mt">
                        <span class="dashicons dashicons-database wpdd-icon-align-3"></span>
                        <?php esc_html_e( 'Download Full Database Backup', 'intouch-orphan-table-cleaner' ); ?>
                    </a>
                </div>
                <?php endif; ?>

                <div class="card wpdd-card-flex wpdd-card-flex--orange">
                    <h2 class="wpdd-heading-flush"><?php esc_html_e( 'Database Health', 'intouch-orphan-table-cleaner' ); ?></h2>
                    <p class="wpdd-text-14">
                        <strong><?php esc_html_e( 'Overhead (Wasted Space):', 'intouch-orphan-table-cleaner' ); ?></strong>
                        <span id="stat-overhead-mb" class="wpdd-overhead-value <?php echo esc_attr( $overhead_class ); ?>">
                            <?php echo esc_html( $overhead_data['overhead_mb'] ); ?> MB
                        </span>
                    </p>
                    <p class="wpdd-text-13-muted">
                        <?php esc_html_e( 'Overhead is fragmented space created when rows are deleted or updated. Optimizing tables reclaims this space.', 'intouch-orphan-table-cleaner' ); ?>
                    </p>
                    <button class="button button-secondary wpdd-btn-mt" id="btn-optimize-db" <?php disabled( $overhead_data['overhead_mb'] == 0 ); ?>>
                        <span class="dashicons dashicons-update-alt wpdd-icon-align-3"></span>
                        <span class="btn-text"><?php esc_html_e( 'Optimize Database', 'intouch-orphan-table-cleaner' ); ?></span>
                    </button>
                    <span id="optimize-feedback" class="wpdd-feedback-hidden"></span>
                </div>
            </div>

            <?php if ( $is_pro ) : ?>
            <div class="wpdd-bulk-actions">
                <button class="button action bulk-trash-btn"><?php esc_html_e( 'Suspend Selected (Dry Run)', 'intouch-orphan-table-cleaner' ); ?></button>
            </div>
            <?php endif; // Pro bulk actions ?>

            <table class="wp-list-table widefat fixed striped" id="orphan-tables-list">
                <thead>
                    <tr>
                        <?php if ( $is_pro ) : ?>
                            <th scope="col" class="manage-column check-column"><input type="checkbox" class="wpdd-select-all"></th>
                        <?php endif; ?>
                        <th scope="col" class="manage-column column-table_name"><?php esc_html_e( 'Table Name', 'intouch-orphan-table-cleaner' ); ?></th>
                        <th scope="col" class="manage-column column-last_modified"><?php esc_html_e( 'Last Modified', 'intouch-orphan-table-cleaner' ); ?></th>
                        <th scope="col" class="manage-column column-size"><?php esc_html_e( 'Size (MB)', 'intouch-orphan-table-cleaner' ); ?></th>
                        <th scope="col" class="manage-column column-status"><?php esc_html_e( 'Status', 'intouch-orphan-table-cleaner' ); ?></th>
                        <th scope="col" class="manage-column column-actions"><?php esc_html_e( 'Actions', 'intouch-orphan-table-cleaner' ); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    if ( ! empty( $orphan_tables ) ) {
                        foreach ( $orphan_tables as $table_data ) {

                            $ignore_url = wp_nonce_url(
                                admin_url( 'admin.php?page=intouch-orphan-table-cleaner&action=ignore_table&table=' . rawurlencode( $table_data['name'] ) ),
                                'ignore_table_nonce'
                            );

                            $search_url = 'https://www.google.com/search?q=' . rawurlencode( 'wordpress plugin "' . $table_data['name'] . '"' );

                            $backup_url = wp_nonce_url(
                                admin_url( 'admin.php?page=intouch-orphan-table-cleaner&action=backup_table&table=' . rawurlencode( $table_data['name'] ) ),
                                'backup_table_nonce'
                            );

                            ?>
                            <tr id="row-<?php echo esc_attr( md5($table_data['name']) ); ?>">
                                <?php if ( $is_pro ) : ?>
                                    <th scope="row" class="check-column"><input type="checkbox" class="wpdd-table-checkbox" value="<?php echo esc_attr($table_data['name']); ?>"></th>
                                <?php endif; ?>
                                <td><strong><?php echo esc_html( $table_data['name'] ); ?></strong></td>
                                <td><?php echo esc_html( $table_data['last_modified'] ); ?></td>
                                <td class="table-size" data-size="<?php echo esc_attr( $table_data['size_mb'] ); ?>"><?php echo esc_html( $table_data['size_mb'] ); ?> MB</td>
                                <td>
                                    <span class="dashicons dashicons-warning wpdd-icon-danger"></span>
                                    <?php echo esc_html( $table_data['status_text'] ); ?>
                                </td>
                                <td>
                                    <div class="wpdd-actions-wrapper">
                                        <button class="button button-secondary ajax-trash-table-btn wpdd-btn-danger" data-tablename="<?php echo esc_attr( $table_data['name'] ); ?>">
                                            <?php esc_html_e( 'Suspend (Dry Run)', 'intouch-orphan-table-cleaner' ); ?>
                                        </button>
                                        <span class="delete-feedback wpdd-feedback-success-hidden">
                                            <?php esc_html_e( 'Suspended!', 'intouch-orphan-table-cleaner' ); ?>
                                        </span>
                                        <a href="<?php echo esc_url( $backup_url ); ?>" class="button button-secondary">
                                            <span class="dashicons dashicons-download wpdd-icon-align-3"></span>
                                            <?php esc_html_e( 'Backup', 'intouch-orphan-table-cleaner' ); ?>
                                        </a>
                                        <a href="<?php echo esc_url( $ignore_url ); ?>" class="button button-secondary">
                                            <?php esc_html_e( 'Ignore', 'intouch-orphan-table-cleaner' ); ?>
                                        </a>
                                        <a href="<?php echo esc_url( $search_url ); ?>" target="_blank" class="button button-secondary">
                                            <span class="dashicons dashicons-search wpdd-icon-align-3"></span>
                                            <?php esc_html_e( 'Search Info', 'intouch-orphan-table-cleaner' ); ?>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php
                        }
                    } else {
                        ?>
                        <tr id="no-tables-row">
                            <td colspan="<?php echo $is_pro ? '6' : '5'; ?>"><?php esc_html_e( 'No orphan tables found. Great job!', 'intouch-orphan-table-cleaner' ); ?></td>
                        </tr>
                        <?php
                    }
                    ?>
                </tbody>
            </table>
            </div><!-- /#wpdd-tab-scanner -->

            <div id="wpdd-tab-trash" class="wpdd-tab-content">
            <?php if ( ! empty( $trashed_tables ) ) : ?>
            <h2 class="wpdd-danger-heading"><?php esc_html_e( 'Suspended Tables (Trash)', 'intouch-orphan-table-cleaner' ); ?></h2>
            <p><?php esc_html_e( 'These tables have been temporarily renamed. If your site works perfectly, you can permanently delete them. If something is broken, restore them immediately.', 'intouch-orphan-table-cleaner' ); ?></p>

            <?php if ( $is_pro ) : ?>
            <div class="wpdd-bulk-actions">
                <button class="button action bulk-restore-btn"><?php esc_html_e( 'Restore Selected', 'intouch-orphan-table-cleaner' ); ?></button>
                <button class="button action bulk-force-delete-btn wpdd-btn-danger"><?php esc_html_e( 'Delete Permanently Selected', 'intouch-orphan-table-cleaner' ); ?></button>
            </div>
            <?php endif; ?>

            <table class="wp-list-table widefat fixed striped" id="trashed-tables-list">
                <thead>
                    <tr>
                        <?php if ( $is_pro ) : ?>
                            <th scope="col" class="manage-column check-column"><input type="checkbox" class="wpdd-select-all"></th>
                        <?php endif; ?>
                        <th scope="col" class="manage-column column-table_name"><?php esc_html_e( 'Original Name', 'intouch-orphan-table-cleaner' ); ?></th>
                        <th scope="col" class="manage-column column-last_modified"><?php esc_html_e( 'Suspended Name', 'intouch-orphan-table-cleaner' ); ?></th>
                        <th scope="col" class="manage-column column-size"><?php esc_html_e( 'Size (MB)', 'intouch-orphan-table-cleaner' ); ?></th>
                        <th scope="col" class="manage-column column-status"><?php esc_html_e( 'Status', 'intouch-orphan-table-cleaner' ); ?></th>
                        <th scope="col" class="manage-column column-actions"><?php esc_html_e( 'Actions', 'intouch-orphan-table-cleaner' ); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ( $trashed_tables as $trash_data ) : ?>
                    <tr id="trash-row-<?php echo esc_attr( md5($trash_data['name']) ); ?>">
                        <?php if ( $is_pro ) : ?>
                            <th scope="row" class="check-column"><input type="checkbox" class="wpdd-table-checkbox" value="<?php echo esc_attr($trash_data['name']); ?>"></th>
                        <?php endif; ?>
                        <td><strong><?php echo esc_html( $trash_data['original_name'] ); ?></strong></td>
                        <td class="wpdd-text-danger"><em><?php echo esc_html( $trash_data['name'] ); ?></em></td>
                        <td class="table-size" data-size="<?php echo esc_attr( $trash_data['size_mb'] ); ?>"><?php echo esc_html( $trash_data['size_mb'] ); ?> MB</td>
                        <td>
                            <span class="dashicons dashicons-trash wpdd-icon-danger"></span>
                            <?php echo esc_html( $trash_data['status_text'] ); ?>
                        </td>
                        <td>
                            <div class="wpdd-actions-wrapper">
                                <button class="button button-primary ajax-restore-table-btn" data-tablename="<?php echo esc_attr( $trash_data['name'] ); ?>">
                                    <span class="dashicons dashicons-undo wpdd-icon-align-3"></span>
                                    <?php esc_html_e( 'Restore', 'intouch-orphan-table-cleaner' ); ?>
                                </button>
                                <button class="button button-secondary ajax-force-delete-table-btn wpdd-btn-danger" data-tablename="<?php echo esc_attr( $trash_data['name'] ); ?>">
                                    <span class="dashicons dashicons-trash wpdd-icon-align-3"></span>
                                    <?php esc_html_e( 'Delete Permanently', 'intouch-orphan-table-cleaner' ); ?>
                                </button>
                                <span class="action-feedback wpdd-feedback-bold-hidden"></span>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <div class="notice notice-error inline wpdd-notice-error-block">
                <h3 class="wpdd-danger-heading-flat"><?php echo esc_html( '⚠️ ' . __( 'Emergency Recovery Link', 'intouch-orphan-table-cleaner' ) ); ?></h3>
                <p><?php esc_html_e( 'If suspending a table causes a fatal error and locks you out of this dashboard, you can use the link below to force-restore all tables. Keep this link safe before proceeding!', 'intouch-orphan-table-cleaner' ); ?></p>
                <input type="text" readonly="readonly" class="large-text wpdd-recovery-input wpdd-select-on-click" value="<?php echo esc_attr( $recovery_url ); ?>">
            </div>
            <?php else : ?>
                <p class="wpdd-mt-15 wpdd-text-14"><?php esc_html_e( 'No suspended tables found. Your trash is empty!', 'intouch-orphan-table-cleaner' ); ?></p>
            <?php endif; ?>
            </div><!-- /#wpdd-tab-trash -->

            <div id="wpdd-tab-settings" class="wpdd-tab-content">
            <?php if ( $is_pro ) : ?>
            <div class="card wpdd-card-full wpdd-card-full--gray">
                <h2 class="wpdd-heading-flush"><span class="dashicons dashicons-clock wpdd-icon-align-2"></span> <?php esc_html_e( 'Automatic Optimization (Cron)', 'intouch-orphan-table-cleaner' ); ?></h2>
                <p class="wpdd-text-14">
                    <?php esc_html_e( 'Configure automatic database optimization. When enabled, the plugin will automatically run the optimization task to reclaim overhead space at the selected interval.', 'intouch-orphan-table-cleaner' ); ?>
                </p>
                <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row"><?php esc_html_e( 'Enable Auto-Optimize', 'intouch-orphan-table-cleaner' ); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" id="wpdd-cron-enabled" value="yes" <?php checked( $cron_settings['enabled'], 'yes' ); ?>>
                                <?php esc_html_e( 'Enable automatic database overhead cleanup', 'intouch-orphan-table-cleaner' ); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="wpdd-cron-frequency"><?php esc_html_e( 'Frequency', 'intouch-orphan-table-cleaner' ); ?></label></th>
                        <td>
                            <select id="wpdd-cron-frequency">
                                <option value="daily" <?php selected( $cron_settings['frequency'], 'daily' ); ?>><?php esc_html_e( 'Daily', 'intouch-orphan-table-cleaner' ); ?></option>
                                <option value="weekly" <?php selected( $cron_settings['frequency'], 'weekly' ); ?>><?php esc_html_e( 'Weekly', 'intouch-orphan-table-cleaner' ); ?></option>
                                <option value="monthly" <?php selected( $cron_settings['frequency'], 'monthly' ); ?>><?php esc_html_e( 'Monthly', 'intouch-orphan-table-cleaner' ); ?></option>
                                <option value="custom" <?php selected( $cron_settings['frequency'], 'custom' ); ?>><?php esc_html_e( 'Custom (Days)', 'intouch-orphan-table-cleaner' ); ?></option>
                            </select>
                        </td>
                    </tr>
                    <tr id="wpdd-cron-custom-days-row" class="<?php echo ( $cron_settings['frequency'] === 'custom' ) ? '' : 'wpdd-hidden'; ?>">
                        <th scope="row"><label for="wpdd-cron-days"><?php esc_html_e( 'Custom Days', 'intouch-orphan-table-cleaner' ); ?></label></th>
                        <td>
                            <input type="number" id="wpdd-cron-days" min="1" max="365" value="<?php echo esc_attr( $cron_settings['days'] ); ?>" class="small-text">
                            <p class="description"><?php esc_html_e( 'Enter the number of days between optimizations (e.g. 15 for every 15 days).', 'intouch-orphan-table-cleaner' ); ?></p>
                        </td>
                    </tr>
                </table>
                <h2 class="wpdd-mt-30"><span class="dashicons dashicons-email-alt wpdd-icon-align-2"></span> <?php esc_html_e( 'Email Reports', 'intouch-orphan-table-cleaner' ); ?></h2>
                <p class="wpdd-text-14">
                    <?php esc_html_e( 'Receive an email report containing a summary of detected orphan tables and recoverable space, at the interval you choose.', 'intouch-orphan-table-cleaner' ); ?>
                </p>
                <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row"><?php esc_html_e( 'Enable Email Reports', 'intouch-orphan-table-cleaner' ); ?></th>
                        <td>
                            <label>
                                <?php $report_enabled = isset( $cron_settings['report_enabled'] ) ? $cron_settings['report_enabled'] : 'yes'; ?>
                                <input type="checkbox" id="wpdd-report-enabled" value="yes" <?php checked( $report_enabled, 'yes' ); ?>>
                                <?php esc_html_e( 'Send me a periodic summary report', 'intouch-orphan-table-cleaner' ); ?>
                            </label>
                        </td>
                    </tr>
                    <tr id="wpdd-report-email-row" class="<?php echo ( $report_enabled === 'yes' ) ? '' : 'wpdd-hidden'; ?>">
                        <th scope="row"><label for="wpdd-report-email"><?php esc_html_e( 'Recipient Email', 'intouch-orphan-table-cleaner' ); ?></label></th>
                        <td>
                            <?php $report_email = isset( $cron_settings['report_email'] ) ? $cron_settings['report_email'] : ''; ?>
                            <input type="email" id="wpdd-report-email" value="<?php echo esc_attr( $report_email ); ?>" class="regular-text" placeholder="<?php echo esc_attr( get_option('admin_email') ); ?>">
                            <p class="description"><?php esc_html_e( 'Leave blank to use the default site administrator email.', 'intouch-orphan-table-cleaner' ); ?></p>
                        </td>
                    </tr>
                    <tr id="wpdd-report-frequency-row" class="<?php echo ( $report_enabled === 'yes' ) ? '' : 'wpdd-hidden'; ?>">
                        <th scope="row"><label for="wpdd-report-frequency"><?php esc_html_e( 'Frequency', 'intouch-orphan-table-cleaner' ); ?></label></th>
                        <td>
                            <?php $report_frequency = isset( $cron_settings['report_frequency'] ) ? $cron_settings['report_frequency'] : 'monthly'; ?>
                            <select id="wpdd-report-frequency">
                                <option value="weekly" <?php selected( $report_frequency, 'weekly' ); ?>><?php esc_html_e( 'Weekly', 'intouch-orphan-table-cleaner' ); ?></option>
                                <option value="monthly" <?php selected( $report_frequency, 'monthly' ); ?>><?php esc_html_e( 'Monthly', 'intouch-orphan-table-cleaner' ); ?></option>
                                <option value="custom" <?php selected( $report_frequency, 'custom' ); ?>><?php esc_html_e( 'Custom (Days)', 'intouch-orphan-table-cleaner' ); ?></option>
                            </select>
                        </td>
                    </tr>
                    <tr id="wpdd-report-custom-days-row" class="<?php echo ( $report_enabled === 'yes' && $report_frequency === 'custom' ) ? '' : 'wpdd-hidden'; ?>">
                        <th scope="row"><label for="wpdd-report-days"><?php esc_html_e( 'Custom Days', 'intouch-orphan-table-cleaner' ); ?></label></th>
                        <td>
                            <?php $report_days = isset( $cron_settings['report_days'] ) ? $cron_settings['report_days'] : 30; ?>
                            <input type="number" id="wpdd-report-days" min="1" max="365" value="<?php echo esc_attr( $report_days ); ?>" class="small-text">
                            <p class="description"><?php esc_html_e( 'Enter the number of days between email reports (e.g. 15 for every 15 days).', 'intouch-orphan-table-cleaner' ); ?></p>
                        </td>
                    </tr>
                </table>
                <p class="submit wpdd-submit-flush">
                    <button type="button" class="button button-primary" id="btn-save-cron-settings">
                        <?php esc_html_e( 'Save Settings', 'intouch-orphan-table-cleaner' ); ?>
                    </button>
                    <span id="save-cron-feedback" class="wpdd-feedback-hidden"></span>
                </p>
            </div>
            <?php else : ?>
            <div class="card wpdd-card-full wpdd-card-full--blue">
                <h2 class="wpdd-heading-flush"><?php esc_html_e( 'About Intouch Orphan Table Cleaner', 'intouch-orphan-table-cleaner' ); ?></h2>
                <p class="wpdd-about-desc">
                    <?php esc_html_e( 'This plugin scans your WordPress database and identifies tables left behind by uninstalled plugins. You can safely suspend, verify, and permanently delete them to keep your database clean.', 'intouch-orphan-table-cleaner' ); ?>
                </p>
                <p class="wpdd-text-14">
                    <a href="<?php echo esc_url( function_exists( 'iotc_fs' ) ? iotc_fs()->get_account_url() : 'https://dev.intouchdesign.it/plugin/intouch-orphan-table-cleaner/' ); ?>" class="button button-secondary">
                        <?php esc_html_e( 'Activate License Key', 'intouch-orphan-table-cleaner' ); ?>
                    </a>
                </p>
            </div>

            <div class="card wpdd-pro-teaser">
                <p class="wpdd-pro-badge">★ <?php esc_html_e( 'Unlock the Potential', 'intouch-orphan-table-cleaner' ); ?></p>
                <h2 class="wpdd-pro-teaser-title">
                    <?php esc_html_e( 'Intouch Orphan Table Cleaner', 'intouch-orphan-table-cleaner' ); ?> <span class="wpdd-pro-title-accent">PRO</span>
                </h2>
                <p class="wpdd-pro-modal-subtitle">
                    <?php esc_html_e( 'Automate your database maintenance and take full control of your cleanup workflow.', 'intouch-orphan-table-cleaner' ); ?>
                </p>
                <ul class="wpdd-pro-feature-list">
                    <li>
                        <span class="dashicons dashicons-yes-alt"></span>
                        <span><strong><?php esc_html_e( 'Full Database Backup:', 'intouch-orphan-table-cleaner' ); ?></strong> <?php esc_html_e( 'Download a complete .sql backup of your entire database in one click.', 'intouch-orphan-table-cleaner' ); ?></span>
                    </li>
                    <li>
                        <span class="dashicons dashicons-yes-alt"></span>
                        <span><strong><?php esc_html_e( 'Bulk Actions:', 'intouch-orphan-table-cleaner' ); ?></strong> <?php esc_html_e( 'Suspend, restore, or permanently delete multiple orphan tables at once.', 'intouch-orphan-table-cleaner' ); ?></span>
                    </li>
                    <li>
                        <span class="dashicons dashicons-yes-alt"></span>
                        <span><strong><?php esc_html_e( 'Automatic Optimization:', 'intouch-orphan-table-cleaner' ); ?></strong> <?php esc_html_e( 'Schedule recurring database optimization so overhead never builds up again.', 'intouch-orphan-table-cleaner' ); ?></span>
                    </li>
                    <li>
                        <span class="dashicons dashicons-yes-alt"></span>
                        <span><strong><?php esc_html_e( 'Monthly Email Reports:', 'intouch-orphan-table-cleaner' ); ?></strong> <?php esc_html_e( 'Get a summary of detected orphan tables and recoverable space straight to your inbox.', 'intouch-orphan-table-cleaner' ); ?></span>
                    </li>
                    <li>
                        <span class="dashicons dashicons-yes-alt"></span>
                        <span><strong><?php esc_html_e( 'Priority Support:', 'intouch-orphan-table-cleaner' ); ?></strong> <?php esc_html_e( 'Dedicated, fast assistance whenever you need it.', 'intouch-orphan-table-cleaner' ); ?></span>
                    </li>
                </ul>
                <a href="<?php echo esc_url( $upgrade_url ); ?>" target="_blank" class="button button-primary wpdd-pro-modal-cta">
                    <?php esc_html_e( 'Discover PRO version', 'intouch-orphan-table-cleaner' ); ?>
                </a>
            </div>
            <?php endif; ?>

            </div><!-- /#wpdd-tab-settings -->

            <p class="wpdd-footer-credit">
                <?php
                printf(
                    /* translators: %s: Author website URL */
                    /* translators: %s: dynamic value */
                    wp_kses_post( __( 'Developed with ❤️ by <a href="%s" target="_blank">InTouchDesign</a>.', 'intouch-orphan-table-cleaner' ) ),
                    'https://dev.intouchdesign.it/'
                );
                ?>
            </p>

        </div>
        <?php
    }
}
