<?php
namespace FlysystemOffload\Admin;

class SettingsPage
{
    private string $pluginFile;

    public function __construct(string $pluginFile)
    {
        $this->pluginFile = $pluginFile;
    }

    public function boot(): void
    {
        add_action('admin_menu', [$this, 'registerPage']);
        add_action('admin_init', [$this, 'registerSettings']);
        add_action('admin_enqueue_scripts', [$this, 'enqueueAssets']);
    }

    public function registerPage(): void
    {
        add_options_page(
            __('Flysystem Offload', 'flysystem-offload'),
            __('Flysystem Offload', 'flysystem-offload'),
            'manage_options',
            'flysystem-offload',
            [$this, 'render']
        );
    }

    public function registerSettings(): void
    {
        register_setting(
            'flysystem_offload',
            'flysystem_offload_settings',
            [
                'sanitize_callback' => [$this, 'sanitizeSettings'],
            ]
        );

        add_settings_section(
            'flysystem_offload_general',
            __('Configuración general', 'flysystem-offload'),
            '__return_false',
            'flysystem-offload'
        );

        add_settings_field(
            'adapter',
            __('Adaptador activo', 'flysystem-offload'),
            [$this, 'renderAdapterField'],
            'flysystem-offload',
            'flysystem_offload_general'
        );

        add_settings_field(
            'base_prefix',
            __('Prefijo de almacenamiento', 'flysystem-offload'),
            [$this, 'renderBasePrefixField'],
            'flysystem-offload',
            'flysystem_offload_general'
        );

        add_settings_section(
            'flysystem_offload_s3',
            __('Amazon S3 / Compatible', 'flysystem-offload'),
            function () {
                echo '<p>' . esc_html__('Proporciona credenciales de un bucket S3 o compatible (MinIO, DigitalOcean Spaces, etc.).', 'flysystem-offload') . '</p>';
            },
            'flysystem-offload'
        );

        $this->registerS3Fields();
    }

    private function registerS3Fields(): void
    {
        $fields = [
            [
                'id'    => 's3_access_key',
                'label' => __('Access Key', 'flysystem-offload'),
                'args'  => ['key' => 'access_key', 'type' => 'text'],
            ],
            [
                'id'    => 's3_secret_key',
                'label' => __('Secret Key', 'flysystem-offload'),
                'args'  => ['key' => 'secret_key', 'type' => 'password'],
            ],
            [
                'id'    => 's3_region',
                'label' => __('Región', 'flysystem-offload'),
                'args'  => ['key' => 'region', 'type' => 'text', 'placeholder' => 'us-east-1'],
            ],
            [
                'id'    => 's3_bucket',
                'label' => __('Bucket', 'flysystem-offload'),
                'args'  => ['key' => 'bucket', 'type' => 'text'],
            ],
            [
                'id'    => 's3_prefix',
                'label' => __('Prefijo (opcional)', 'flysystem-offload'),
                'args'  => ['key' => 'prefix', 'type' => 'text', 'placeholder' => 'uploads'],
            ],
            [
                'id'    => 's3_endpoint',
                'label' => __('Endpoint personalizado', 'flysystem-offload'),
                'args'  => ['key' => 'endpoint', 'type' => 'text', 'placeholder' => 'https://nyc3.digitaloceanspaces.com'],
            ],
            [
                'id'    => 's3_cdn_url',
                'label' => __('URL CDN (opcional)', 'flysystem-offload'),
                'args'  => ['key' => 'cdn_url', 'type' => 'text', 'placeholder' => 'https://cdn.midominio.com'],
            ],
        ];

        foreach ($fields as $field) {
            $args = array_merge(
                $field['args'],
                ['class' => 'flysystem-offload-field flysystem-offload-field--s3']
            );

            add_settings_field(
                $field['id'],
                $field['label'],
                [$this, 'renderS3Field'],
                'flysystem-offload',
                'flysystem_offload_s3',
                $args
            );
        }
    }

    public function enqueueAssets(): void
    {
        $screen = get_current_screen();

        if (! $screen || $screen->id !== 'settings_page_flysystem-offload') {
            return;
        }

        wp_enqueue_script(
            'flysystem-offload-settings',
            plugins_url('assets/admin-settings.js', $this->pluginFile),
            ['jquery'],
            '0.1.1',
            true
        );

        wp_localize_script(
            'flysystem-offload-settings',
            'flysystemOffloadSettings',
            [
                'labels' => [
                    's3' => __('Amazon S3 / Compatible', 'flysystem-offload'),
                ],
            ]
        );
    }

