<?php

namespace FSPoster\App\Providers;

use FSPoster\App\Controller\Ajax;
use FSPoster\App\Controller\Popups;

class BackEnd
{

	use PluginMenu;

	private $active_custom_post_types;

	public function __construct()
	{
		if( !Helper::pluginDisabled() )
		{
			new Ajax();
			new Popups();
		}

		$this->initMenu();

		$this->enqueueAssets();
		$this->updateService();
		$this->registerMetaBox();

		$this->registerActions();
		$this->registerBulkAction();
		$this->registerNotifications();
	}

	private function registerMetaBox()
	{
		add_action( 'add_meta_boxes', function()
		{
			add_meta_box( 'fs_poster_meta_box', 'FS Poster', [$this , 'publishMetaBox'], $this->getActiveCustomPostTypes() , 'side' , 'high'  );
		});
	}

	public function publishMetaBox( $post )
	{
		// post creating panel
		if( in_array( $post->post_status , ['new' , 'auto-draft' , 'draft' , 'pending'] ) )
		{
			Helper::view('post_meta_box', [
				'post_id'  =>  $post->ID
			]);
		}
		else // post edit panel
		{
			Helper::view('post_meta_box_edit', [
				'post'  =>  $post
			]);
		}
	}

	private function enqueueAssets()
	{
		add_action('admin_enqueue_scripts' , function()
		{
			wp_register_script('fs-code', Helper::assets('js/fs-code.js') , [ 'jquery' ] , Helper::getVersion());
			wp_enqueue_script( 'fs-code' );
			wp_localize_script( 'fs-code', 'FSPosterData', [
				'assets_url'    => Helper::assets(''),
			]);
			$this->bulkScheduleAction();

			wp_enqueue_style( 'fs-code', Helper::assets('css/fs-code.css') , [] , Helper::getVersion() );
			wp_enqueue_style( 'font_aweasome', '//use.fontawesome.com/releases/v5.0.13/css/all.css' );
		});
	}

	private function updateService()
	{
		$activationKey = Helper::getOption('poster_plugin_purchase_key' , '', true);

		if( !empty($activationKey) )
		{
			add_action( 'init', function () use ( $activationKey )
			{
				$updater = new FSCodeUpdater( 'fs-poster', FS_API_URL . '/api.php', $activationKey );
			});
		}
	}

	private function registerActions()
	{
		if( Helper::getOption('show_fs_poster_column', '1') )
		{
			$usedColumnsSave = [];

			foreach( $this->getActiveCustomPostTypes() AS $postType )
			{
				$postType = preg_replace('/[^a-zA-Z0-9\-\_]/' , '' , $postType);

				switch($postType)
				{
					case 'post':
						$typeName = 'posts';
						break;
					case 'page':
						$typeName = 'pages';
						break;
					case 'attachment':
						$typeName = 'media';
						break;
					default:
						$typeName = $postType . '_posts';
				}

				add_action( 'manage_'.$typeName.'_custom_column', function ( $column_name, $post_id ) use( &$usedColumnsSave )
				{
					if ( $column_name == 'share_btn' && get_post_status($post_id) == 'publish' && !isset($usedColumnsSave[$post_id]) )
					{
						printf( '<img class="fs_post_icons ws_tooltip" data-title="Share" src="'.Helper::assets('images/share_icon.png').'" data-load-modal="share_saved_post" data-parameter-post_id="%d">', $post_id  );
						printf( '<img class="fs_post_icons ws_tooltip" data-title="Schedule" src="'.Helper::assets('images/schedule_icon.png').'" data-load-modal="add_schedule" data-parameter-post_ids="%d"> ', $post_id  );

						$usedColumnsSave[$post_id] = true;
					}
				}, 10, 2 );

				add_filter('manage_'.$typeName.'_columns', function ( $columns )
				{
					if( is_array( $columns ) && ! isset( $columns['share_btn'] ) )
					{
						$columns['share_btn'] = esc_html__('FS Poster' , 'fs-poster');
					}

					return $columns;
				} );

			}
		}
	}

