<?php
/**
 * Admin Settings View
 *
 * Variables in scope:
 *   $settings        - current settings array
 *   $has_secret      - bool: whether a secret key is stored
 *   $using_constants - bool: whether credentials come from wp-config.php
 *
 * @package Wrenio_Media_Offload
 */

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

$wrenio_logger = \Wrenio_Media_Offload\Wrenio_Logger::get_instance();
?>

<div class="wrenio-media-offload-admin">

    <?php if ( $using_constants ) : ?>
        <div class="notice notice-info">
            <p><strong><?php echo esc_html__( 'Note:', 'wrenio-media-offload' ); ?></strong>
                <?php echo esc_html__( 'Some credentials are defined in wp-config.php and will override the values below.', 'wrenio-media-offload' ); ?>
            </p>
        </div>
    <?php endif; ?>

    <div class="nav-tab-wrapper">
        <a href="#general" class="nav-tab nav-tab-active" data-tab="general"><?php echo esc_html__( 'General', 'wrenio-media-offload' ); ?></a>
        <a href="#features" class="nav-tab" data-tab="features"><?php echo esc_html__( 'Features', 'wrenio-media-offload' ); ?></a>
        <a href="#auto-sync" class="nav-tab" data-tab="auto-sync"><?php echo esc_html__( 'Auto Sync', 'wrenio-media-offload' ); ?></a>
        <a href="#logs" class="nav-tab" data-tab="logs"><?php echo esc_html__( 'Logs', 'wrenio-media-offload' ); ?></a>
        <a href="#debug" class="nav-tab" data-tab="debug"><?php echo esc_html__( 'Debug Info', 'wrenio-media-offload' ); ?></a>
    </div>

    <form method="post" action="" id="wrenio-media-offload-settings-form">
        <?php wp_nonce_field( 'wrenio_media_offload_settings_nonce' ); ?>

        <div id="tab-general" class="tab-content active">
            <h2><?php echo esc_html__( 'Cloudflare R2 Credentials', 'wrenio-media-offload' ); ?></h2>

            <div class="notice notice-warning inline" style="margin: 16px 0; padding: 10px;">
                <p><strong><?php echo esc_html__( 'Security tip:', 'wrenio-media-offload' ); ?></strong>
                <?php echo esc_html__( 'For best security, define credentials in wp-config.php rather than storing them in the database:', 'wrenio-media-offload' ); ?></p>
                <pre style="background: #f6f7f7; padding: 8px; font-size: 11px; overflow-x: auto;">define( 'WRENIO_R2_ACCOUNT_ID',        'your-account-id' );
