<?php
/**
 * Admin UI for Doli Training Management.
 *
 * @package DoliTrainingManagement
 */

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

/**
 * Registers the standalone admin menu, settings, and documentation.
 */
class Doli_Training_Management_Admin {

    /**
     * Constructor.
     */
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_init', array($this, 'register_settings'));
    }

    /**
     * Top-level menu with training icon and subpages.
     */
    public function add_admin_menu() {
        add_menu_page(
            __('Doli Training Management', 'doli-training-management'),
            __('Doli Training', 'doli-training-management'),
            'manage_options',
            'doli-training-management',
            array($this, 'render_settings_page'),
            'dashicons-welcome-learn-more',
            30
        );

        add_submenu_page(
            'doli-training-management',
            __('Settings', 'doli-training-management'),
            __('Settings', 'doli-training-management'),
            'manage_options',
            'doli-training-management',
            array($this, 'render_settings_page')
        );

        add_submenu_page(
            'doli-training-management',
            __('Documentation', 'doli-training-management'),
            __('Documentation', 'doli-training-management'),
            'manage_options',
            'doli-training-management-doc',
            array($this, 'render_documentation_page')
        );
    }

    /**
     * Register options (used with Settings API where applicable).
     */
    public function register_settings() {
        register_setting(
            'doli_training_management_settings',
            'doli_training_management_dolibarr_url',
            array(
                'sanitize_callback' => 'esc_url_raw',
                'type'              => 'string',
                'default'           => '',
            )
        );
        register_setting(
            'doli_training_management_settings',
            'doli_training_management_dolibarr_api_key',
            array(
                'sanitize_callback' => 'sanitize_text_field',
                'type'              => 'string',
                'default'           => '',
            )
        );
    }

    /**
     * Settings screen.
     */
    public function render_settings_page() {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to access this page.', 'doli-training-management'));
        }

        if ($this->is_settings_form_submitted()) {
            $this->save_settings();
        }

        $dolibarr_url = get_option('doli_training_management_dolibarr_url', '');
        $api_key      = get_option('doli_training_management_dolibarr_api_key', '');

        include DOLI_TRAINING_MANAGEMENT_PLUGIN_DIR . 'templates/admin/settings.php';
    }

    /**
     * Documentation screen.
     */
    public function render_documentation_page() {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to access this page.', 'doli-training-management'));
        }

        include DOLI_TRAINING_MANAGEMENT_PLUGIN_DIR . 'templates/admin/documentation.php';
    }

    /**
     * Whether the settings form was POSTed with a valid nonce.
     */
    private function is_settings_form_submitted() {
        if (!isset($_POST['doli_training_management_settings_submit'], $_POST['_wpnonce'])) {
            return false;
        }

        return wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'doli_training_management_settings_save');
    }

    /**
     * Persist settings after capability and nonce checks.
     */
    private function save_settings() {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to save these settings.', 'doli-training-management'));
        }

        if (!isset($_POST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'doli_training_management_settings_save')) {
            wp_die(esc_html__('Security check failed. Please try again.', 'doli-training-management'));
        }

        $url = isset($_POST['doli_training_management_dolibarr_url']) ? esc_url_raw(wp_unslash($_POST['doli_training_management_dolibarr_url'])) : '';
        $key = isset($_POST['doli_training_management_dolibarr_api_key']) ? sanitize_text_field(wp_unslash($_POST['doli_training_management_dolibarr_api_key'])) : '';
        $key = trim($key);

        update_option('doli_training_management_dolibarr_url', $url);
        // Password field is often left blank on "save other settings" — do not wipe a previously stored key.
        if ($key !== '') {
            update_option('doli_training_management_dolibarr_api_key', $key);
        }

        add_settings_error(
            'doli_training_management_settings',
            'doli_training_management_settings_saved',
            __('Settings saved.', 'doli-training-management'),
            'updated'
        );
    }
}
