<?php

namespace FSPoster\App\view;

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

defined( 'ABSPATH' ) or exit;

DB::DB()->query('DELETE FROM `'.DB::table('account_status').'` WHERE (SELECT count(0) FROM `'.DB::table('accounts').'` WHERE id=account_id)=0');
DB::DB()->query('DELETE FROM `'.DB::table('account_node_status').'` WHERE (SELECT count(0) FROM `'.DB::table('account_nodes').'` WHERE id=`'.DB::table('account_node_status').'`.node_id)=0');

$accountsList = DB::DB()->get_results(DB::DB()->prepare("SELECT driver, COUNT(0) AS _count FROM ".DB::table('accounts')." WHERE (user_id=%d OR is_public=1) AND blog_id=%d GROUP BY driver",  [ get_current_user_id(), Helper::getBlogId() ]) , ARRAY_A);
$accountsCount = [
	'fb'		=>  0,
	'twitter'	=>  0,
	'instagram'	=>  0,
	'linkedin'	=>  0,
	'vk'		=>  0,
	'pinterest'	=>  0,
	'reddit'	=>  0,
	'tumblr'	=>  0,
	'google_b'	=>  0,
	'ok'		=>  0,
	'telegram'	=>	0,
	'medium'	=>	0,
	'wordpress'	=>	0
];

foreach( $accountsList AS $aInf )
{
	if( isset($accountsCount[$aInf['driver']]) )
	{
		$accountsCount[$aInf['driver']] = $aInf['_count'];
	}
}

$failedAccountsList = DB::DB()->get_results(DB::DB()->prepare("SELECT driver, COUNT(0) AS _count FROM ".DB::table('accounts')." WHERE status = 'error' AND (user_id=%d OR is_public=1) AND blog_id=%d GROUP BY driver",  [ get_current_user_id(), Helper::getBlogId() ]) , ARRAY_A);
$failedAccountsCount = [
	'fb'		=>  0,
	'twitter'	=>  0,
	'instagram'	=>  0,
	'linkedin'	=>  0,
	'vk'		=>  0,
	'pinterest'	=>  0,
	'reddit'	=>  0,
	'tumblr'	=>  0,
	'google_b'	=>  0,
	'ok'		=>  0,
	'telegram'	=>	0,
	'medium'	=>	0,
	'wordpress'	=>	0
];

foreach( $failedAccountsList AS $aInf )
{
	if( isset($failedAccountsCount[$aInf['driver']]) )
	{
		$failedAccountsCount[$aInf['driver']] = $aInf['_count'];
	}
}

$activeTab = Request::get('tab', 'fb', 'string');
?>

<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>

<div id="fs_sub_menu">
	<div class="activate_btn">Activate</div>
	<div class="activate_with_condition_btn">Activate (condition)</div>
	<div class="deactivate_btn">Deactivate</div>
</div>

<div id="fs_sub_menu2">
	<div class="make_public_action" data-type="public">Make public <i class="fa fa-question-circle ws_tooltip" data-title="<?=__('Using this feature you will be able to allow other WordPress Users to share in this profile.' , 'fs-poster')?>"></i></div>
	<div class="make_public_action" style="display: none;" data-type="private">Make private <i class="fa fa-question-circle ws_tooltip" data-title="<?=__('Using this feature you will be able to allow other WordPress Users to share in this profile.' , 'fs-poster')?>"></i></div>
	<div class="delete_account_action">Delete</div>
</div>