define( 'WRENIO_R2_ACCESS_KEY_ID',     'your-access-key' );
define( 'WRENIO_R2_SECRET_ACCESS_KEY', 'your-secret-key' );
define( 'WRENIO_R2_BUCKET_NAME',       'your-bucket-name' );
define( 'WRENIO_R2_PUBLIC_URL',        'https://media.example.com' );</pre>
            </div>

            <table class="form-table">
                <tr>
                    <th scope="row">
                        <label for="account_id"><?php echo esc_html__( 'Account ID', 'wrenio-media-offload' ); ?></label>
                    </th>
                    <td>
                        <input type="text" id="account_id" name="wrenio_media_offload_settings[account_id]"
                               value="<?php echo esc_attr( $settings['account_id'] ); ?>"
                               class="regular-text"
                               <?php echo defined( 'WRENIO_R2_ACCOUNT_ID' ) && WRENIO_R2_ACCOUNT_ID ? 'readonly' : ''; ?> />
                        <p class="description"><?php echo esc_html__( 'Your Cloudflare Account ID', 'wrenio-media-offload' ); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="access_key_id"><?php echo esc_html__( 'Access Key ID', 'wrenio-media-offload' ); ?></label>
                    </th>
                    <td>
                        <input type="text" id="access_key_id" name="wrenio_media_offload_settings[access_key_id]"
                               value="<?php echo esc_attr( $settings['access_key_id'] ); ?>"
                               class="regular-text"
                               <?php echo defined( 'WRENIO_R2_ACCESS_KEY_ID' ) && WRENIO_R2_ACCESS_KEY_ID ? 'readonly' : ''; ?> />
                        <p class="description"><?php echo esc_html__( 'R2 API Token Access Key ID', 'wrenio-media-offload' ); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="secret_access_key"><?php echo esc_html__( 'Secret Access Key', 'wrenio-media-offload' ); ?></label>
                    </th>
                    <td>
                        <?php
                        $wrenio_secret_readonly = defined( 'WRENIO_R2_SECRET_ACCESS_KEY' ) && WRENIO_R2_SECRET_ACCESS_KEY;
                        if ( $wrenio_secret_readonly ) {
                            $wrenio_placeholder = esc_attr__( 'Set in wp-config.php', 'wrenio-media-offload' );
                        } elseif ( $has_secret ) {
                            $wrenio_placeholder = '••••••••••••••••';
                        } else {
                            $wrenio_placeholder = esc_attr__( 'Enter your R2 secret access key', 'wrenio-media-offload' );
                        }
                        ?>
                        <input type="password"
                               id="secret_access_key"
                               name="wrenio_media_offload_settings[secret_access_key]"
                               value=""
                               class="regular-text"
                               autocomplete="new-password"
                               placeholder="<?php echo esc_attr( $wrenio_placeholder ); ?>"
                               <?php if ( $wrenio_secret_readonly ) { echo 'readonly'; } ?> />
                        <p class="description">
                            <?php if ( $has_secret && ! ( defined( 'WRENIO_R2_SECRET_ACCESS_KEY' ) && WRENIO_R2_SECRET_ACCESS_KEY ) ) : ?>
                                <?php echo esc_html__( 'A secret is currently stored. Leave this field blank to keep it; enter a new value to replace it.', 'wrenio-media-offload' ); ?>
                            <?php else : ?>
                                <?php echo esc_html__( 'R2 API Token Secret Access Key', 'wrenio-media-offload' ); ?>
                            <?php endif; ?>
                        </p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="bucket_name"><?php echo esc_html__( 'Bucket Name', 'wrenio-media-offload' ); ?></label>
                    </th>
                    <td>
                        <input type="text" id="bucket_name" name="wrenio_media_offload_settings[bucket_name]"
                               value="<?php echo esc_attr( $settings['bucket_name'] ); ?>"
                               class="regular-text"
                               <?php echo defined( 'WRENIO_R2_BUCKET_NAME' ) && WRENIO_R2_BUCKET_NAME ? 'readonly' : ''; ?> />
                        <p class="description"><?php echo esc_html__( 'Cloudflare R2 Bucket name', 'wrenio-media-offload' ); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="public_url"><?php echo esc_html__( 'Public URL', 'wrenio-media-offload' ); ?></label>
                    </th>
                    <td>
                        <input type="url" id="public_url" name="wrenio_media_offload_settings[public_url]"
                               value="<?php echo esc_url( $settings['public_url'] ); ?>"
                               class="regular-text"
                               placeholder="https://media.example.com"
                               <?php echo defined( 'WRENIO_R2_PUBLIC_URL' ) && WRENIO_R2_PUBLIC_URL ? 'readonly' : ''; ?> />
                        <p class="description"><?php echo esc_html__( 'Custom domain or bucket public URL', 'wrenio-media-offload' ); ?></p>
                    </td>
                </tr>
            </table>

            <p>
                <button type="button" id="test-connection" class="button button-secondary"><?php echo esc_html__( 'Test Connection', 'wrenio-media-offload' ); ?></button>
                <button type="button" id="test-put" class="button button-secondary"><?php echo esc_html__( 'Test Write Access', 'wrenio-media-offload' ); ?></button>
                <span id="test-connection-result"></span>
            </p>
        </div>

        <div id="tab-features" class="tab-content" style="display: none;">
            <h2><?php echo esc_html__( 'Features', 'wrenio-media-offload' ); ?></h2>
            <table class="form-table">
                <tr>
                    <th scope="row"><?php echo esc_html__( 'Enable URL Rewrite', 'wrenio-media-offload' ); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="wrenio_media_offload_settings[enable_url_rewrite]" value="1" <?php checked( $settings['enable_url_rewrite'] ); ?> />
                            <?php echo esc_html__( 'Rewrite media URLs to point to Cloudflare R2', 'wrenio-media-offload' ); ?>
                        </label>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php echo esc_html__( 'Upload Mode', 'wrenio-media-offload' ); ?></th>
                    <td>
                        <label>
                            <input type="radio" name="wrenio_media_offload_settings[upload_mode]" value="full_only" <?php checked( ( $settings['upload_mode'] ?? 'full_only' ), 'full_only' ); ?> />
                            <?php echo esc_html__( 'Upload full-size images only (recommended)', 'wrenio-media-offload' ); ?>
                        </label>
                        <br />
                        <label>
                            <input type="radio" name="wrenio_media_offload_settings[upload_mode]" value="all_sizes" <?php checked( ( $settings['upload_mode'] ?? 'full_only' ), 'all_sizes' ); ?> />
                            <?php echo esc_html__( 'Upload all image sizes', 'wrenio-media-offload' ); ?>
                        </label>
                        <p class="description"><?php echo esc_html__( 'Full-only saves space on R2; all-sizes mirrors your local media structure exactly.', 'wrenio-media-offload' ); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php echo esc_html__( 'Delete Local Files', 'wrenio-media-offload' ); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="wrenio_media_offload_settings[delete_local_files]" value="1" <?php checked( $settings['delete_local_files'] ); ?> />
                            <?php echo esc_html__( 'Delete local files after successful upload to R2', 'wrenio-media-offload' ); ?>
                        </label>
                        <p class="description"><strong><?php echo esc_html__( 'Irreversible.', 'wrenio-media-offload' ); ?></strong> <?php echo esc_html__( 'Ensure R2 sync is complete and verified before enabling.', 'wrenio-media-offload' ); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php echo esc_html__( 'Debug Logging', 'wrenio-media-offload' ); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="wrenio_media_offload_settings[enable_debug_logging]" value="1" <?php checked( $settings['enable_debug_logging'] ); ?> />
                            <?php echo esc_html__( 'Write INFO and DEBUG log entries (ERROR and WARNING always log)', 'wrenio-media-offload' ); ?>
                        </label>
                    </td>
                </tr>
            </table>
        </div>

        <div id="tab-auto-sync" class="tab-content" style="display: none;">
            <h2><?php echo esc_html__( 'Automatic Sync', 'wrenio-media-offload' ); ?></h2>
            <?php
            $wrenio_auto_sync_enabled    = (bool) get_option( 'wrenio_media_offload_auto_sync_enabled', false );
            $wrenio_auto_sync_batch_size = (int) get_option( 'wrenio_media_offload_auto_sync_batch_size', 10 );
            $wrenio_auto_sync_interval   = get_option( 'wrenio_media_offload_auto_sync_interval', 'hourly' );
            ?>
            <table class="form-table">
                <tr>
                    <th scope="row"><?php echo esc_html__( 'Enable Auto Sync', 'wrenio-media-offload' ); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="wrenio_media_offload_auto_sync_enabled" value="1" <?php checked( $wrenio_auto_sync_enabled ); ?> />
                            <?php echo esc_html__( 'Run a background sync on schedule (handles new uploads automatically)', 'wrenio-media-offload' ); ?>
                        </label>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="auto_sync_interval"><?php echo esc_html__( 'Sync Interval', 'wrenio-media-offload' ); ?></label></th>
                    <td>
                        <select id="auto_sync_interval" name="wrenio_media_offload_auto_sync_interval">
                            <option value="wrenio_every_5_minutes"  <?php selected( $wrenio_auto_sync_interval, 'wrenio_every_5_minutes' );  ?>><?php echo esc_html__( 'Every 5 minutes', 'wrenio-media-offload' ); ?></option>
                            <option value="wrenio_every_15_minutes" <?php selected( $wrenio_auto_sync_interval, 'wrenio_every_15_minutes' ); ?>><?php echo esc_html__( 'Every 15 minutes', 'wrenio-media-offload' ); ?></option>
                            <option value="wrenio_every_30_minutes" <?php selected( $wrenio_auto_sync_interval, 'wrenio_every_30_minutes' ); ?>><?php echo esc_html__( 'Every 30 minutes', 'wrenio-media-offload' ); ?></option>
                            <option value="hourly"               <?php selected( $wrenio_auto_sync_interval, 'hourly' );               ?>><?php echo esc_html__( 'Hourly', 'wrenio-media-offload' ); ?></option>
                            <option value="twicedaily"           <?php selected( $wrenio_auto_sync_interval, 'twicedaily' );           ?>><?php echo esc_html__( 'Twice Daily', 'wrenio-media-offload' ); ?></option>
                            <option value="daily"                <?php selected( $wrenio_auto_sync_interval, 'daily' );                ?>><?php echo esc_html__( 'Daily', 'wrenio-media-offload' ); ?></option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="auto_sync_batch_size"><?php echo esc_html__( 'Batch Size', 'wrenio-media-offload' ); ?></label></th>
                    <td>
                        <input type="number" id="auto_sync_batch_size" name="wrenio_media_offload_auto_sync_batch_size"
                               value="<?php echo esc_attr( $wrenio_auto_sync_batch_size ); ?>" min="1" max="50" />
                        <p class="description"><?php echo esc_html__( 'Files processed per run (1–50)', 'wrenio-media-offload' ); ?></p>
                    </td>
                </tr>
            </table>
            <p>
                <button type="button" id="run-auto-sync" class="button button-secondary"><?php echo esc_html__( 'Run Auto Sync Now', 'wrenio-media-offload' ); ?></button>
                <span id="run-auto-sync-result"></span>
            </p>
        </div>

        <div id="tab-logs" class="tab-content" style="display: none;">
            <h2><?php echo esc_html__( 'Plugin Logs', 'wrenio-media-offload' ); ?></h2>
            <p>
                <?php
                printf(
                    /* translators: %s: log file size */
                    esc_html__( 'Current log size: %s', 'wrenio-media-offload' ),
                    '<strong>' . esc_html( $wrenio_logger->get_log_size_formatted() ) . '</strong>'
                );
                ?>
            </p>
            <textarea readonly style="width: 100%; height: 400px; font-family: monospace; font-size: 12px;"><?php echo esc_textarea( $wrenio_logger->get_log_content( 200 ) ); ?></textarea>
            <p><em><?php echo esc_html__( 'Showing last 200 lines. Debug/info entries require Debug Logging to be enabled; errors and warnings always log.', 'wrenio-media-offload' ); ?></em></p>
        </div>

        <div id="tab-debug" class="tab-content" style="display: none;">
            <h2><?php echo esc_html__( 'Debug Information', 'wrenio-media-offload' ); ?></h2>

            <p class="notice notice-info inline" style="padding: 8px 12px;">
                <?php echo esc_html__( 'Need to fix stale thumbnail data after a sync? Thumbnail regeneration runs in batches to avoid timeouts.', 'wrenio-media-offload' ); ?>
            </p>

            <p>
                <button type="button" id="fix-all-thumbnails" class="button button-secondary"><?php echo esc_html__( 'Fix All Thumbnails', 'wrenio-media-offload' ); ?></button>
                <span id="fix-thumbnails-result"></span>
            </p>
            <div id="fix-thumbnails-progress" style="display: none; margin-top: 12px;">
                <div style="background: #f0f0f1; border-radius: 4px; height: 20px; overflow: hidden;">
                    <div id="fix-thumbnails-bar" style="background: #2271b1; height: 100%; width: 0; transition: width 0.3s;"></div>
                </div>
                <p id="fix-thumbnails-status" style="margin-top: 6px;"></p>
            </div>

            <hr />

            <h3><?php echo esc_html__( 'Related tools', 'wrenio-media-offload' ); ?></h3>
            <ul>
                <li><a href="<?php echo esc_url( admin_url( 'admin.php?page=wrenio-media-offload&tab=bulk-sync' ) ); ?>"><?php echo esc_html__( '→ Bulk Sync: upload existing media to R2', 'wrenio-media-offload' ); ?></a></li>
                <li><a href="<?php echo esc_url( admin_url( 'admin.php?page=wrenio-media-offload&tab=reconcile' ) ); ?>"><?php echo esc_html__( '→ R2 Reconcile: align existing R2 object keys with local paths', 'wrenio-media-offload' ); ?></a></li>
                <li><a href="<?php echo esc_url( admin_url( 'admin.php?page=wrenio-media-offload&tab=filename-cleanup' ) ); ?>"><?php echo esc_html__( '→ Filename Cleanup: repair filename mismatches between WP and R2', 'wrenio-media-offload' ); ?></a></li>
                <li><a href="<?php echo esc_url( admin_url( 'admin.php?page=wrenio-media-offload&tab=orphan-cleanup' ) ); ?>"><?php echo esc_html__( '→ Orphan Cleanup: delete R2 objects not referenced by any attachment', 'wrenio-media-offload' ); ?></a></li>
            </ul>

            <hr />

            <?php $this->show_debug_info(); ?>
        </div>

        <p class="submit">
            <button type="submit" name="submit" class="button button-primary"><?php echo esc_html__( 'Save Settings', 'wrenio-media-offload' ); ?></button>
        </p>
    </form>
</div>
