<?php
require dirname(dirname(__FILE__)) . "/bootstrap.php";

$config = parse_ini_file(ROOT . '/../config/backend.ini', true);

if (is_array($config) && isset($config['bootstrap']))
{
    $databaseconfig = $config['bootstrap'];

    if (!isset($databaseconfig['username']))
    {
        $databaseconfig['username'] = get_current_user();
    }

    $dbconn = pg_pconnect(
      sprintf(
          'dbname=%s host=%s port=%s user=%s password=%s',
          $databaseconfig['database'],
          $databaseconfig['host'],
          $databaseconfig['port'],
          $databaseconfig['username'],
          $databaseconfig['password']
      )
    );

    if ($dbconn === false) die('Could not connect DB!');
} else {
  die('Invalid DB Config!');
}


// Select all aprs_thursday records
$res = pg_query($dbconn, "
  SELECT a.*, split_part(s.name, '-', 1) AS callsign FROM aprs_thursday a LEFT JOIN station s ON (a.station_id = s.id) ORDER BY callsign ASC, net_date ASC
");

$last_callsign = '';
$last_netdate = '';
while (($record = pg_fetch_assoc($res)) !== false)
{
  if ($last_netdate == $record['net_date'] && $last_netdate == $record['net_date']) continue;
    pg_query($dbconn, "
      INSERT INTO aprs_thursday_stats (callsign, checkins) VALUES('{$record['callsign']}', 1) ON CONFLICT (callsign) DO UPDATE SET checkins = aprs_thursday_stats.checkins + 1;
    ");
    $last_callsign = $record['callsign'];
    $last_netdate = $record['net_date'];
}

?>
