<?php

namespace FSPoster\App\Controller;

use FSPoster\App\Controller\Ajax\Accounts;
use FSPoster\App\Controller\Ajax\App;
use FSPoster\App\Controller\Ajax\Nodes;
use FSPoster\App\Controller\Ajax\Reports;
use FSPoster\App\Controller\Ajax\Schedule;
use FSPoster\App\Controller\Ajax\Settings;
use FSPoster\App\Controller\Ajax\Share;
use FSPoster\App\Controller\Ajax\SharePanel;
use FSPoster\App\Providers\Curl;
use FSPoster\App\Providers\Helper;
use FSPoster\App\Providers\Request;
use FSPoster\App\Providers\DB;
use FSPoster\App\Lib\fb\Facebook;

class Ajax
{

	use Accounts,
		App,
		Nodes,
		Reports,
		Share,
		Schedule,
		Settings,
		SharePanel;

	public function __construct()
	{
		$methods = get_class_methods( $this );

		foreach ($methods AS $method)
		{
			if( $method == '__construct' )
			{
				continue;
			}

			add_action( 'wp_ajax_' . $method, function() use($method)
			{
				$this->$method();
				exit();
			});
		}
	}

	public function activate_app()
	{
		$code		= Request::post('code' , '' , 'string');
		$statistic	= Request::post('statistic' , '' , 'string');

		if( empty($code) || empty($statistic) )
		{
			Helper::response(false, 'Please type purchase key!');
		}

		if( Helper::getOption('poster_plugin_installed' , '0', true) )
		{
			Helper::response(false , 'Your plugin is already installed!');
		}

		set_time_limit(0);

		$checkPurchaseCodeURL = FS_API_URL . "api.php?act=install&version=" . Helper::getVersion() . "&purchase_code=" . $code . "&domain=" . network_site_url() . "&statistic=" . $statistic;
		$result2 = Curl::getURL($checkPurchaseCodeURL);

		$result = json_decode($result2 , true);
		if( !is_array( $result ) )
		{
			if( empty( $result2 ) )
			{
				Helper::response( false , 'Your server can not access our license server via CURL! Our license server is "' . htmlspecialchars(FS_API_URL) . '". Please contact your hosting provider/server administrator and ask them to solve the problem. If you are sure that problem is not your server/hosting side then contact FS Poster administrators.' );
			}

			Helper::response(false , 'Installation error! Rosponse error! Response: ' . htmlspecialchars($result2));
		}

		if( !($result['status'] == 'ok' && isset($result['sql'])) )
		{
			Helper::response(false , isset($result['error_msg']) ? $result['error_msg'] : 'Error! Response: ' . htmlspecialchars($result2));
		}

		$sql = str_replace( ['{tableprefix}', '{tableprefixbase}'] , [(DB::DB()->base_prefix . DB::PLUGIN_DB_PREFIX), DB::DB()->base_prefix] , base64_decode($result['sql']) );

		if( empty($sql) )
		{
			Helper::response(false , 'Error! Please contact the plugin administration! (info@fs-code.com)');
		}

		foreach( explode(';' , $sql) AS $sqlQueryOne )
		{
			$checkIfEmpty = preg_replace('/\s/', '', $sqlQueryOne);
			if( !empty( $checkIfEmpty ) )
			{
				DB::DB()->query( $sqlQueryOne );
			}
		}

		register_uninstall_hook( FS_ROOT_DIR . '/init.php', [ Helper::class, 'removePlugin' ]);

		Helper::setOption('poster_plugin_installed', Helper::getVersion(), true );
		Helper::setOption('poster_plugin_purchase_key', $code, true );

		Helper::response(true);
	}

	public function update_app()
	{
		$code = Request::post('code' , '' , 'string');

		if( empty($code) )
		{
			Helper::response(false, 'Please type purchase key!');
		}

		if( Helper::getOption('poster_plugin_installed', '0', true) == Helper::getVersion() )
		{
			Helper::response(false , 'Your plugin is already updated!');
		}

		$result = self::updatePlugin( $code );

		if( $result[0] )
		{
			Helper::response(true);
		}
		else
		{
			Helper::response(false , $result[1]);
		}
	}

	public static function updatePlugin( $code )
	{
		set_time_limit(0);

		register_uninstall_hook( FS_ROOT_DIR . '/init.php', [ Helper::class, 'removePlugin' ]);

		$checkPurchaseCodeURL = FS_API_URL . "api.php?act=update&version1=" . Helper::getInstalledVersion() . "&version2=" . Helper::getVersion() . "&purchase_code=" . $code . "&domain=" . network_site_url();
		$result2 = Curl::getURL($checkPurchaseCodeURL);

		$result = json_decode($result2 , true);

		if( !is_array( $result ) )
		{
			if( empty( $result2 ) )
			{
				return [ false , 'Your server can not access our license server via CURL! Our license server is "' . htmlspecialchars(FS_API_URL) . '". Please contact your hosting provider/server administrator and ask them to solve the problem. If you are sure that problem is not your server/hosting side then contact FS Poster administrators.' ];
			}

			return [ false , 'Installation error! Rosponse error! Response: ' . htmlspecialchars($result2) ];
		}

		if( !($result['status'] == 'ok' && isset($result['sql'])) )
		{
			return [ false , isset($result['error_msg']) ? $result['error_msg'] : 'Error! Response: ' . htmlspecialchars($result2) ];
		}

		$sql = str_replace( ['{tableprefix}', '{tableprefixbase}'] , [(DB::DB()->base_prefix . DB::PLUGIN_DB_PREFIX), DB::DB()->base_prefix] , base64_decode($result['sql']) );

		foreach( explode(';' , $sql) AS $sqlQueryOne )
		{
			$checkIfEmpty = preg_replace('/\s/', '', $sqlQueryOne);
			if( !empty( $checkIfEmpty ) )
			{
				DB::DB()->query( $sqlQueryOne );
			}
		}

		Helper::setOption('poster_plugin_installed', Helper::getVersion(), true );
		Helper::setOption('poster_plugin_purchase_key', $code, true );

		return [ true ];
	}

}