<?php

define('TIME_NOW',  time());
define('DS',        DIRECTORY_SEPARATOR);
define('BASE_PATH', strtr(__DIR__, '\\', '/'));

clearstatcache();

$pathimpl = function() {
  return BASE_PATH . '/' . ltrim(strtr(implode(DS, func_get_args()), '\\', '/'), '/');
};

$populationfile  = $pathimpl('population.json');
$cachefile       = $pathimpl('.cache');
$is_cache        = is_file($cachefile);
$cachesize       = filesize($cachefile);
$flag            = 0;

if (!$is_cache || !$cachesize) {
  touch($cachefile);
  clearstatcache();
  $flag = 1;
}

$cache_filemtime = filemtime($cachefile);
$cachetime       = intval(TIME_NOW - $cache_filemtime);

if (!$flag && $cachetime > 3600) {
  $flag = 1;
}

if ($flag > 0) {
  $json = file_get_contents("https://api.apify.com/v2/key-value-stores/tVaYRsPHLjNdNBu7S/records/LATEST?disableRedirect=true", 0, stream_context_create(
      array(
        'http' => array(
          'method'                    => 'GET',
          'header'                    => array(),
          'user_agent'                => 'PHP/7.3.12',
          'content'                   => '',
          'proxy'                     => '',
          'request_fulluri'           => FALSE,
          'follow_location'           => 1,
          'max_redirects'             => 2,
          'protocol_version'          => '1.0',
          'timeout'                   => 5,
          'ignore_errors'             => TRUE
        )
      )
    )
  );
  if (!$json) { echo "Err[0x01]: [JSON]: NO_DATA\n"; exit(1); }
  $json = json_decode($json, true);
  if (!$json) { echo "Err[0x02]: [JSON]: DECODE_ERROR\n"; exit(1); }
  file_put_contents($cachefile, json_encode($json));
} else {
  $json = file_get_contents($cachefile);
  if (!$json) { echo "Err[0x03]: [JSON]: DECODE_ERROR\n"; exit(1); }
  $json = json_decode($json, true);
  if (!$json) { echo "Err[0x04]: [JSON]: DECODE_ERROR\n"; exit(1); }
}

$pjson = json_decode(file_get_contents($populationfile), true);

$array = array();
foreach($pjson as $_data) {
  $country = strtolower($_data['country']);
  $array[$country]['population'] = intval($_data['population']);
}

$pjson = $array;

$array = array();
foreach($json as $_data) {
  $country = strtolower($_data['country']);
  $array[$country] = array();
  foreach($_data as $k => $v) {
    $array[$country][$k] = $v;
  }
}

$json = $array;
$array = array();

foreach($json as $country => $data) {
  if (isset($pjson[$country])) {
    $json[$country]['population'] = $pjson[$country]['population'];
    $array[$country] = $json[$country];
  }
}

$data = $array;
$json = array();
$array = array();

?><!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body style="width:100%;float:left">
<div style="width:100%;max-width:1200px;float:none;margin: 0 auto;">

<?php
echo "<table style=\"width:100%\">\n";

  echo "<caption></caption>\n";

  echo "<thead>\n";
    echo "<tr>\n";
      echo "<th style=\"text-align: left;\">Страна / Country</th>\n";
      echo "<th style=\"text-align: left;\">Заражений / Infected</th>\n";
      echo "<th style=\"text-align: left;\">Население / Population</th>\n";
      echo "<th style=\"text-align: left;\">Процент / Percentage</th>\n";
    echo "</tr>\n";
  echo "</thead>\n";

  echo "<tbody>\n";

foreach($data as $country => $_data) {
  $population =& $_data['population'];
  $infected =& $_data['infected'];
  $percentage = round(($infected / $population) * 100, 4);

    echo "<tr>\n";
      echo "<td>{$country}</td>\n";
      echo "<td>{$infected}</td>\n";
      echo "<td>{$population}</td>\n";
      echo "<td>{$percentage}</td>\n";
    echo "</tr>\n";
}

  echo "</tbody>\n";

  echo "<tfoot>\n";
    echo "<tr>\n";
      echo "<td></td>\n";
    echo "</tr>\n";
  echo "</tfoot>\n";

echo "</table>\n";

?>

</div>
</body>
</html>