	private function registerBulkAction()
	{
		foreach( $this->getActiveCustomPostTypes() AS $postType )
		{
			if( $postType == 'attachment' )
			{
				$postType = 'upload';
			}
			else
			{
				$postType = 'edit-' . $postType;
			}

			add_filter( 'bulk_actions-' . $postType, function ($bulk_actions)
			{
				$bulk_actions['fs_schedule'] = __( 'FS Poster: Schedule', 'fs-poster');
				return $bulk_actions;
			});

			add_filter( 'handle_bulk_actions-' . $postType, function ( $redirect_to, $doaction, $post_ids )
			{
				if ( $doaction !== 'fs_schedule' )
				{
					return $redirect_to;
				}

				$redirect_to = add_query_arg( 'fs_schedule_posts', implode(',' , $post_ids), $redirect_to );
				return $redirect_to;
			}, 10, 3 );
		}
	}

	private function getActiveCustomPostTypes()
	{
		if( is_null( $this->active_custom_post_types ) )
		{
			$this->active_custom_post_types = explode( '|' , Helper::getOption('allowed_post_types' , 'post|page|attachment|product') );
		}

		return $this->active_custom_post_types;
	}

	private function bulkScheduleAction()
	{
		$posts = Request::get('fs_schedule_posts', '', 'string');

		$posts = explode(',' , $posts);
		$postIds = [];
		foreach ($posts AS $postId)
		{
			if( is_numeric($postId) && $postId > 0 )
			{
				$postIds[] = (int)$postId;
			}
		}

		if( empty( $postIds ) )
		{
			return;
		}

		wp_add_inline_script( 'fs-code', 'jQuery(document).ready(function(){ fsCode.loadModal("add_schedule" , {"post_ids": "'.implode(',', $postIds).'"}) });' );
	}

	private function registerNotifications ()
	{
		add_action( 'init', function ()
		{
			$plgnVer = Helper::getOption('poster_plugin_installed' , '0', true);;

			if( ! $plgnVer )
			{
				return;
			}
			
			$failed_accounts = DB::DB()->get_row( DB::DB()->prepare( 'SELECT COUNT(id) AS total FROM ' . DB::table( 'accounts' ) . ' WHERE status = \'error\' AND ( is_public = 1 OR user_id = %d ) AND blog_id=%d', [ get_current_user_id(), Helper::getBlogId() ] ) , ARRAY_A );

			if ( $failed_accounts && $failed_accounts['total'] > 0 )
			{
				add_action( 'admin_notices', function () use ( $failed_accounts ) {
					$verb = (int) $failed_accounts['total'] >= 2 ? 'are' : 'is';

					printf( '<div class="notice notice-error is-dismissible"><div class="fs_notice"><div class="fs_notice_text"><b>FS Poster</b><br>There %s %d failed account(s).</div><div class="fs_notice_button"><a href="%sadmin.php?page=fs-poster" class="ws_btn ws_bg_danger ws_btn_small">%s</a></div></div></div>', $verb, $failed_accounts['total'], admin_url(), esc_html__( 'Review accounts', 'fs-poster' ) );
				} );
			}

			$failed_feeds = DB::DB()->get_row( DB::DB()->prepare('SELECT COUNT(id) AS total FROM ' . DB::table('feeds') . ' tb1 WHERE blog_id="'.Helper::getBlogId().'" AND is_sended = 1 AND ( ( node_type="account" AND ( SELECT COUNT(0) FROM '.DB::table('accounts').' tb2 WHERE tb2.id = tb1.node_id AND ( tb2.user_id = %d OR tb2.is_public=1) ) > 0 ) OR ( node_type <> "account" AND (SELECT COUNT(0) FROM '.DB::table('account_nodes').' tb2 WHERE tb2.id = tb1.node_id AND ( tb2.user_id = %d ) > 0 OR tb2.is_public = 1 ) ) ) AND status = "error" AND is_seen = "0"', (int) get_current_user_id(), (int) get_current_user_id() ), ARRAY_A );

			if ( $failed_feeds && $failed_feeds['total'] > 0 )
			{
				add_action( 'admin_notices', function () use ( $failed_feeds ) {
					$verb = (int) $failed_feeds['total'] >= 2 ? 'are' : 'is';

					printf( '<div class="notice notice-error is-dismissible"><div class="fs_notice"><div class="fs_notice_text"><b>FS Poster</b><br>There %s %d failed feed(s).</div><div class="fs_notice_button"><a href="%sadmin.php?page=fs-poster-posts&filter_by=error" class="ws_btn ws_bg_danger ws_btn_small">%s</a></div></div></div>', $verb, $failed_feeds['total'], admin_url(), esc_html__( 'Go to logs', 'fs-poster' ) );
				} );
			}
		});
	}
}
