<?php

$oldDir = getcwd();
chdir(dirname(__FILE__));
include_once 'connect.admin.db.php';
include_once '../install-funcs.inc.php';
include_once '../classes/Metadata.class.php';
include_once '../classes/MetadataFactory.class.php';
include_once '../classes/RegionFactory.class.php';
$imtFactory = new MetadataFactory($db, 'imt');
$vs30Factory = new MetadataFactory($db, 'vs30');
$editionFactory = new MetadataFactory($db, 'edition');
$regionFactory = new RegionFactory($db);
include_once './metadata.php';
try {
    if (promptYesNo('Do you want to create tables/views?', true)) {
        $db->beginTransaction();
        $db->exec(file_get_contents('./schema.sql'));
        $db->exec('GRANT SELECT ON ALL TABLES IN SCHEMA ' . $CONFIG['DB_SCHEMA'] . ' TO ' . $CONFIG['DB_USER']);
        $db->commit();
        echo 'Finished creating tables/views.' . PHP_EOL;
    }
    if (promptYesNo('Do you want to load metadata?', true)) {
        $db->beginTransaction();
        foreach ($imts as $imt) {
            $imtFactory->set($imt);
        }
        foreach ($vs30s as $vs30) {
            $vs30Factory->set($vs30);
        }
        foreach ($editions as $edition) {
    $editionInput = array_shift($tokens);
    $regionInput = array_shift($tokens);
    $longitude = safefloatval(array_shift($tokens));
    $latitude = safefloatval(array_shift($tokens));
    $imtInput = array_shift($tokens);
    $vs30Input = array_shift($tokens);
} else {
    $editionInput = isset($_GET['edition']) ? $_GET['edition'] : null;
    $regionInput = isset($_GET['region']) ? $_GET['region'] : null;
    $longitude = isset($_GET['longitude']) ? floatval($_GET['longitude']) : null;
    $latitude = isset($_GET['latitude']) ? floatval($_GET['latitude']) : null;
    $imtInput = isset($_GET['imt']) ? $_GET['imt'] : null;
    $vs30Input = isset($_GET['vs30']) ? $_GET['vs30'] : null;
}
$editionFactory = new MetadataFactory($DB, 'edition');
$regionFactory = new RegionFactory($DB);
$imtFactory = new MetadataFactory($DB, 'imt');
$vs30Factory = new MetadataFactory($DB, 'vs30');
$datasetFactory = new DatasetFactory($DB);
$curveFactory = new CurveFactory($DB);
$request = ($_SERVER['HTTPS'] == 'On' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'];
try {
    $curves = array();
    if ($editionInput === 'any') {
        $editions = $editionFactory->getAvailable();
    } else {
        $editions = array($editionFactory->get($editionFactory->getId($editionInput)));
    }
    if ($regionInput === 'any') {
        $regions = $regionFactory->getAvailable();
    } else {