<?php
if (!defined('ABSPATH')) {
    exit;
}

class BMTQB_License_Manager {
    const OPTION_NAME = 'bmtqb_license_settings';

    private $industries = [];

    public function __construct() {
        add_action('admin_init', [$this, 'register_settings']);
        add_action('admin_menu', [$this, 'add_menu'], 30);
    }

    public function register_industry(BMTQB_Industry_Interface $industry) {
        $this->industries[$industry->key()] = $industry;
    }

    public function register_settings() {
        register_setting('bmtqb_license_settings_group', self::OPTION_NAME, [
            'sanitize_callback' => [$this, 'sanitize'],
        ]);
    }

    public function add_menu() {
        add_submenu_page(
            'options-general.php',
            'Quote Updates & License',
            'Quote Updates',
            BMTQB_Capabilities::MANAGE_UPDATES,
            'bmtqb-updates',
            [$this, 'render_page']
        );

        foreach ($this->industries as $industry) {
            add_submenu_page(
                $industry->settings_menu_slug(),
                'Quote Updates & License',
                'Updates',
                BMTQB_Capabilities::MANAGE_UPDATES,
                'bmtqb-updates',
                [$this, 'render_page']
            );
        }
    }

    public function sanitize($input) {
        $input = is_array($input) ? $input : [];

        return [
            'license_code' => sanitize_text_field($input['license_code'] ?? ''),
            'channel' => sanitize_key($input['channel'] ?? 'stable'),
        ];
    }

    public function settings() {
        $settings = get_option(self::OPTION_NAME, []);
        return is_array($settings) ? array_merge(['license_code' => '', 'channel' => 'stable'], $settings) : ['license_code' => '', 'channel' => 'stable'];
    }

    public function license_code() {
        $settings = $this->settings();
        return trim((string) $settings['license_code']);
    }

    public function has_license_code() {
        return $this->license_code() !== '';
    }

    public function channel() {
        $settings = $this->settings();
        return $settings['channel'] ?: 'stable';
    }

    public function redacted_license_code() {
        $code = $this->license_code();
        if ($code === '') {
            return '';
        }

        return '•••• ' . substr($code, -4);
    }

    public function render_page() {
        if (!current_user_can(BMTQB_Capabilities::MANAGE_UPDATES)) {
            wp_die(esc_html__('You do not have permission to manage quote updates.', 'better-mousetrap-quote-base'));
        }

        $settings = $this->settings();
        ?>
        <div class="wrap">
            <h1>Quote Updates & License</h1>
            <form method="post" action="options.php">
                <?php settings_fields('bmtqb_license_settings_group'); ?>
                <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row"><label for="bmtqb-license-code">License Code</label></th>
                        <td>
                            <input type="password" id="bmtqb-license-code" name="<?php echo esc_attr(self::OPTION_NAME); ?>[license_code]" value="<?php echo esc_attr($settings['license_code']); ?>" class="regular-text">
                            <p class="description">A saved code enables plugin update checks and downloads.</p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="bmtqb-channel">Update Channel</label></th>
                        <td>
                            <select id="bmtqb-channel" name="<?php echo esc_attr(self::OPTION_NAME); ?>[channel]">
                                <?php foreach (['stable', 'beta', 'dev'] as $channel) : ?>
                                    <option value="<?php echo esc_attr($channel); ?>" <?php selected($settings['channel'], $channel); ?>><?php echo esc_html(ucfirst($channel)); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                    </tr>
                </table>
                <?php submit_button('Save License Settings'); ?>
            </form>
        </div>
        <?php
    }
}
