<?php

$config = [
  'tg_bot_key' => 'BOT_KEY',
  'tg_chat_ids' => [
	'111111111', // user1
	'222222222', // user2
  ],
];

$db_path = '/opt/scripts/epicgames_promotions_bot/db.json';

// Get EpicGames data
// $json_raw = file_get_contents('test.json');
$json_raw = file_get_contents('https://store-site-backend-static-ipv4.ak.epicgames.com/freeGamesPromotions?locale=en-US&country=US&allowCountries=US');
$json = @json_decode($json_raw, true);

// Get db
$db_json_raw = @file_get_contents($db_path);
$db_json = @json_decode($db_json_raw, true);
if (!$db_json) {
	$db_json = [];
}

function isGameHasBeenLogged($db_json, $game_id, $promo_start_date, $promo_end_date) {
	foreach ($db_json as $entry) {
		if ($entry['game_id'] == $game_id && $entry['promo_start_date'] == $promo_start_date && $entry['promo_end_date'] == $promo_end_date) {
			return true;
		}
	}

	return false;
}

$elements = $json['data']['Catalog']['searchStore']['elements'];
foreach ($elements as $el) {
	$game_id = $el['id'];
	$game_title = $el['title'];

	// Get promotion
	$promotion = $el['promotions']['promotionalOffers'][0]['promotionalOffers'][0] ?? null;
	if (!$promotion) continue;
	if (isGameHasBeenLogged($db_json, $game_id, $promotion['startDate'], $promotion['endDate'])) continue;

	// Check is game on FREE discount
	$original_price = $el['price']['totalPrice']['originalPrice'];
	$discount = $el['price']['totalPrice']['discount'];
	if ($original_price == $discount) {
		// echo "{$el['title']}\n";
		// echo "https://www.epicgames.com/store/en-US/p/{$el['productSlug']}\n";
		// echo "\n";

		// Log game
		$db_json[] = [
			'game_id'          => $game_id,
			'game_title'       => $game_title,
			'promo_start_date' => $promotion['startDate'],
			'promo_end_date'   => $promotion['endDate'],
		];

		// Get page slug
		$page_slug = $el['productSlug'];
		if (empty($page_slug)) {
			foreach ($el['catalogNs']['mappings'] as $row) {
				if (isset($row['pageSlug'])) {
					$page_slug = $row['pageSlug'];
					break;
				}
			}
		}

		// Build page url
		$game_url = "https://www.epicgames.com/store/en-US/p/{$page_slug}";

		// Send telegram notification
		$tg_msg_arr = [];
		$tg_msg_arr[] = "EpicGames FREE game out now!\n";
		$tg_msg_arr[] = $el['title'];
		$tg_msg_arr[] = $game_url;
		$tg_msg = implode("\n", $tg_msg_arr);

		foreach ($config['tg_chat_ids'] as $chat_id) {
			echo "sending free epic game noty for user {$chat_id} - {$game_url}\n";
			exec("/usr/bin/curl \"https://api.telegram.org/bot{$config['tg_bot_key']}/sendMessage?chat_id={$chat_id}\" --data-urlencode \"text=${tg_msg}\"");
		}
	}
}

file_put_contents($db_path, json_encode($db_json));