<?php

/**
 * Main plugin class
 */
class okewa_main {

	/**
	 * @var object $ui
	 */
	public $ui;


	/**
	 * Dump everything for this plugin here :p
	 *
	 * @since 1.0
	 */
	public function __construct() {

		// User interfaces object
		$this->ui = new okewa_ui;

		// Pull stored data
		$this->settings = get_option( 'okewa_settings' );

		// Plugin text domain
		add_action( 'init', array( $this, 'okewa_textdomain' ) );		
		
		// Redirection CPT
		add_action( 'init', array( $this, 'okewa_redirection_cpt' ) );
		add_action( 'admin_menu', array( $this, 'okewa_redirection_submenu' ), 11 ) ;
		add_filter( 'parent_file', array( $this, 'okewa_redirection_parent' ) );		
		add_filter( 'single_template', array( $this, 'load_okewa_redirection_template' ), 99 );
		add_action( 'add_meta_boxes_wa', array( $this, 'okewa_add_meta_boxes' ) );
		add_action( 'save_post_wa', array( $this, 'okewa_save_meta_box_data' ) );

		// Register settings
		add_action( 'admin_init', array( $this, 'okewa_register_settings' ) );

		// Admin menu
		add_action( 'admin_menu', array( $this, 'okewa_admin_menu' ) );

		// Admin assets
		add_action( 'admin_enqueue_scripts', array( $this, 'okewa_admin_assets' ) );

		// Admin notices
		add_action( 'admin_notices', array( $this, 'okewa_admin_notices' ) );

		// Icons UI
		add_action( 'wp_footer', array( $this->ui, 'icons' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'okewa_ui_assets' ) );
		
		// Woocommerce
        if ( isset( $this->settings['woo_btn'] ) ) {
    		add_action( 'woocommerce_after_add_to_cart_button', array( $this, 'whatsapp_order_btn' ) );
        }
		if ( isset( $this->settings['woo_disable_atc'] ) ) {
            add_action( 'woocommerce_single_product_summary', array( $this, 'remove_add_to_cart_buttons' ) );
		}
		if ( isset( $this->settings['woo_confirm'] ) ) {
    	    add_action( 'woocommerce_email_after_order_table', array( $this, 'whatsapp_confirm_btn' ) );
		}
		
		// Post Sharing
		if ( isset( $this->settings['post_btn'] ) ) {
    		add_filter('the_content', array( $this,'whatsapp_share_btn') );
		}
		
		// Shortcodes
		add_shortcode('okewa', array( $this,'okewa_button') );
		add_shortcode('okewa-open', array( $this,'okewa_opener') );
		
	}



	/**
	 * Load text domain
	 *
	 * @since 1.0
	 */
	public function okewa_textdomain() {

		load_plugin_textdomain( 'okewa-text-domain', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );

	}


	/**
	 * Register settings
	 *
	 * @since 1.0
	 */
	public function okewa_register_settings() {

		register_setting( 'okewa_storage', 'okewa_settings' );
		register_setting( 'okewa_storage', 'okewa_agents' );

	}


	/**
	 * Admin menu
	 *
	 * @since 1.0
	 */
	public function okewa_admin_menu() {

		add_menu_page(
			__( 'OKEWA - Ultimate Whatsapp Chat Widget', 'okewa-text-domain' ),
			__( 'OKEWA', 'okewa-text-domain' ),
			'manage_options',
			'okewa',
			array(
				$this->ui,
				'admin_page'
			),
			plugins_url( 'assets/img/okewa.png' , __FILE__ )
		);

	}


	/**
	 * Admin style
	 *
	 * @since 1.0
	 */
	public function okewa_admin_assets() {

		// CSS
		wp_enqueue_style( 'okewa-admin-style', plugins_url( 'assets/css/okewa-admin-style.css', __FILE__ ) );
		wp_enqueue_style( 'wp-color-picker' );

		// JS
		wp_enqueue_script( 'jquery-ui-core' );
		wp_enqueue_script( 'jquery-ui-accordion' );
		wp_enqueue_script( 'jquery-ui-sortable' );
		wp_enqueue_script( 'wp-color-picker' );
		wp_enqueue_script( 'okewa-admin-js', plugins_url( 'assets/js/okewa-admin-js.js', __FILE__ ) );

	}


