<?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 = doPostToPinterest($campaign, $post);
	break;
case 1:
  $res = doCustomToPinterest($campaign);
	break;
}

echo "Finished...";

function doPostToPinterest($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 Pinterest', $campaignId, $wpPostId) == 0) {
		$imgURL = get_the_post_thumbnail_url($post->ID, 'full');
		smPostToPinterest($wpPostId, $permalink, $post->post_title, $imgURL, $campaignId);
		return true;
	} else {
		echo "Post already posted to pinterest<br/>\n";
		return false;
	}
}

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

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

  if (sm_check_in_master_log('Custom to Pinterest', $campaignId, $custom->id) == 0) {
    smPostToPinterest($custom->id, $custom->url, $custom->headline, $custom->image, $campaignId, 'Custom to Pinterest');
    return true;
  } else {
    echo "Custom {$custom->id} already posted to pinterest<br/>\n";
    return false;
  }
}

function smPostToPinterest($wpPostId, $link, $title, $imgURL, $campaignId, $logAction='WP Post to Pinterest Board') {

	if (empty($imgURL)) {
		echo "No Image. Skipping...";
		return false;
	}
	$email = get_post_meta(111111113, $campaignId . 'smPnEmail', TRUE);
	$password = get_post_meta(111111113, $campaignId . 'smPnPassword', TRUE);
	$boardID = get_post_meta(111111113, $campaignId . 'smPnBoard', TRUE);

	$nxs_gCookiesArr = smGetSavedPinterestLogin();

	$nt = new nxsAPI_PN();
	$nt->ck = $nxs_gCookiesArr;
	$loginError = $nt->connect($email, $password);

	if (!$loginError) {
		smSavePinterestLogin($nt->ck);
		$return = $nt->post($title, $imgURL, $link, $boardID);

		if (is_array($return)) {
			sm_add_to_master_log($logAction, $campaignId, $wpPostId, $return['post_url'], $link);
			// var_dump($return);
			return true;
		} else {
			var_dump(smReversePrintR($return));
			return false;
		}
	} else {
		var_dump($loginError);
		return false;
	}
}
