<?php

declare(strict_types=1);

namespace UFPE\GoogleOIDC;

final class AdminSettings
{
    private Config $config;

    public function __construct(Config $config)
    {
        $this->config = $config;
    }

    public function register(): void
    {
        add_action('admin_init', [$this, 'registerSettings']);
        add_action('admin_menu', [$this, 'menu']);
    }

    public function registerSettings(): void
    {
        register_setting('ufpe_google_oidc', Config::OPTION, [
            'type' => 'array',
            'sanitize_callback' => [$this, 'sanitize'],
        ]);
    }

    public function menu(): void
    {
        add_options_page(
            'UFPE Google OIDC',
            'UFPE Google OIDC',
            'manage_options',
            'ufpe-google-oidc',
            [$this, 'render']
        );
    }

    public function sanitize(array $input): array
    {
        $defaults = Config::defaults();

        return [
            'client_id' => sanitize_text_field((string) ($input['client_id'] ?? $defaults['client_id'])),
            'client_secret' => sanitize_text_field((string) ($input['client_secret'] ?? $defaults['client_secret'])),
            'allowed_domain' => sanitize_text_field((string) ($input['allowed_domain'] ?? $defaults['allowed_domain'])),
            'primary_admin_email' => sanitize_email((string) ($input['primary_admin_email'] ?? $defaults['primary_admin_email'])),
            'administrator_emails' => $this->sanitizeEmailList((string) ($input['administrator_emails'] ?? $defaults['administrator_emails'])),
            'auto_provision' => ! empty($input['auto_provision']) ? '1' : '0',
            'default_role' => sanitize_key((string) ($input['default_role'] ?? $defaults['default_role'])),
            'link_existing_by_email' => ! empty($input['link_existing_by_email']) ? '1' : '0',
            'restrict_password_login' => ! empty($input['restrict_password_login']) ? '1' : '0',
        ];
    }

    private function sanitizeEmailList(string $value): string
    {
        $raw = preg_split('/[\s,;]+/', strtolower($value));
        $emails = array_filter(array_map('sanitize_email', is_array($raw) ? $raw : []));

        return implode("\n", array_values(array_unique($emails)));
    }

    public function render(): void
    {
        if (! current_user_can('manage_options')) {
            return;
        }

        $settings = $this->config->all();
        ?>
        <div class="wrap">
            <h1>UFPE Google OIDC</h1>
            <p>Redirect URI no Google Cloud: <code><?php echo esc_html($this->config->redirectUri()); ?></code></p>
            <form method="post" action="options.php">
                <?php settings_fields('ufpe_google_oidc'); ?>
                <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row"><label for="client_id">Google Client ID</label></th>
                        <td><input class="regular-text" id="client_id" name="<?php echo esc_attr(Config::OPTION); ?>[client_id]" value="<?php echo esc_attr($settings['client_id']); ?>"></td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="client_secret">Google Client Secret</label></th>
                        <td><input class="regular-text" type="password" id="client_secret" name="<?php echo esc_attr(Config::OPTION); ?>[client_secret]" value="<?php echo esc_attr($settings['client_secret']); ?>"></td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="allowed_domain">Dominio permitido</label></th>
                        <td><input class="regular-text" id="allowed_domain" name="<?php echo esc_attr(Config::OPTION); ?>[allowed_domain]" value="<?php echo esc_attr($settings['allowed_domain']); ?>"></td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="primary_admin_email">Conta principal</label></th>
                        <td><input class="regular-text" id="primary_admin_email" name="<?php echo esc_attr(Config::OPTION); ?>[primary_admin_email]" value="<?php echo esc_attr($settings['primary_admin_email']); ?>"></td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="administrator_emails">Administradores Google</label></th>
                        <td><textarea class="large-text code" rows="4" id="administrator_emails" name="<?php echo esc_attr(Config::OPTION); ?>[administrator_emails]"><?php echo esc_textarea($settings['administrator_emails']); ?></textarea></td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="default_role">Role padrao</label></th>
                        <td><input class="regular-text" id="default_role" name="<?php echo esc_attr(Config::OPTION); ?>[default_role]" value="<?php echo esc_attr($settings['default_role']); ?>"></td>
                    </tr>
                    <tr>
                        <th scope="row">Politica</th>
                        <td>
                            <label><input type="checkbox" name="<?php echo esc_attr(Config::OPTION); ?>[auto_provision]" value="1" <?php checked($settings['auto_provision'], '1'); ?>> provisionar usuario no primeiro login</label><br>
                            <label><input type="checkbox" name="<?php echo esc_attr(Config::OPTION); ?>[link_existing_by_email]" value="1" <?php checked($settings['link_existing_by_email'], '1'); ?>> vincular conta local existente por e-mail verificado</label><br>
                            <label><input type="checkbox" name="<?php echo esc_attr(Config::OPTION); ?>[restrict_password_login]" value="1" <?php checked($settings['restrict_password_login'], '1'); ?>> bloquear senha local exceto admins de contingencia marcados</label>
                        </td>
                    </tr>
                </table>
                <?php submit_button(); ?>
            </form>
        </div>
        <?php
    }
}