	/**
	 * Admin notices
	 *
	 * @since 1.0
	 */
	public function okewa_admin_notices() {

		// Get current screen
		$screen = get_current_screen();

		/**
		 * If settings updated successfully
		 */
		if ( isset( $_GET['settings-updated'] ) && $screen->id == 'toplevel_page_okewa' ) {
			?>
			<div class="notice notice-success is-dismissible">
				<p>Changes has been updated!</p>
			</div>
			<?php
		}

	}


	/**
	 * UI Assets
	 *
	 * @since 1.0
	 */
	public function okewa_ui_assets() {

		// CSS
		wp_enqueue_style( 'okewa-ui-animate', plugins_url( 'assets/css/animate.min.css', __FILE__ ) );
		wp_enqueue_style( 'okewa-ui-style', plugins_url( 'assets/css/okewa-ui-style.css', __FILE__ ) );

		// JS
		wp_enqueue_script('jquery-ui-core');
		wp_enqueue_script('jquery-effects-shake');
		wp_enqueue_script('okewa-ui-js', plugins_url('assets/js/okewa-ui-js.js', __FILE__));
        if (!defined('WC_VERSION')) {
    		wp_enqueue_script('okewa-cookie-js', plugins_url('assets/js/js.cookie.min.js', __FILE__));
        }

		$btn_z_index = isset( $this->settings['btn_z_index'] ) ? $this->settings['btn_z_index'] : 1;
		wp_localize_script( 'okewa-ui-js', 'okewa_ui_data', array(
			'z_index' => intval( $btn_z_index )
		));
	}


	/**
	 * Woocommerce
	 *
	 * @since 1.0
	 */	
    public function whatsapp_order_btn() {
        ?>    
            <div class="okewa-woo"><a href="#" data-no="<?php echo $this->settings['woo_btn_number']; ?>" style="background:<?php echo $this->settings['woo_btn_col']; ?>;" class="okewa-btn btn_<?php echo ( isset( $this->settings['woo_btn_style'] ) ) ? $this->settings['woo_btn_style'] : '1'; ?>"><span class="okewa-btn_text"><?php echo ( isset( $this->settings['woo_btn_text'] ) && $this->settings['woo_btn_text'] != '' ) ? $this->settings['woo_btn_text'] : 'Order via Whatsapp'; ?></span><img class="okewa-btn_icon" src="<?php echo plugins_url( 'assets/img/whatsapp.png' , __FILE__ ); ?>" /></a></div>
        <?php    
    }
    public function remove_add_to_cart_buttons() {
        ?>    
        <style>
            .single_add_to_cart_button { display: none!Important; }
            .single-product form.cart input { padding: 10px; }
            .okewa-woo { display: inline-block; }
            .okewa-woo  .okewa-btn { margin-top: 0px; }
            .woocommerce .quantity .qty {
                padding: 11px 5px 11px 20px;
                text-align: center;
                min-width: 80px;
            <?php if ( isset( $this->settings['woo_btn_style'] ) && $this->settings['woo_btn_style'] == '1' ) { ?>
                border-radius: 0px;
            <?php } else if ( isset( $this->settings['woo_btn_style'] ) && $this->settings['woo_btn_style'] == '2' ) { ?>
                border-radius: 6px;
            <?php } else if ( isset( $this->settings['woo_btn_style'] ) && $this->settings['woo_btn_style'] == '3' ) { ?>
                border-radius: 60px;
            <?php } ?>
            }
        </style>
        <?php    
    }
    public function whatsapp_confirm_btn( $order ) {
        if ( $order->post_status == 'wc-on-hold' ) {
        ?>    
            <div style="text-align:center;margin-bottom:40px;"><!--[if mso]>
              <v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="#" style="height:40px;v-text-anchor:middle;width:200px;" arcsize="150%" stroke="f" fillcolor="#4ed214">
                <w:anchorlock/>
                <center>
              <![endif]-->
                  <a href="https://api.whatsapp.com/send?phone=<?php echo $this->settings['woo_confirm_number']; ?>&text=<?php echo $this->settings['woo_confirm_text']; ?>" style="background-color:<?php echo isset( $this->settings['woo_confirm_col'] ) ? $this->settings['woo_confirm_col'] : '#0dc152' ?>;border-radius:<?php echo ( isset( $this->settings['woo_confirm_style'] ) && $this->settings['woo_confirm_style'] == 3 ) ? '60' : '6'; ?>px;color:#ffffff;display:inline-block;font-family:sans-serif;font-size:13px;font-weight:bold;line-height:40px;text-align:center;text-decoration:none;width:200px;-webkit-text-size-adjust:none;"><?php echo ( isset( $this->settings['woo_confirm_text'] ) && $this->settings['woo_confirm_text'] != '' ) ? $this->settings['woo_confirm_text'] : 'Confirm Payment'; ?></a>
              <!--[if mso]>
                </center>
              </v:roundrect>
            <![endif]--></div>
        <?php    
        }
    }
    public function whatsapp_share_btn($content) {
        if(is_single()) {
            if ( wp_is_mobile() ){ $url = 'api'; } else { $url = 'web'; }
            $content .= '<div class="okewa-post"><a href="https://'.$url.'.whatsapp.com/send?&text=*'.$this->settings["post_prefix"].'*%0A'.get_the_title().'%0A%0A'.get_permalink().'" class="okewa-btn btn_share"><img class="okewa-btn_icon" src="'.plugins_url( 'assets/img/whatsapp.png' , __FILE__ ).'" /><span class="okewa-btn_text">'.$this->settings["post_btn_text"].'</span></a></div>';
        }
        return $content;
    }
    
