<?php

//$url = 'https://api.tvmedia.ca/tv/v4/lineups/' . $lineupID . '/listings/grid';   2022-07-26T08:47:39.000Z
// Example call: samsung.api.clinic/bww/tvguide/fetch.php?key=094KS932&limitchannels=10
if($_GET['key'] == '094KS932') {
 
  echo("Executing request");
  $apiAuthKey = getAPIKey();
  executeAPIFetch($apiAuthKey);

} else {
  echo("NO KEY PROVIDED");
}


function getAPIKey(){
  $encodedData = file_get_contents("apiKeys.json");
  $decodedData = json_decode($encodedData, true);
  $index = rand(0, count($decodedData["apiKeys"]) -1);
  echo($index);
  return $decodedData["apiKeys"][$index]; 
}

function verifyFile() {
  $fileSize = filesize("temp-guide.json");
  if($fileSize > 50000) {
    return true;
  } else {
    return false;
  }
}

function executeAPIFetch($apiKey) {
  $lineupID = '36473D';
  //$lineupID = '2381D';

  $now = new DateTime(); //now
  $hours=6;
  $modified = (clone $now)->sub(new DateInterval("PT{$hours}H"));
  $start = urlencode($modified->format('c')); 

  $hours = 15; 
  $modified = (clone $now)->add(new DateInterval("PT{$hours}H")); 
  $end = urlencode($modified->format('c')); 
  $append = '';
  
  
  if(isset($_GET['limitchannels'])) {
    $append = $append . '&maxchan=' . $_GET['limitchannels'];
  }
  
   if(isset($_GET['usealtapikey'])) {
    $apiKey = '7109026521e974ce170c9dc0dbfc23dd';
  }
  
  
  // $finalURL = $url . '?start=' . $start . '&end=' . $end . $append . '&detail=brief&api_key=' . $apiKey;
  $url = 'https://api.tvmedia.ca/tv/v4/lineups/' . $lineupID . '/listings/grid?start=' . $start .'&end=' . $end . '&timezone=-05:00' . '&detail=brief&api_key=' . $apiKey;
  //$url = 'https://api.tvmedia.ca/tv/v4/lineups/browse' . $lineupID . '/listings/grid?start=' . $start .'&end=' . $end . '&timezone=-05:00' . '&detail=brief&api_key=' . $apiKey;
  $response = file_get_contents($url);
  
  file_put_contents('temp-guide.json', $response);
   $fileCheck = verifyFile();
  if($fileCheck == true) {
    echo("<br /> Passed test. Archiving old data and writing new guide");
    copy('temp-guide.json', 'guide.json');
    archiveCurrent();   
    
  } else {
    echo("Integrity check failed... Dropping changes.");
  }
  
}

function archiveCurrent() {
  $date = date('d-m-y h:i:s');
  $dest = 'archive/' . $date . '.json';
  copy('guide.json', $dest);
}






?>