<div style="display: flex;">
	<div id="fs_account_supports">
		<div class="fs_social_network_div" data-setting="fb">
			<div><i class="fab fa-facebook-square"></i> Facebook</div>
			<div style="display: flex;">
				<div style="background: #ff0000;<?php echo ( $failedAccountsCount['fb'] === 0 ? ' display: none;' : '' ); ?>" class="fs_snd_badge"><?=$failedAccountsCount['fb']?></div>
				<div style="background: #00a8ef;" class="fs_snd_badge"><?=$accountsCount['fb']?></div>
			</div>
		</div>
		<div class="fs_social_network_div" data-setting="twitter">
			<div><i class="fab fa-twitter-square"></i> Twitter</div>
			<div style="display: flex;">
				<div style="background: #ff0000;<?php echo ( $failedAccountsCount['twitter'] === 0 ? ' display: none;' : '' ); ?>" class="fs_snd_badge"><?=$failedAccountsCount['twitter']?></div>
				<div style="background: #00a8ef;" class="fs_snd_badge"><?=$accountsCount['twitter']?></div>
			</div>
		</div>
		<div class="fs_social_network_div" data-setting="instagram">
			<div><i class="fab fa-instagram"></i> Instagram</div>
			<div style="display: flex;">
				<div style="background: #ff0000;<?php echo ( $failedAccountsCount['instagram'] === 0 ? ' display: none;' : '' ); ?>" class="fs_snd_badge"><?=$failedAccountsCount['instagram']?></div>
				<div style="background: #00a8ef;" class="fs_snd_badge"><?=$accountsCount['instagram']?></div>
			</div>
		</div>
		<div class="fs_social_network_div" data-setting="linkedin">
			<div><i class="fab fa-linkedin"></i> Linkedin</div>
			<div style="display: flex;">
				<div style="background: #ff0000;<?php echo ( $failedAccountsCount['linkedin'] === 0 ? ' display: none;' : '' ); ?>" class="fs_snd_badge"><?=$failedAccountsCount['linkedin']?></div>
				<div style="background: #00a8ef;" class="fs_snd_badge"><?=$accountsCount['linkedin']?></div>
			</div>
		</div>
		<div class="fs_social_network_div" data-setting="vk">
			<div><i class="fab fa-vk"></i> VK</div>
			<div style="display: flex;">
				<div style="background: #ff0000;<?php echo ( $failedAccountsCount['vk'] === 0 ? ' display: none;' : '' ); ?>" class="fs_snd_badge"><?=$failedAccountsCount['vk']?></div>
				<div style="background: #00a8ef;" class="fs_snd_badge"><?=$accountsCount['vk']?></div>
			</div>
		</div>
		<div class="fs_social_network_div" data-setting="pinterest">
			<div><i class="fab fa-pinterest"></i> Pinterest</div>
			<div style="display: flex;">
				<div style="background: #ff0000;<?php echo ( $failedAccountsCount['pinterest'] === 0 ? ' display: none;' : '' ); ?>" class="fs_snd_badge"><?=$failedAccountsCount['pinterest']?></div>
				<div style="background: #00a8ef;" class="fs_snd_badge"><?=$accountsCount['pinterest']?></div>
			</div>
		</div>
		<div class="fs_social_network_div" data-setting="reddit">
			<div><i class="fab fa-reddit"></i> Reddit</div>
			<div style="display: flex;">
				<div style="background: #ff0000;<?php echo ( $failedAccountsCount['reddit'] === 0 ? ' display: none;' : '' ); ?>" class="fs_snd_badge"><?=$failedAccountsCount['reddit']?></div>
				<div style="background: #00a8ef;" class="fs_snd_badge"><?=$accountsCount['reddit']?></div>
			</div>
		</div>
		<div class="fs_social_network_div" data-setting="tumblr">
			<div><i class="fab fa-tumblr-square"></i> Tumblr</div>
			<div style="display: flex;">
				<div style="background: #ff0000;<?php echo ( $failedAccountsCount['tumblr'] === 0 ? ' display: none;' : '' ); ?>" class="fs_snd_badge"><?=$failedAccountsCount['tumblr']?></div>
				<div style="background: #00a8ef;" class="fs_snd_badge"><?=$accountsCount['tumblr']?></div>
			</div>
		</div>
		<div class="fs_social_network_div" data-setting="ok">
			<div><i class="fab fa-odnoklassniki"></i> OK.ru</div>
			<div style="display: flex;">
				<div style="background: #ff0000;<?php echo ( $failedAccountsCount['ok'] === 0 ? ' display: none;' : '' ); ?>" class="fs_snd_badge"><?=$failedAccountsCount['ok']?></div>
				<div style="background: #00a8ef;" class="fs_snd_badge"><?=$accountsCount['ok']?></div>
			</div>
		</div>
		<div class="fs_social_network_div" data-setting="google_b">
			<div><i class="fab fa-google"></i> Google MyBusiness</div>
			<div style="display: flex;">
				<div style="background: #ff0000;<?php echo ( $failedAccountsCount['google_b'] === 0 ? ' display: none;' : '' ); ?>" class="fs_snd_badge"><?=$failedAccountsCount['google_b']?></div>
				<div style="background: #00a8ef;" class="fs_snd_badge"><?=$accountsCount['google_b']?></div>
			</div>
		</div>
		<div class="fs_social_network_div" data-setting="telegram">
			<div><i class="fab fa-telegram"></i> Telegram</div>
			<div style="display: flex;">
				<div style="background: #ff0000;<?php echo ( $failedAccountsCount['telegram'] === 0 ? ' display: none;' : '' ); ?>" class="fs_snd_badge"><?=$failedAccountsCount['telegram']?></div>
				<div style="background: #00a8ef;" class="fs_snd_badge"><?=$accountsCount['telegram']?></div>
			</div>
		</div>
		<div class="fs_social_network_div" data-setting="medium">
			<div><i class="fab fa-medium"></i> Medium</div>
			<div style="display: flex;">
				<div style="background: #ff0000;<?php echo ( $failedAccountsCount['medium'] === 0 ? ' display: none;' : '' ); ?>" class="fs_snd_badge"><?=$failedAccountsCount['medium']?></div>
				<div style="background: #00a8ef;" class="fs_snd_badge"><?=$accountsCount['medium']?></div>
			</div>
		</div>
		<div class="fs_social_network_div" data-setting="wordpress">
			<div><i class="fab fa-wordpress"></i> WordPress</div>
			<div style="display: flex;">
				<div style="background: #ff0000;<?php echo ( $failedAccountsCount['wordpress'] === 0 ? ' display: none;' : '' ); ?>" class="fs_snd_badge"><?=$failedAccountsCount['wordpress']?></div>
				<div style="background: #00a8ef;" class="fs_snd_badge"><?=$accountsCount['wordpress']?></div>
			</div>
		</div>
	</div>
	<div style="width: 100%;" id="account_content">

	</div>