    public function okewa_button( $atts, $content ) {
        extract(shortcode_atts(array(
            'number' => '',
            'msg' => '',
            'group' => '',
            'bg' => '#0dc152',
            'color' => '#fff',
            'style' => '1',
            'fw' => '0',
            'size' => ''
            ), $atts));
            if ( wp_is_mobile() ){ $url = 'api'; } else { $url = 'web'; }
            return '<a href="'.(( $group !== "" ) ? $group : "https://$url.whatsapp.com/send?phone=$number&text=$msg").'" style="background:'.$bg.';display:'.(( $fw == "1" ) ? "block" : "").';" class="okewa-btn btn_'.$style.' '.(( $size == "small" ) ? "okewa-small" : "").'"><span style="color:'.$color.';" class="okewa-btn_text">'.do_shortcode($content).'</span><img class="okewa-btn_icon" src="'.plugins_url( 'assets/img/whatsapp.png' , __FILE__ ).'" /></a>';
    }
    public function okewa_opener( $atts ) {
        extract(shortcode_atts(array(
            'bg' => '#0dc152',
            'color' => '#fff',
            'style' => '1',
            'fw' => '0',
            'size' => '',
            'text' => 'Open Chat Widget'
            ), $atts));
        return '<a href="#" style="background:'.$bg.';display:'.(( $fw == "1" ) ? "block" : "").';" class="okewa-btn open-wa btn_'.$style.' '.(( $size == "small" ) ? "okewa-small" : "").'"> <span style="color:'.$color.';" class="okewa-btn_text">'.$text.'</span> </a>';
    }
	public function okewa_redirection_cpt() {
		register_post_type( 'wa', array(
		  'labels' => array(
			'name' => 'Whatsapp Redirection Links',
			'singular_name' => 'Whatsapp Redirection Link',
		   ),
		  'description' => 'Create redirection link from your domain into whatsapp account number.',
		  'public' => true,
		  'show_in_menu' => false,
		  'supports' => array( 'title' )
		));
	}
	public function okewa_redirection_submenu() {
		add_submenu_page('okewa', __( 'Redirections', 'okewa-text-domain' ), __( 'Redirections', 'okewa-text-domain' ), 'edit_pages' , 'edit.php?post_type=wa');
	}
	function okewa_redirection_parent($parent_file){
		global $submenu_file, $current_screen;
		if($current_screen->post_type == 'wa') {
			$submenu_file = 'edit.php?post_type=wa';
			$parent_file = 'okewa';
		}
		return $parent_file;
	}
	public function load_okewa_redirection_template($template) {
		global $post;
		if ($post->post_type == "wa"){
			$plugin_path = plugin_dir_path( __FILE__ );
			$template_name = 'okewa-redirection.php';
			if($template === get_stylesheet_directory() . '/' . $template_name
				|| !file_exists($plugin_path . $template_name)) {
				return $template;
			}
			return $plugin_path . $template_name;
		}
		return $template;
	}
	public function okewa_add_meta_boxes($post) {
		add_meta_box( 'okewa_meta_box', __( 'Whatsapp Redirection Link', 'okewa-text-domain' ), array($this, 'okewa_build_meta_box'), 'wa', 'normal', 'high' );
	}
	public function okewa_build_meta_box($post) {
		wp_nonce_field( basename( __FILE__ ), 'okewa_meta_box_nonce' );
		$wa_no = get_post_meta( $post->ID, '_wa_no', true );
		$wa_message = get_post_meta( $post->ID, '_wa_message', true );
		$wa_pixel = get_post_meta( $post->ID, '_wa_pixel', true );
		?>
		<div class='inside'>
			<table class="form-table">
				<tbody>
					<tr>
						<th style="width:20%"><label for="okewa_wa_no"><?php echo __( 'Whatsapp Number', 'okewa-text-domain' ); ?></label></th>
						<td><input type="text" name="okewa_wa_no" id="okewa_wa_no" value="<?php echo $wa_no; ?>" placeholder="62" size="30" style="width:97%"><br><?php echo __( 'Insert whatsapp number destination here with country code.', 'okewa-text-domain' ); ?></td>
						<td></td>
					</tr>
					<tr>
						<th style="width:20%"><label for="okewa_wa_message"><?php echo __( 'Predefined Message', 'okewa-text-domain' ); ?></label></th>
						<td><textarea name="okewa_wa_message" id="okewa_wa_message" cols="60" rows="4" style="width:97%"><?php echo $wa_message; ?></textarea><br><?php echo __( 'Insert predefined message to be sent to the destination number (optional).', 'okewa-text-domain' ); ?></td>
						<td></td>
					</tr>
					<tr>
						<th style="width:20%"><label for="okewa_wa_pixel"><?php echo __( 'Pixel Code', 'okewa-text-domain' ); ?></label></th>
						<td><textarea name="okewa_wa_pixel" id="okewa_wa_pixel" cols="60" rows="4" style="width:97%"><?php echo $wa_pixel; ?></textarea><br><?php echo __( 'Paste pixel code here with script tag (optional).', 'okewa-text-domain' ); ?></td>
						<td></td>
					</tr>
				</tbody>
			</table>

		</div>
		<?php
	}
	public function okewa_save_meta_box_data($post_id) {
		if ( !isset( $_POST['okewa_meta_box_nonce'] ) || !wp_verify_nonce( $_POST['okewa_meta_box_nonce'], basename( __FILE__ ) ) ){
			return;
		}
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ){
			return;
		}
		if ( ! current_user_can( 'edit_post', $post_id ) ){
			return;
		}
		if ( isset( $_REQUEST['okewa_wa_no'] ) ) {
			update_post_meta( $post_id, '_wa_no', $_POST['okewa_wa_no'] );
		}
		if ( isset( $_REQUEST['okewa_wa_message'] ) ) {
			update_post_meta( $post_id, '_wa_message', $_POST['okewa_wa_message'] );
		}
		if ( isset( $_REQUEST['okewa_wa_pixel'] ) ) {
			update_post_meta( $post_id, '_wa_pixel', $_POST['okewa_wa_pixel'] );
		}
	}
}