<?php

namespace SWPanel\Pages;

defined('ABSPATH') || die('No direct access.');

use SWPanel\SettingsManager;

class TokenPage {
    public function __construct() {
        add_action('admin_menu', [$this, 'register']);
        add_action('admin_post_swpanel_ai_token_form', [$this, 'handleSubmit']);
    }

    public function register() {
        add_submenu_page(null, __('SWPanel Token', 'swpanel-ai'), __('SWPanel Token', 'swpanel-ai'), 'manage_options', 'swpanel_ai_token', [$this, 'render']);
    }

    public function render() {        
        include SWPANEL_PATH . 'admin/views/token-form.php';
    }

    public function handleSubmit() {
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ) : '';
        if ( ! $nonce || ! wp_verify_nonce( $nonce, 'swpanel_ai_token' ) ) {
            wp_die( 'Invalid nonce' );
        }

        SettingsManager::saveBearerToken($_POST);

        wp_redirect(admin_url('admin.php?page=swpanel_ai'));
        exit;
    }
}
