| 1 |
<?php |
| 2 |
namespace BTNB; |
| 3 |
|
| 4 |
if ( !defined( 'ABSPATH' ) ) { exit; } |
| 5 |
|
| 6 |
/** |
| 7 |
* Options class |
| 8 |
* Handles plugin options and related AJAX requests. |
| 9 |
* |
| 10 |
* @package BTN |
| 11 |
*/ |
| 12 |
class Options { |
| 13 |
/** |
| 14 |
* Constructor. |
| 15 |
* Registers options-related hooks. |
| 16 |
*/ |
| 17 |
public function __construct() { |
| 18 |
add_action( 'wp_ajax_btnSaveUninstallOption', [ $this, 'saveUninstallOption' ] ); |
| 19 |
} |
| 20 |
|
| 21 |
/** |
| 22 |
* Retrieves all plugin options, merged with defaults. |
| 23 |
* |
| 24 |
* @return array The plugin options. |
| 25 |
*/ |
| 26 |
public static function getOptions() { |
| 27 |
$defaults = [ |
| 28 |
'delete_data_on_uninstall' => false, |
| 29 |
]; |
| 30 |
|
| 31 |
$options = get_option( BTNB_OPTIONS_KEY, [] ); |
| 32 |
|
| 33 |
return wp_parse_args( $options, $defaults ); |
| 34 |
} |
| 35 |
|
| 36 |
/** |
| 37 |
* Updates plugin options. |
| 38 |
* |
| 39 |
* @param array $new_options The options to update. |
| 40 |
* @return bool True on success, false on failure. |
| 41 |
*/ |
| 42 |
public static function updateOptions( $new_options ) { |
| 43 |
$options = self::getOptions(); |
| 44 |
$updated_options = array_merge( $options, $new_options ); |
| 45 |
return update_option( BTNB_OPTIONS_KEY, $updated_options ); |
| 46 |
} |
| 47 |
|
| 48 |
/** |
| 49 |
* Saves the "delete data on uninstall" option via AJAX. |
| 50 |
* |
| 51 |
* @return void |
| 52 |
*/ |
| 53 |
public function saveUninstallOption() { |
| 54 |
check_ajax_referer( 'btnSaveUninstallOption', 'nonce' ); |
| 55 |
|
| 56 |
if ( ! current_user_can( 'manage_options' ) ) { |
| 57 |
wp_send_json_error( __( 'Permission denied.', 'button-block' ) ); |
| 58 |
} |
| 59 |
|
| 60 |
$enabled = isset( $_POST['enabled'] ) && 'true' === sanitize_text_field( wp_unslash( $_POST['enabled'] ) ); |
| 61 |
|
| 62 |
self::updateOptions( [ 'delete_data_on_uninstall' => $enabled ] ); |
| 63 |
|
| 64 |
wp_send_json_success( [ |
| 65 |
'enabled' => $enabled, |
| 66 |
'message' => $enabled |
| 67 |
? __( 'All plugin data will be deleted when uninstalled.', 'button-block' ) |
| 68 |
: __( 'Plugin data will be preserved when uninstalled.', 'button-block' ) |
| 69 |
] ); |
| 70 |
} |
| 71 |
} |
| 72 |
new Options(); |
| 73 |
|