    public function sanitizeSettings(array $input): array
    {
        $current    = get_option('flysystem_offload_settings', []);
        $adapter    = sanitize_key($input['adapter'] ?? $current['adapter'] ?? 'local');
        $basePrefix = trim($input['base_prefix'] ?? '');

        $s3      = $current['adapters']['s3'] ?? [];
        $inputS3 = $input['adapters']['s3'] ?? [];

        $secretRaw = $inputS3['secret_key'] ?? '';
        $secret    = $secretRaw === '' ? ($s3['secret_key'] ?? '') : $secretRaw;

        $sanitizedS3 = [
            'access_key' => sanitize_text_field($inputS3['access_key'] ?? $s3['access_key'] ?? ''),
            'secret_key' => sanitize_text_field($secret),
            'region'     => sanitize_text_field($inputS3['region'] ?? $s3['region'] ?? ''),
            'bucket'     => sanitize_text_field($inputS3['bucket'] ?? $s3['bucket'] ?? ''),
            'prefix'     => trim($inputS3['prefix'] ?? $s3['prefix'] ?? ''),
            'endpoint'   => esc_url_raw($inputS3['endpoint'] ?? $s3['endpoint'] ?? ''),
            'cdn_url'    => esc_url_raw($inputS3['cdn_url'] ?? $s3['cdn_url'] ?? ''),
        ];

        $current['adapter']            = $adapter;
        $current['base_prefix']        = $basePrefix;
        $current['adapters']['s3']     = $sanitizedS3;

        return $current;
    }

    public function render(): void
    {
        ?>
        <div class="wrap">
            <h1><?php esc_html_e('Flysystem Offload', 'flysystem-offload'); ?></h1>
            <form method="post" action="options.php">
                <?php
                settings_fields('flysystem_offload');
                do_settings_sections('flysystem-offload');
                submit_button(__('Guardar cambios', 'flysystem-offload'));
                ?>
            </form>
        </div>
        <?php
    }

    public function renderAdapterField(): void
    {
        $settings = get_option('flysystem_offload_settings', []);
        $adapter  = $settings['adapter'] ?? 'local';

        $options = [
            'local'      => __('Local (fallback)', 'flysystem-offload'),
            's3'         => __('Amazon S3 / Compatible', 'flysystem-offload'),
            'sftp'       => 'SFTP',
            'webdav'     => 'WebDAV',
            'gcs'        => 'Google Cloud Storage',
            'azure'      => 'Azure Blob Storage',
            'googledrive'=> 'Google Drive (beta)',
            'onedrive'   => 'OneDrive (beta)',
            'dropbox'    => 'Dropbox (beta)',
        ];
        ?>
        <select name="flysystem_offload_settings[adapter]" id="flysystem-offload-adapter">
            <?php foreach ($options as $value => $label) : ?>
                <option value="<?php echo esc_attr($value); ?>" <?php selected($adapter, $value); ?>>
                    <?php echo esc_html($label); ?>
                </option>
            <?php endforeach; ?>
        </select>
        <?php
    }

    public function renderBasePrefixField(): void
    {
        $settings = get_option('flysystem_offload_settings', []);
        $prefix   = $settings['base_prefix'] ?? '';
        ?>
        <input
            type="text"
            name="flysystem_offload_settings[base_prefix]"
            value="<?php echo esc_attr($prefix); ?>"
            placeholder="media/"
            class="regular-text"
        />
        <p class="description">
            <?php esc_html_e('Opcional. Se antepone a todas las rutas remotas (ej. "wordpress/uploads").', 'flysystem-offload'); ?>
        </p>
        <?php
    }

    public function renderS3Field(array $args): void
    {
        $settings    = get_option('flysystem_offload_settings', []);
        $s3          = $settings['adapters']['s3'] ?? [];
        $key         = $args['key'];
        $type        = $args['type'] ?? 'text';
        $placeholder = $args['placeholder'] ?? '';
        $value       = $s3[$key] ?? '';

        if ($type === 'password') {
            $value = '';
        }
        ?>
        <input
            type="<?php echo esc_attr($type); ?>"
            name="flysystem_offload_settings[adapters][s3][<?php echo esc_attr($key); ?>]"
            value="<?php echo esc_attr($value); ?>"
            class="regular-text"
            placeholder="<?php echo esc_attr($placeholder); ?>"
            autocomplete="off"
        />
        <?php if ('secret_key' === $key) : ?>
            <p class="description">
                <?php esc_html_e('La clave no se mostrará después de guardarla.', 'flysystem-offload'); ?>
            </p>
        <?php endif;
    }
}
