<?php
define('ROOT', dirname(dirname(dirname(__FILE__))));

require_once ROOT . '/includes/autoload.php';
require_once ROOT . '/includes/common.php';

date_default_timezone_set("UTC");

ini_set("error_reporting", "on");
error_reporting(E_ALL);

ini_set("display_errors", "on");

// Database
$pdo = PDOWriterConnection::getInstance();

// First APRS Date of 2023
$firstThursday = new DateTime('2022-04-07 00:00:00 UTC');
$lastEvent = clone $firstThursday;

// Populate all known events since the first one
$aprsThursdayEvents = [];
while ($lastEvent->getTimestamp() < time())
{
  $nextEvent = [];
  $nextEvent['start'] = clone $lastEvent;
  $nextEvent['end'] = clone $nextEvent['start'];
  $nextEvent['end']->modify('+1 day');
  $aprsThursdayEvents[] = $nextEvent;
  $lastEvent = clone $nextEvent['start'];
  $lastEvent->modify('+1 week');
}


function isAPRSTEvent($netDate)
{
  global $aprsThursdayEvents;
  foreach ($aprsThursdayEvents as $event)
  {
    if ($netDate >= $event['start'] && $netDate <= $event['end'])
    {
      return true;
    }
  }
  return false;
}

echo "Opening...\r\n";
$fp = fopen(dirname(__FILE__)."/aprst.txt", "r");

if ($fp)
{
  $imported = 0;
  echo "Processing...\r\n";
    while (($buffer = fgets($fp, 4096)) !== false)
    {
      preg_match('/(....-..-.. ..:..:.. ...:)\s(.[^\>]*)\>(.[^:]*): (.*)/i', $buffer, $matches);

      if (sizeof($matches) == 5 && stripos($matches[4], 'cq hotg') !== false)
      {
        $dateTime = new DateTime(trim($matches[1], ':'));
        if (isAPRSTEvent($dateTime))
        {
          echo "APRSThursday Check-in Found...\r\n";
          echo "From: {$matches[2]}\r\n";
          echo "To: {$matches[3]}\r\n";
          echo "Message: {$matches[4]}\r\n";

          // Find the stations
          $station = StationRepository::getInstance()->getObjectByName(strtoupper(trim($matches[2])) ?? null);
          if ($station != null && $station->id)
          {
            $sql =
            "INSERT INTO aprs_thursday (net_date, station_id, checkin_timestamp )
              VALUES (?, ?, ?) ON CONFLICT (net_date, station_id) DO NOTHING;";
            $stmt = $pdo->prepareAndExec
            (
              $sql,
              [
                $dateTime->format('Y-m-d'),
                $station->id,
                $dateTime->getTimestamp()
              ]
            );
            $imported++;
            echo "Inserted station " . $station->name . " ({$station->id}) found: " . $dateTime->format('Y-m-d') . " TS: " .$dateTime->getTimestamp(). "\r\n";
          }
          else echo "Station " . $station->name . " NOT FOUND!\r\n";
        }
    }
    echo "\r\n$imported records processed.\r\n";
  }
  if (!feof($fp))
  {
      echo "Error: unexpected fgets() fail\n";
  }
  fclose($fp);
}
else {
  echo "Could not open import file: " . dirname(__FILE__)."/aprs_thursday_log.txt";
}

?>
