<?php

namespace FSPoster\App\Controller\Ajax;

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

trait Share
{
	public function share_post()
	{
		if( !(isset($_POST['id']) && is_numeric($_POST['id']) && $_POST['id'] > 0) )
		{
			exit();
		}

		$feedId = (int)$_POST['id'];

		$res = ShareService::post($feedId);

		Helper::response(true, ['result' => $res]);
	}

	public function share_saved_post()
	{
		$postId				=	Request::post('post_id' , '0' , 'num');
		$nodes				=	Request::post('nodes' , [] , 'array');
		$background			=	!(Request::post('background' , '0' , 'string')) ? 0 : 1;
		$custom_messages	=	Request::post('custom_messages' , [] , 'array');

		if( empty($postId) || empty($nodes) || $postId <= 0 )
		{
			Helper::response(false);
		}

		if( !ShareService::insertFeeds( $postId, $nodes, $custom_messages, false, null, $background, null, true ) )
		{
			Helper::response(false, esc_html__('Not found active account or cammunity for shareing this post!'));
		}

		Helper::response(true);
	}

	public function get_feed_details ()
	{
		$feedId = Request::post('feed_id' , '0' , 'num');

		if ( empty( $feedId ) || $feedId <= 0 )
		{
			Helper::response(false);
		}

		$feed = DB::fetch(
			'feeds',
			[
				'id' => $feedId
			]
		);

		if ( ! $feed )
		{
			Helper::response(false);
		}

		$result = [
			'postId' => $feed['post_id'],
			'nodes' => [ $feed['driver'] . ':' . $feed['node_type'] . ':' . $feed['node_id'] ],
			'customMessages' => []
		];

		if ( ! is_null( $feed['custom_post_message'] ) )
		{
			$result['customMessages'][ $feed['driver'] ] = $feed['custom_post_message'];
		}
		else
		{
			$result['customMessages'][ $feed['driver'] ] = Helper::getOption('post_text_message_' . $feed['driver'], "{title}" );
		}

		DB::DB()->delete( DB::table( 'feeds' ), [ 'id' => $feed['id'] ] );

		Helper::response( true, [ 'result' => $result ] );
	}
}