<?php
require '../../../wp-blog-header.php';

set_time_limit(200);
function return_300($seconds) {
	// change the default feed cache recreation period to 2 hours
	return 300;
}

add_filter('wp_feed_cache_transient_lifetime', 'return_300');

$campaign = smSelectCampaign();

if (empty($campaign)) {
	echo "no campaign selected <br/>\n";
	exit;
}

switch (rand(1, 100) % 3) {
case 0:
	$post = smChooseWPPost($campaign);
	if (empty($post)) {
		echo "nothing to post <br/>\n";
		exit;
	}
	$res = doPostToReddit($campaign, $post);
	break;
case 1:
  doCustomToReddit($campaign);
	break;
}

echo "Cron Finished <br/>\n";

function doPostToReddit($campaignId, $wpPostId) {
	$permalink = get_permalink(intval($wpPostId));
	$post = get_post(intval($wpPostId));

	if (empty($post)) {
		echo "No Post found with given ID<br/>\n";
		return;
	}

	if (sm_check_in_master_log('WP Post To Reddit', $campaignId, $wpPostId) == 0) {
		$imgURL = get_the_post_thumbnail_url($post->ID, 'full');
		smPostToReddit($permalink, $post->post_title, $imgURL, $campaignId, $wpPostId);
	} else {
		echo "Post already posted to facebook<br/>\n";
	}
}

function doCustomToReddit($campaignId) {
  $custom = smGetCustom($campaignId);

  if (empty($custom)) {
    echo "No custom Post found<br/>\n";
    return;
  }

  if (sm_check_in_master_log('Custom To Reddit', $campaignId, $custom->id) == 0) {
    smPostToReddit($custom->url, $custom->headline, $custom->image, $campaignId, $custom->id, 'Custom To Reddit');
  } else {
    echo "Custom {$custom->id} already posted to facebook<br/>\n";
  }
}

function smPostToReddit($link, $title, $imgURL, $campaign, $wpPostId, $logAction='WP Post To Reddit') {
	if (!class_exists('OAuth2/Client')) {
		require_once __DIR__ . '/oauth2/Client.php';
		require_once __DIR__ . "/oauth2/GrantType/IGrantType.php";
		require_once __DIR__ . "/oauth2/GrantType/AuthorizationCode.php";
		require_once __DIR__ . "/oauth2/GrantType/RefreshToken.php";
	}

	$clientId = get_post_meta(111111113, $campaign . 'smRdID', TRUE);
	$clientSecret = get_post_meta(111111113, $campaign . 'smRdSecret', TRUE);
	$refreshtoken = get_post_meta(111111113, $campaign . 'smRdRefreshToken', TRUE);

	$userAgent = 'SocialTrafficBot Pro by DanGreen';
	$client = new OAuth2\Client($clientId, $clientSecret, OAuth2\Client::AUTH_TYPE_AUTHORIZATION_BASIC);
	$client->setCurlOption(CURLOPT_USERAGENT, $userAgent);

	$response = $client->getAccessToken('https://ssl.reddit.com/api/v1/access_token', "refresh_token", array("refresh_token" => $refreshtoken));

	update_post_meta(111111113, $campaign . 'smRdAccessToken', $response["result"]["access_token"]);

	$accesstoken = $response["result"]["access_token"];

	$client->setAccessToken($accesstoken);
	$client->setAccessTokenType(OAuth2\Client::ACCESS_TOKEN_BEARER);

	$subreddit = get_post_meta(111111113, $campaign . 'smRdPage', TRUE);

	$data = array(
		'api_type' => 'json',
		'kind' => 'link',
		'url' => $link,
		'title' => $title,
		'text' => $title,
		'sr' => $subreddit,
	);

	$response = $client->fetch("https://oauth.reddit.com/api/submit", $data, OAuth2\Client::HTTP_METHOD_POST);

	if (count($response['result']['json']['errors']) > 0) {
    // var_dump(count($response['result']['json']['errors']));
		return false;
	} else {
		sm_add_to_master_log($logAction, $campaign, $wpPostId, $response['result']['json']['data']['url'], $link);
		return true;
	}
}
