<?php
require '../../../wp-blog-header.php';
require __DIR__ . '/composer/vendor/autoload.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 = doPostToInstagram($campaign, $post);
	echo "Cron Finished <br/>\n";
	break;
case 1:
	doCustomToInstagram($campaign);
	echo "Custom To Instagram <br/>\n";
	break;
case 2:
	smDoFollow($campaign);
	echo "Following... Insta Cron Finished <br/>\n";
	break;
}

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

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

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

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

function smPostToInstagram($wpPostId, $link, $title, $imgURL, $campaignId, $logAction='WP Post to Instagram') {
	$smIGUser = get_post_meta(111111113, $campaignId . 'smIGUser', true);
	$smIGPassword = get_post_meta(111111113, $campaignId . 'smIGPassword', true);

	$instagram = new \Instagram\Instagram();
	$uniqueName = 'tempfile-' . uniqid();

	try {
		file_put_contents($uniqueName, file_get_contents($imgURL));
	} catch (\Exception $e) {
		echo "cannot open file.";
		return false;
	}

	try {
		$instagram->login($smIGUser, $smIGPassword);
		$response = $instagram->postPhoto($uniqueName, $title);

		sm_add_to_master_log($logAction, $campaignId, $wpPostId, "https://instagram.com/" . $response->getUploadId(), $link);

		unlink($uniqueName);

		echo "successfully posted to instagram";
		return true;
	} catch (\Exception $e) {
		unlink($uniqueName);
		echo 'Something went wrong: ' . $e->getMessage() . "\n";
		return false;
	}

	return false;
}

function smDoFollow($campaign) {
	$smIGUser = get_post_meta(111111113, $campaign . 'smIGUser', true);
	$smIGPassword = get_post_meta(111111113, $campaign . 'smIGPassword', true);

	$instagram = new \Instagram\Instagram();

	try {
		$instagram->login($smIGUser, $smIGPassword);
		$userName = selectRandomInstagramUser($campaign);

		if (empty($userName)) {
			echo "No user found";
			exit;
		}

		$users = $instagram->searchUsers($userName);
		$limit = rand(1, 3);

		foreach ($users->getUsers() as $user) {
			$status = $instagram->showFriendship($user->getPk());
			if ($status->isFollowing()) {
				continue;
			}

			$res = $instagram->followUser($user->getPk());
			sm_add_to_master_log("Instagram Follow User", $campaign, $user->getPk(), "https://instagram.com/" . $user->getUsername());

			$limit--;

			smDoLikeUsersMedia($instagram, $user->getPk(), $campaign);

			if ($limit <= 0) {
				break;
			}
			sleep(5);
		}

		echo "Finish";
	} catch (\Exception $e) {
		echo 'Something went wrong: ' . $e->getMessage() . "\n";
		exit(0);
	}
}

function selectRandomInstagramUser($campaign) {
	global $wpdb;
	$wpdb->show_errors();

	$table_name = $wpdb->prefix . "sminstacrons";
	$query = "SELECT keyword FROM $table_name WHERE campaign='$campaign' ORDER BY RAND() limit 1";
	$keyword = $wpdb->get_var($query);

	return $keyword;
}

function smDoLikeUsersMedia($instagram, $userId, $campaignId) {
	$limit = rand(1, 3);
	$feeds = $instagram->getUserFeed($userId);
	$items = $feeds->getItems();
	shuffle($items);
	$randomItemKeys = array_rand($items, $limit);

	foreach ($randomItemKeys as $key) {
		$instagram->likeMedia($items[$key]);
		sm_add_to_master_log("Instagram Like User Media", $campaignId, $items[$key]->getId(), "https://instagram.com/p/" . $items[$key]->getCode());

		sleep(5);
	}
}
