<?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", "true");
error_reporting(E_ALL|E_STRICT);

ini_set("display_errors", "false");

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

// Pull the latest file from Github and parse it
$json = file_get_contents('https://raw.githubusercontent.com/aprsorg/aprs-deviceid/main/generated/tocalls.dense.json');

if ($json)
{
  $data = json_decode($json);
}

// Class Caching
$equipmentClassCache = [];

// Install/update equipment classes
if ($data && isset($data->classes))
{
  foreach ($data->classes as $classCode => $equipmentClass)
  {
    $sql =
      "INSERT INTO equipment_class (class, display_name, description)
        VALUES (?, ?, ?) ON CONFLICT (class) DO UPDATE SET display_name = ?, description = ? RETURNING id;";
    $stmt = $pdo->prepareAndExec
    (
      $sql,
      [
        $classCode,
        $equipmentClass->shown,
        $equipmentClass->description,

        $equipmentClass->shown,
        $equipmentClass->description
      ]
    );
    $equipmentClassCache[$classCode] = $stmt->fetchColumn();
  }
}


// Install/update equipment
if ($data && isset($data->tocalls))
{
  foreach ($data->tocalls as $toCall => $toCallData)
  {
    $toCall = str_replace('?', '*', $toCall);
    $sql =
    "INSERT INTO equipment (class_id, to_call, model, vendor, os, contact, features)
      VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT (to_call) DO UPDATE SET class_id = ?, model = ?, vendor = ?, os = ?, contact = ?, features = ?;";
    $stmt = $pdo->prepareAndExec
    (
      $sql,
      [
        isset($toCallData->class) ? $equipmentClassCache["{$toCallData->class}"] : null,
        $toCall,
        $toCallData->model ?? null,
        $toCallData->vendor ?? null,
        $toCallData->os ?? null,
        $toCallData->vendor ?? null,
        (isset($toCallData->features) ? implode(',', $toCallData->features) : null),

        isset($toCallData->class) ? $equipmentClassCache["{$toCallData->class}"] : null,
        $toCallData->model ?? null,
        $toCallData->vendor ?? null,
        $toCallData->os ?? null,
        $toCallData->vendor ?? null,
        (isset($toCallData->features) ? implode(',', $toCallData->features) : null)
      ]
    );
  }
}
?>
