<?php

namespace FSPoster\App\Controller\Popups;


use FSPoster\App\Providers\DB;
use FSPoster\App\Providers\Helper;
use FSPoster\App\Providers\Request;

trait Schedule
{

	public function add_schedule ()
	{
		$accountAndNodes = Request::post( 'nodes', NULL, 'array' );

		if ( ! is_null( $accountAndNodes ) )
		{
			$accountIDs = [];
			$nodeIDs    = [];
			foreach ( $accountAndNodes as $accountNodeInf )
			{
				if ( empty( $accountNodeInf ) )
				{
					continue;
				}

				$accountNodeInf = explode( ':', $accountNodeInf );

				if ( ! isset( $accountNodeInf[1] ) )
				{
					continue;
				}

				if ( $accountNodeInf[0] == 'account' )
				{
					$accountIDs[] = (int) $accountNodeInf[1];
				}
				else
				{
					$nodeIDs[] = (int) $accountNodeInf[1];
				}
			}

			$accountIDs = implode( ',', $accountIDs );
			$nodeIDs    = implode( ',', $nodeIDs );

			if ( ! empty( $accountIDs ) )
			{
				$accounts = DB::DB()->get_results(
					DB::DB()->prepare( "
					SELECT 
						tb2.*, IFNULL(tb1.filter_type, 'no') AS filter_type, tb1.categories, (SELECT GROUP_CONCAT(`name`) FROM " . DB::WPtable( 'terms', TRUE ) . " WHERE FIND_IN_SET(term_id,tb1.categories) ) AS categories_name,'account' AS node_type 
					FROM " . DB::table( 'accounts' ) . " tb2
					LEFT JOIN " . DB::table( 'account_status' ) . " tb1 ON tb2.id=tb1.account_id AND tb1.user_id=%d
					WHERE (tb2.user_id=%d OR tb2.is_public=1) AND tb2.blog_id=%d AND tb2.id IN ({$accountIDs})
					ORDER BY name", [ get_current_user_id(), get_current_user_id(), Helper::getBlogId() ] )
					, ARRAY_A
				);
			}
			else
			{
				$accounts = [];
			}

			if ( ! empty( $nodeIDs ) )
			{
				$activeNodes = DB::DB()->get_results(
					DB::DB()->prepare( "
				SELECT 
					tb2.*, IFNULL(tb1.filter_type, 'no') AS filter_type, tb1.categories, (SELECT GROUP_CONCAT(`name`) FROM " . DB::WPtable( 'terms', TRUE ) . " WHERE FIND_IN_SET(term_id,tb1.categories) ) AS categories_name 
				FROM " . DB::table( 'account_nodes' ) . " tb2
				LEFT JOIN " . DB::table( 'account_node_status' ) . " tb1 ON tb2.id=tb1.node_id AND tb1.user_id=%d
				WHERE (tb2.user_id=%d OR tb2.is_public=1) AND tb2.blog_id=%d AND tb2.id IN ({$nodeIDs})
				ORDER BY (CASE node_type WHEN 'ownpage' THEN 1 WHEN 'group' THEN 2 WHEN 'page' THEN 3 END), name", [ get_current_user_id(), get_current_user_id(), Helper::getBlogId() ] )
					, ARRAY_A
				);
			}
			else
			{
				$activeNodes = [];
			}
		}
		else
		{
			$accounts = DB::DB()->get_results(
				DB::DB()->prepare( "
				SELECT tb2.*, tb1.filter_type, tb1.categories, (SELECT GROUP_CONCAT(`name`) FROM " . DB::WPtable( 'terms', TRUE ) . " WHERE FIND_IN_SET(term_id,tb1.categories) ) AS categories_name,'account' AS node_type 
				FROM " . DB::table( 'account_status' ) . " tb1
				INNER JOIN " . DB::table( 'accounts' ) . " tb2 ON tb2.id=tb1.account_id
				WHERE tb1.user_id=%d AND tb2.blog_id=%d
				ORDER BY name", [ get_current_user_id(), Helper::getBlogId() ] )
				, ARRAY_A
			);

			$activeNodes = DB::DB()->get_results(
				DB::DB()->prepare( "
				SELECT tb2.*, tb1.filter_type, tb1.categories, (SELECT GROUP_CONCAT(`name`) FROM " . DB::WPtable( 'terms', TRUE ) . " WHERE FIND_IN_SET(term_id,tb1.categories) ) AS categories_name FROM " . DB::table( 'account_node_status' ) . " tb1
				LEFT JOIN " . DB::table( 'account_nodes' ) . " tb2 ON tb2.id=tb1.node_id
				WHERE tb1.user_id=%d AND tb2.blog_id=%d
				ORDER BY (CASE node_type WHEN 'ownpage' THEN 1 WHEN 'group' THEN 2 WHEN 'page' THEN 3 END), name", [ get_current_user_id(), Helper::getBlogId() ] )
				, ARRAY_A
			);
		}

		$activeNodes = array_merge( $accounts, $activeNodes );
		foreach ( $activeNodes as $aKey => $active_node )
		{
			if ( $nodeInf['filter_type'] == 'no' )
			{
				$titleText = '';
			}
			else
			{
				$titleText = ( $nodeInf['filter_type'] == 'in' ? esc_html__( 'Only the selected categories will be shared:', 'fs-poster' ) : esc_html__( 'The selected categories will not be shared:', 'fs-poster' ) ) . "\n";
				$titleText .= str_replace( ',', ', ', $nodeInf['categories_name'] );
			}

			$activeNodes[$aKey]['title_text'] = $titleText;
		}

		/*
		 * Fetch all Custom Post types...
		 */
		$postTypes        = [];
		$allowedPostTypes = explode( '|', Helper::getOption( 'allowed_post_types', 'post|page|attachment|product' ) );
		foreach ( get_post_types() as $post_type )
		{
			if ( ! in_array( $post_type, $allowedPostTypes ) )
			{
				continue;
			}

			$postTypes[] = $post_type;
		}

		$postCategories    = get_terms( [ 'category' ], [ 'hide_empty' => FALSE ] );
		$productCategories = taxonomy_exists( 'product_cat' ) ? get_terms( [ 'product_cat' ], [ 'hide_empty' => FALSE ] ) : [];
		$customTaxonomies  = [];

		$getCustomTaxs = get_terms( [ 'hide_empty' => FALSE, 'orderby' => 'taxonomy' ] );
		foreach ( $getCustomTaxs as $categ )
		{
			if ( in_array( $categ->taxonomy, [ 'category', 'product_cat' ] ) )
			{
				continue;
			}

			if ( ! isset( $customTaxonomies[$categ->taxonomy] ) )
			{
				$customTaxonomies[$categ->taxonomy] = [];
			}

			$customTaxonomies[$categ->taxonomy][] = $categ;
		}

		$customMessages = [
			'fb'          => Helper::getOption( 'post_text_message_fb', "{title}" ),
			'instagram'   => Helper::getOption( 'post_text_message_instagram', "{title}" ),
			'instagram_h' => Helper::getOption( 'post_text_message_instagram_h', "{title}" ),
			'twitter'     => Helper::getOption( 'post_text_message_twitter', "{title}" ),
			'linkedin'    => Helper::getOption( 'post_text_message_linkedin', "{title}" ),
			'tumblr'      => Helper::getOption( 'post_text_message_tumblr', "{title}" ),
			'reddit'      => Helper::getOption( 'post_text_message_reddit', "{title}" ),
			'vk'          => Helper::getOption( 'post_text_message_vk', "{title}" ),
			'ok'          => Helper::getOption( 'post_text_message_ok', "{title}" ),
			'pinterest'   => Helper::getOption( 'post_text_message_pinterest', "{title}" ),
			'google_b'    => Helper::getOption( 'post_text_message_google_b', "{title}" ),
			'telegram'    => Helper::getOption( 'post_text_message_telegram', "{title}" ),
			'medium'      => Helper::getOption( 'post_text_message_medium', "{title}" ),
			'wordpress'   => Helper::getOption( 'post_text_message_wordpress', "{content_full}" )
		];

		$post_ids       = Request::post( 'post_ids', '', 'string' );
		$schedule_name  = '';
		$post_ids_count = 0;
		if ( ! empty( $post_ids ) )
		{
			$post_ids       = explode( ',', $post_ids );
			$post_ids_count = count( $post_ids );

			if ( $post_ids_count == 1 )
			{
				$onePostId  = reset( $post_ids );
				$onePostInf = get_post( $onePostId, ARRAY_A );

				$schedule_name = 'Scheduled post: "' . Helper::cutText( ! empty( $onePostInf['post_title'] ) ? $onePostInf['post_title'] : $onePostInf['post_content'] ) . '"';
			}
			else
			{
				$schedule_name = 'Schedule ( ' . $post_ids_count . ' posts )';
			}

			$post_ids = implode( ',', $post_ids );
		}

		Helper::modalView( 'schedule.add', [
			'name'              => $schedule_name,
			'activeNodes'       => $activeNodes,
			'postTypes'         => $postTypes,
			'postCategories'    => $postCategories,
			'productCategories' => $productCategories,
			'customTaxonomies'  => $customTaxonomies,
			'customMessages'    => $customMessages,
			'title'             => esc_html__( 'ADD NEW SCHEDULE', 'fs-poster' ),
			'btn_title'         => esc_html__( 'ADD SCHEDULE', 'fs-poster' ),
			'post_ids'          => $post_ids,
			'post_ids_count'    => $post_ids_count
		] );
	}

	public function edit_schedule ()
	{
		$scheduleId = Request::post( 'schedule_id', 0, 'int' );

		$scheduleInf = DB::fetch( 'schedules', $scheduleId );

		if ( ! $scheduleInf )
		{
			Helper::response( FALSE, esc_html__( 'Schedule not found!', 'fs-poster' ) );
		}

		if ( $scheduleInf['interval'] % 1440 === 0 )
		{
			$scheduleInf['interval']      = $scheduleInf['interval'] / 1440;
			$scheduleInf['interval_type'] = 1440;
		}
		else
		{
			if ( $scheduleInf['interval'] % 60 === 0 )
			{
				$scheduleInf['interval']      = $scheduleInf['interval'] / 60;
				$scheduleInf['interval_type'] = 60;
			}
			else
			{
				$scheduleInf['interval_type'] = 1;
			}
		}

		$accountAndNodes = explode( ',', $scheduleInf['share_on_accounts'] );
		$accountIDs      = [];
		$nodeIDs         = [];
		foreach ( $accountAndNodes as $accountNodeInf )
		{
			if ( empty( $accountNodeInf ) )
			{
				continue;
			}

			$accountNodeInf = explode( ':', $accountNodeInf );

			if ( ! isset( $accountNodeInf[1] ) )
			{
				continue;
			}

			if ( $accountNodeInf[0] == 'account' )
			{
				$accountIDs[] = (int) $accountNodeInf[1];
			}
			else
			{
				$nodeIDs[] = (int) $accountNodeInf[1];
			}
		}

		$accountIDs = implode( ',', $accountIDs );
		$nodeIDs    = implode( ',', $nodeIDs );

		if ( ! empty( $accountIDs ) )
		{
			$accounts = DB::DB()->get_results(
				DB::DB()->prepare( "
				SELECT 
					tb2.*, IFNULL(tb1.filter_type, 'no') AS filter_type, tb1.categories, (SELECT GROUP_CONCAT(`name`) FROM " . DB::WPtable( 'terms', TRUE ) . " WHERE FIND_IN_SET(term_id,tb1.categories) ) AS categories_name,'account' AS node_type 
				FROM " . DB::table( 'accounts' ) . " tb2
				LEFT JOIN " . DB::table( 'account_status' ) . " tb1 ON tb2.id=tb1.account_id AND tb1.user_id=%d
				WHERE (tb2.user_id=%d OR is_public=1) AND tb2.blog_id=%d AND tb2.id IN ({$accountIDs})
				ORDER BY name", [ get_current_user_id(), get_current_user_id(), Helper::getBlogId() ] )
				, ARRAY_A
			);
		}
		else
		{
			$accounts = [];
		}

		if ( ! empty( $nodeIDs ) )
		{
			$activeNodes = DB::DB()->get_results(
				DB::DB()->prepare( "
				SELECT 
					tb2.*, IFNULL(tb1.filter_type, 'no') AS filter_type, tb1.categories, (SELECT GROUP_CONCAT(`name`) FROM " . DB::WPtable( 'terms', TRUE ) . " WHERE FIND_IN_SET(term_id,tb1.categories) ) AS categories_name 
				FROM " . DB::table( 'account_nodes' ) . " tb2
				LEFT JOIN " . DB::table( 'account_node_status' ) . " tb1 ON tb2.id=tb1.node_id AND tb1.user_id=%d
				WHERE (tb2.user_id=%d OR tb2.is_public=1) AND tb2.blog_id=%d AND tb2.id IN ({$nodeIDs})
				ORDER BY (CASE node_type WHEN 'ownpage' THEN 1 WHEN 'group' THEN 2 WHEN 'page' THEN 3 END), name", [ get_current_user_id(), get_current_user_id(), Helper::getBlogId() ] )
				, ARRAY_A
			);
		}
		else
		{
			$activeNodes = [];
		}

		$activeNodes = array_merge( $accounts, $activeNodes );
		foreach ( $activeNodes as $aKey => $active_node )
		{
			if ( $active_node['filter_type'] == 'no' )
			{
				$titleText = '';
			}
			else
			{
				$titleText = ( $active_node['filter_type'] == 'in' ? esc_html__( 'Only the selected categories will be shared:', 'fs-poster' ) : esc_html__( 'The selected categories will not be shared:', 'fs-poster' ) ) . "\n";
				$titleText .= str_replace( ',', ', ', $active_node['categories_name'] );
			}

			$activeNodes[$aKey]['title_text'] = $titleText;
		}

		/*
		 * Fetch all Custom Post types...
		 */
		$postTypes        = [];
		$allowedPostTypes = explode( '|', Helper::getOption( 'allowed_post_types', 'post|page|attachment|product' ) );
		foreach ( get_post_types() as $post_type )
		{
			if ( ! in_array( $post_type, $allowedPostTypes ) )
			{
				continue;
			}

			$postTypes[] = $post_type;
		}

		$postCategories    = get_terms( [ 'category' ], [ 'hide_empty' => FALSE ] );
		$productCategories = taxonomy_exists( 'product_cat' ) ? get_terms( [ 'product_cat' ], [ 'hide_empty' => FALSE ] ) : [];
		$customTaxonomies  = [];

		$getCustomTaxs = get_terms( [ 'hide_empty' => FALSE, 'orderby' => 'taxonomy' ] );
		foreach ( $getCustomTaxs as $categ )
		{
			if ( in_array( $categ->taxonomy, [ 'category', 'product_cat' ] ) )
			{
				continue;
			}

			if ( ! isset( $customTaxonomies[$categ->taxonomy] ) )
			{
				$customTaxonomies[$categ->taxonomy] = [];
			}

			$customTaxonomies[$categ->taxonomy][] = $categ;
		}

		$defaultCustomMessages = [
			'fb'          => Helper::getOption( 'post_text_message_fb', "{title}" ),
			'instagram'   => Helper::getOption( 'post_text_message_instagram', "{title}" ),
			'instagram_h' => Helper::getOption( 'post_text_message_instagram_h', "{title}" ),
			'twitter'     => Helper::getOption( 'post_text_message_twitter', "{title}" ),
			'linkedin'    => Helper::getOption( 'post_text_message_linkedin', "{title}" ),
			'tumblr'      => Helper::getOption( 'post_text_message_tumblr', "{title}" ),
			'reddit'      => Helper::getOption( 'post_text_message_reddit', "{title}" ),
			'vk'          => Helper::getOption( 'post_text_message_vk', "{title}" ),
			'ok'          => Helper::getOption( 'post_text_message_ok', "{title}" ),
			'pinterest'   => Helper::getOption( 'post_text_message_pinterest', "{title}" ),
			'google_b'    => Helper::getOption( 'post_text_message_google_b', "{title}" ),
			'telegram'    => Helper::getOption( 'post_text_message_telegram', "{title}" ),
			'medium'      => Helper::getOption( 'post_text_message_medium', "{title}" )
		];

		$customMessages = array_merge( $defaultCustomMessages, json_decode( $scheduleInf['custom_post_message'], TRUE ) );

		if ( $scheduleInf['status'] == 'finished' )
		{
			$scheduleInf['title'] = 'Re: ' . $scheduleInf['title'];
		}

		$post_ids_count = empty( $scheduleInf['save_post_ids'] ) ? 0 : count( explode( ',', $scheduleInf['save_post_ids'] ) );

		Helper::modalView( 'schedule.add', [
			'id'                => $scheduleId,
			'info'              => $scheduleInf,
			'activeNodes'       => $activeNodes,
			'postTypes'         => $postTypes,
			'postCategories'    => $postCategories,
			'productCategories' => $productCategories,
			'customTaxonomies'  => $customTaxonomies,
			'customMessages'    => $customMessages,
			'title'             => $scheduleInf['status'] == 'finished' ? esc_html__( 'RE-SCHEDULE', 'fs-poster' ) : esc_html__( 'EDIT SCHEDULE', 'fs-poster' ),
			'btn_title'         => $scheduleInf['status'] == 'finished' ? esc_html__( 'RE-SCHEDULE', 'fs-poster' ) : esc_html__( 'SAVE SCHEDULE', 'fs-poster' ),
			'post_ids_count'    => $post_ids_count
		] );
	}

	public function posts_list ()
	{
		Helper::modalView( 'other.posts_list' );
	}

	public function edit_wp_native_schedule ()
	{
		$postId = Request::post( 'post_id', 0, 'int' );

		if ( $postId > 0 )
		{
			$feeds = DB::fetchAll( 'feeds', [
				'post_id'   => $postId,
				'is_sended' => 0,
				'blog_id'   => Helper::getBlogId()
			] );

			if ( ! $feeds )
			{
				Helper::response( FALSE, esc_html__( 'Schedule not found!', 'fs-poster' ) );
			}

			$info               = [
				'post_id'   => $postId,
				'send_time' => NULL
			];
			$accountIDs         = [];
			$nodeIDs            = [];
			$customPostMessages = [];

			foreach ( $feeds as $feed )
			{
				if ( is_null( $info['send_time'] ) )
				{
					$info['send_time'] = $feed['send_time'];
				}

				if ( $feed['node_type'] === 'account' )
				{
					$accountIDs[] = $feed['node_id'];
				}
				else
				{
					$nodeIDs[] = $feed['node_id'];
				}

				if ( ! array_key_exists( $feed['driver'], $customPostMessages ) )
				{
					$customPostMessages[$feed['driver']] = $feed['custom_post_message'];
				}
			}

			if ( is_null( $info['send_time'] ) )
			{
				Helper::response( FALSE, esc_html__( 'Schedule not found!', 'fs-poster' ) );
			}

			$accountIDs = implode( ',', $accountIDs );
			$nodeIDs    = implode( ',', $nodeIDs );

			if ( ! empty( $accountIDs ) )
			{
				$accounts = DB::DB()->get_results(
					DB::DB()->prepare( "
				SELECT 
					tb2.*, IFNULL(tb1.filter_type, 'no') AS filter_type, tb1.categories, (SELECT GROUP_CONCAT(`name`) FROM " . DB::WPtable( 'terms', TRUE ) . " WHERE FIND_IN_SET(term_id,tb1.categories) ) AS categories_name,'account' AS node_type 
				FROM " . DB::table( 'accounts' ) . " tb2
				LEFT JOIN " . DB::table( 'account_status' ) . " tb1 ON tb2.id=tb1.account_id AND tb1.user_id=%d
				WHERE (tb2.user_id=%d OR is_public=1) AND tb2.blog_id=%d AND tb2.id IN ({$accountIDs})
				ORDER BY name", [ get_current_user_id(), get_current_user_id(), Helper::getBlogId() ] )
					, ARRAY_A
				);
			}
			else
			{
				$accounts = [];
			}

			if ( ! empty( $nodeIDs ) )
			{
				$activeNodes = DB::DB()->get_results(
					DB::DB()->prepare( "
				SELECT 
					tb2.*, IFNULL(tb1.filter_type, 'no') AS filter_type, tb1.categories, (SELECT GROUP_CONCAT(`name`) FROM " . DB::WPtable( 'terms', TRUE ) . " WHERE FIND_IN_SET(term_id,tb1.categories) ) AS categories_name 
				FROM " . DB::table( 'account_nodes' ) . " tb2
				LEFT JOIN " . DB::table( 'account_node_status' ) . " tb1 ON tb2.id=tb1.node_id AND tb1.user_id=%d
				WHERE (tb2.user_id=%d OR tb2.is_public=1) AND tb2.blog_id=%d AND tb2.id IN ({$nodeIDs})
				ORDER BY (CASE node_type WHEN 'ownpage' THEN 1 WHEN 'group' THEN 2 WHEN 'page' THEN 3 END), name", [ get_current_user_id(), get_current_user_id(), Helper::getBlogId() ] )
					, ARRAY_A
				);
			}
			else
			{
				$activeNodes = [];
			}

			$activeNodes = array_merge( $accounts, $activeNodes );

			foreach ( $activeNodes as $aKey => $active_node )
			{
				if ( $active_node['filter_type'] == 'no' )
				{
					$titleText = '';
				}
				else
				{
					$titleText = ( $active_node['filter_type'] == 'in' ? esc_html__( 'Only the selected categories will be shared:', 'fs-poster' ) : esc_html__( 'The selected categories will not be shared:', 'fs-poster' ) ) . "\n";
					$titleText .= str_replace( ',', ', ', $active_node['categories_name'] );
				}

				$activeNodes[$aKey]['title_text'] = $titleText;
			}

			$customPostMessages    = array_filter( $customPostMessages, function ( $message )
			{
				return ! is_null( $message ) && ! empty( $message );
			} );
			$defaultCustomMessages = [
				'fb'          => Helper::getOption( 'post_text_message_fb', "{title}" ),
				'instagram'   => Helper::getOption( 'post_text_message_instagram', "{title}" ),
				'instagram_h' => Helper::getOption( 'post_text_message_instagram_h', "{title}" ),
				'twitter'     => Helper::getOption( 'post_text_message_twitter', "{title}" ),
				'linkedin'    => Helper::getOption( 'post_text_message_linkedin', "{title}" ),
				'tumblr'      => Helper::getOption( 'post_text_message_tumblr', "{title}" ),
				'reddit'      => Helper::getOption( 'post_text_message_reddit', "{title}" ),
				'vk'          => Helper::getOption( 'post_text_message_vk', "{title}" ),
				'ok'          => Helper::getOption( 'post_text_message_ok', "{title}" ),
				'pinterest'   => Helper::getOption( 'post_text_message_pinterest', "{title}" ),
				'google_b'    => Helper::getOption( 'post_text_message_google_b', "{title}" ),
				'telegram'    => Helper::getOption( 'post_text_message_telegram', "{title}" ),
				'medium'      => Helper::getOption( 'post_text_message_medium', "{title}" )
			];
			$customMessages        = array_merge( $defaultCustomMessages, $customPostMessages );

			Helper::modalView( 'schedule.edit', [
				'info'           => $info,
				'activeNodes'    => $activeNodes,
				'customMessages' => $customMessages,
				'title'          => esc_html__( 'EDIT SCHEDULE', 'fs-poster' ),
				'btn_title'      => esc_html__( 'SAVE CHANGES', 'fs-poster' ),
				'post_ids_count' => 1
			] );
		}

		Helper::response( FALSE, esc_html__( 'Schedule not found!', 'fs-poster' ) );
	}
}
