<?php
/**
 * Prevent direct access to the file
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Class WOSR_Delete_Data
 *
 * Handles the "Delete Plugin Data Permission" tab in the plugin settings.
 * This allows administrators to decide whether plugin data should be
 * permanently deleted when the plugin is uninstalled.
 */
class WOSR_Delete_Data {

    /**
     * Constructor
     *
     * Hooks into WordPress to render the tab and register settings.
     */
    public function __construct() {
        // Hook into the custom action to render this specific settings tab
        add_action( 'wosr_render_tab_delete_wosr_settings_on_uninstall', array( $this, 'render_tab' ) );

        // Register the plugin setting so it is saved/validated by WordPress
        add_action( 'admin_init', array( $this, 'register_setting' ) );
    }

    /**
     * Register the setting with WordPress
     *
     * - Setting name: wosr_delete_data_on_uninstall
     * - Group: wosr_settings_group
     * - Default: '0' (data NOT deleted by default)
     * - Sanitization: sanitize_text_field
     */
    public function register_setting() {
        register_setting(
            'wosr_settings_group', // The settings group
            'wosr_delete_data_on_uninstall', // The option name
            array(
                'type'              => 'string',
                'sanitize_callback' => 'sanitize_text_field',
                'default'           => '0',
            )
        );
    }

    /**
     * Render the settings tab content
     *
     * Displays a checkbox allowing the admin to choose whether
     * plugin data should be deleted upon uninstall.
     */
    public function render_tab() {
        // Get current option value, default to '0' if not set
        $value = get_option( 'wosr_delete_data_on_uninstall', '0' );
        ?>
        <h3 class="header-h3">
            <?php esc_html_e( 'Delete Plugin Data Permission', 'order-role-manager-for-woocommerce' ); ?>
        </h3>

        <form method="post" action="options.php">
            <?php 
            // Output nonce, action, and option_page fields for settings
            settings_fields( 'wosr_settings_group' ); 
            ?>
            <label>
                <input type="checkbox" 
                       name="wosr_delete_data_on_uninstall" 
                       value="1" 
                       <?php checked( '1', $value ); ?>>
                <?php esc_html_e( 'Delete plugin data on uninstall.', 'order-role-manager-for-woocommerce' ); ?>
            </label>

            <?php 
            // Outputs a "Save Changes" button
            submit_button(); 
            ?>
        </form>
        <?php
    }
}

// Initialize the class so it runs
new WOSR_Delete_Data();