</div>

<script>

	jQuery(document).ready(function()
	{
		if( typeof $ == 'undefined' ) var $ = typeof jQuery == 'undefined' ? null : jQuery;

		var currentSettings;
		$("#fs_account_supports>[data-setting]").click(function()
		{
			currentSettings = $(this).attr('data-setting');
			$("#fs_account_supports .fs_snd_active").removeClass('fs_snd_active');
			$(this).addClass('fs_snd_active');

			fsCode.ajax('get_accounts' , {'name': currentSettings}, function(result)
			{
				$("#account_content").html(fsCode.htmlspecialchars_decode(result['html']));

				$('#fs_account_supports .fs_social_network_div[data-setting="'+currentSettings+'"] .fs_snd_badge').text( $("#accounts_count").text() );
			});

			window.history.pushState({},"", '?page=fs-poster&tab=' + currentSettings);
		});

		$('#fs_account_supports>[data-setting="<?=htmlspecialchars($activeTab)?>"]').click();

		$("#account_content").on('click' , '.fs_account_checkbox' , function()
		{
			var checked     = $(this).hasClass("fs_account_checked"),
				dataId      = $(this).closest('tr').data('id'),
				dataType    = $(this).closest('tr').data('type');

			$("#fs_sub_menu")
				.show()
				.css('top' , $(this).offset().top + 25 - $(window).scrollTop())
				.css('left' , $(this).offset().left - ($("#fs_sub_menu").width()/2) + 10)
				.data('id' , dataId)
				.data('type' , dataType ? dataType : 'account');
		}).on('click', '.more_options_account', function ()
		{
			var checked     = $(this).hasClass("fs_account_checked"),
				dataId      = $(this).closest('tr').data('id'),
				dataType    = $(this).closest('tr').data('type');

			if( $(this).closest('tr').find('.fs_account_is_public').css('display') == 'none' )
			{
				$('#fs_sub_menu2 > [data-type="public"]').show();
				$('#fs_sub_menu2 > [data-type="private"]').hide();
			}
			else
			{
				$('#fs_sub_menu2 > [data-type="private"]').show();
				$('#fs_sub_menu2 > [data-type="public"]').hide();
			}

			$("#fs_sub_menu2")
				.show()
				.css('top' , $(this).offset().top + 35 - $(window).scrollTop())
				.css('left' , $(this).offset().left - ($("#fs_sub_menu2").width()/2) + 10)
				.data('id' , dataId)
				.data('type' , dataType ? dataType : 'account');
		}).on('click', '.fs_expand_all_btn', function()
		{
			$('.fs_communities_area').slideDown(200, function()
			{
				$(this).prev('table').find('.fs_expand_icon > .fa-angle-right').attr('class', 'fa fa-angle-down');
			});
		}).on('click', '.fs_collapse_all_btn', function()
		{
			$('.fs_communities_area').slideUp(200, function()
			{
				$(this).prev('table').find('.fs_expand_icon > .fa-angle-down').attr('class', 'fa fa-angle-right');
			});
		}).on('click', '.fs_expand_icon', function()
		{
			var arrow = $(this).children('i');

			$(this).closest('table').next('.fs_communities_area').slideToggle(400, function()
			{
				arrow.attr('class', arrow.hasClass('fa-angle-down') ? 'fa fa-angle-right' : 'fa fa-angle-down');
			});
		});

		$(document).click(function(e)
		{
			if( !$(e.target).is('.fs_account_checkbox , .fs_account_checkbox > i') )
			{
				$("#fs_sub_menu").hide();
			}
			if( !$(e.target).is('.more_options_account , .more_options_account > i') )
			{
				$("#fs_sub_menu2").hide();
			}
		});

        $( document ).on( 'click', '#fs_account_refetch', function () {
            const _this = $( this );
            const socialNetwork = _this.data( 'social-network' );
            const accountId = _this.data( 'account-id' );

            if ( socialNetwork === 'vk' ) {
                fsCode.ajax('refetch_vk_account' , { 'accountId': accountId }, function ( data ) {
                    fsCode.toast("<?=esc_html__('Account refetched successfully!' , 'fs-poster')?>" , 'success');
                    $('#fs_account_supports .fs_social_network_div[data-setting="vk"]').click();
                });
            }
        } );

		$("#fs_sub_menu > .activate_with_condition_btn").click(function()
		{
			var dataId      = $('#fs_sub_menu').data('id'),
				dataType    = $('#fs_sub_menu').data('type') == 'community' ? 'node' : 'account';

			fsCode.loadModal('activate_with_condition' , {'id': dataId, 'type': dataType});
		});

		$("#fs_sub_menu > .activate_btn").click(function()
		{
			var dataId      = $('#fs_sub_menu').data('id'),
				nType       = $('#fs_sub_menu').data('type'),
				dataType    = nType === 'community' ? 'settings_node_activity_change' : 'account_activity_change';

			fsCode.ajax(dataType , {'id': dataId, 'checked': 1});
			$('tr[data-id="' + dataId + '"][data-type="' + nType + '"] .fs_account_checkbox').addClass('fs_account_checked').removeClass('fs_account_checked2');
		});

		$("#fs_sub_menu > .deactivate_btn").click(function()
		{
			var dataId		= $('#fs_sub_menu').data('id'),
				dataType	= $('#fs_sub_menu').data('type') == 'community' ? 'settings_node_activity_change' : 'account_activity_change';

			fsCode.ajax(dataType , {'id': dataId, 'checked': 0} );
			$("tr[data-id=\"" + dataId + "\"] .fs_account_checkbox").removeClass('fs_account_checked').removeClass('fs_account_checked2');
		});

		$("#fs_sub_menu2 > .make_public_action").click(function()
		{
			var dataId		= $('#fs_sub_menu2').data('id'),
				dataType	= $('#fs_sub_menu2').data('type');

			var trObj		= $("tr[data-id='" + dataId + "'][data-type='" + dataType + "']");
			var checked		= trObj.find(".fs_account_is_public").css('display') != 'none';

			var ajaxAction = dataType == 'community' ? 'settings_node_make_public' : 'make_account_public';

			fsCode.ajax(ajaxAction , {'id': dataId, 'checked': checked?0:1}, function()
			{
				if( checked )
				{
					trObj.find(".fs_account_is_public").hide(200);
				}
				else
				{
					trObj.find(".fs_account_is_public").show(200);
				}
			});
		});

		$("#fs_sub_menu2 > .delete_account_action").click(function()
		{
			var dataId		= $('#fs_sub_menu2').data('id'),
				dataType	= $('#fs_sub_menu2').data('type'),
				tr      	= $("tr[data-id='" + dataId + "'][data-type='" + dataType + "']");

			fsCode.confirm("<?=esc_html__('Are you sure you want to delete?' , 'fs-poster')?>" , 'danger' , function ()
			{
				var ajaxAction = dataType == 'community' ? 'settings_node_delete' : 'delete_account';

				fsCode.ajax(ajaxAction , {'id': dataId} , function(result)
				{
					if( dataType == 'community' )
					{
						tr.fadeOut(300, function()
						{
							$(this).remove();
						});
					}
					else
					{
						tr.closest('table').fadeOut(300, function()
						{
							$(this).remove();

							if( $(".ws_table>tbody>tr").length == 0 )
							{
								$("#account_content .ws_table_wraper").append('<table class="ws_table"><tbody><tr><td colspan="100%" style="color: #999;">No account found</td></tr></tbody></table>').children('tr').hide().fadeIn(200);
							}
							$("#accounts_count").text(parseInt($("#accounts_count").text()) - 1);
							var oldCount = $('#fs_account_supports .fs_social_network_div[data-setting="'+currentSettings+'"] .fs_snd_badge').text().trim();
							$('#fs_account_supports .fs_social_network_div[data-setting="'+currentSettings+'"] .fs_snd_badge').text(parseInt(oldCount) - 1);
						});

						tr.closest('table').next('.fs_communities_area').fadeOut(200, function()
						{
							$(this).remove();
						});
					}

				});
			}, true);
		});

	});

</script>