| 1 |
<?php namespace TierPricingTable\Admin\Tips; |
| 2 |
|
| 3 |
use TierPricingTable\Core\ServiceContainerTrait; |
| 4 |
|
| 5 |
/** |
| 6 |
* Class Tip |
| 7 |
* |
| 8 |
* @package TierPricingTable\Admin\Tips |
| 9 |
*/ |
| 10 |
abstract class Tip { |
| 11 |
|
| 12 |
use ServiceContainerTrait; |
| 13 |
|
| 14 |
const SEEN_TIPS_OPTION_KEY = 'tiered_pricing_seen_tips'; |
| 15 |
const AJAX_ACTION = 'tiered_pricing_set_tip_as_seen'; |
| 16 |
|
| 17 |
public function __construct() { |
| 18 |
add_action( 'wp_ajax_' . self::AJAX_ACTION, array( $this, 'handleAjax' ) ); |
| 19 |
} |
| 20 |
|
| 21 |
public function handleAjax() { |
| 22 |
|
| 23 |
if ( ! current_user_can( 'manage_options' ) ) { |
| 24 |
wp_send_json_error( array( 'message' => 'Unauthorized' ) ); |
| 25 |
} |
| 26 |
|
| 27 |
$nonce = isset( $_REQUEST['nonce'] ) ? sanitize_text_field( $_REQUEST['nonce'] ) : false; |
| 28 |
$slug = isset( $_REQUEST['slug'] ) ? sanitize_text_field( $_REQUEST['slug'] ) : false; |
| 29 |
|
| 30 |
if ( ! wp_verify_nonce( $nonce, self::AJAX_ACTION ) ) { |
| 31 |
wp_send_json_error( array( 'message' => 'Invalid nonce' ) ); |
| 32 |
} |
| 33 |
|
| 34 |
if ( ! $slug ) { |
| 35 |
wp_send_json_error( array( 'message' => 'Invalid slug' ) ); |
| 36 |
} |
| 37 |
|
| 38 |
$tip = TipsManager::getTipBySlug( $slug ); |
| 39 |
|
| 40 |
if ( ! $tip ) { |
| 41 |
wp_send_json_error( array( 'message' => 'Tip not found' ) ); |
| 42 |
} |
| 43 |
|
| 44 |
$tip->markAsSeen(); |
| 45 |
|
| 46 |
wp_send_json_success( array( 'message' => 'Tip marked as seen' ) ); |
| 47 |
} |
| 48 |
|
| 49 |
abstract public function getSlug(): string; |
| 50 |
|
| 51 |
public function isSeen(): bool { |
| 52 |
return in_array( $this->getSlug(), self::getSeenTips() ); |
| 53 |
} |
| 54 |
|
| 55 |
public function markAsSeen(): bool { |
| 56 |
if ( $this->isSeen() ) { |
| 57 |
return true; |
| 58 |
} |
| 59 |
|
| 60 |
$seenTips = self::getSeenTips(); |
| 61 |
$seenTips[] = $this->getSlug(); |
| 62 |
|
| 63 |
return update_option( self::SEEN_TIPS_OPTION_KEY, $seenTips ); |
| 64 |
} |
| 65 |
|
| 66 |
public function getMarkAsSeenURL(): string { |
| 67 |
return add_query_arg( array( |
| 68 |
'action' => self::AJAX_ACTION, |
| 69 |
'slug' => $this->getSlug(), |
| 70 |
'nonce' => wp_create_nonce( self::AJAX_ACTION ), |
| 71 |
), admin_url( 'admin-ajax.php' ) ); |
| 72 |
} |
| 73 |
|
| 74 |
public static function getSeenTips(): array { |
| 75 |
return array_filter( (array) get_option( self::SEEN_TIPS_OPTION_KEY, array() ) ); |
| 76 |
} |
| 77 |
} |
| 78 |
|