<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class woo2app_metabox_notif
{
	function __construct()
	{
		add_action( 'add_meta_boxes', array($this , 'woo2app_metabox_notif_add') );
		add_action( 'save_post', array($this , 'woo2app_metabox_notif_save') );
		add_filter( 'excerpt_length', array($this , 'wp2appir_excerpt_length'), 999 );
	}
	function woo2app_metabox_notif_add()
	{
		add_meta_box( 'notif-woo-meta-box-id',
			'Send with notifications (woo2app)',
			array($this , 'woo2app_notif_meta_box_design'),
			'product',
			'side',
			'high' );
	}
	function woo2app_notif_meta_box_design()
	{
		wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );
		?>
        <p>
            <input type="radio" name="notify" value="1"> <?php _e('Send mute', 'woo2app'); ?><br>
            <input type="radio" name="notify" value="2"><?php _e('Send unmute', 'woo2app'); ?>e<br>
            <input type="radio" name="notify" value="0" checked><?php _e('Not sending', 'woo2app'); ?>
        </p>
		<?php
	}
	function woo2app_metabox_notif_save( $post_id ){
		// Bail if we're doing an auto save
		if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
		// if our nonce isn't there, or we can't verify it, bail
		if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;
		// if our current user can't edit this post, bail
		if( !current_user_can( 'edit_post' ) ) return;


		$notif_type = get_option('notification_type');

		if(isset($_POST['notify']) && get_post_status($post_id)== "publish" && $_POST['notify'] != 0){
			if($notif_type == 'direct'){
				$r = send_notif(get_the_title($post_id) , $_POST["notify"] , 4 , $post_id);
				$r = json_decode($r , true);
			}
			else{
				$r = send_notif_mr2app( get_the_title($post_id) , $_POST["notify"] , 4 , $post_id);
				$r = json_decode($r , true);
			}
		}
	}

	function woo2app_excerpt( $post )
	{
		$text = $post->post_content;
		$text = strip_shortcodes( $text );
		$text = apply_filters( 'the_content', $text );
		$text = str_replace( ']]>', ']]>', $text );
		$excerpt_length = apply_filters( 'excerpt_length', 55 );
		$excerpt_more   = apply_filters( 'excerpt_more', ' ' . '[...]' );
		$text           = wp_trim_words( $text, $excerpt_length, '' );
		return $text;
	}
	function wp2appir_excerpt_length( $length ) {
		return 20;
	}
}