<?php

include_once './config.php';
include_once './models/services/GeometryService.php';
include_once './libs/Smarty.class.php';

//if ( ! is_updater() )
//    return header('location:http://www.slowtwitch.com');

function DisplayForm ($values, $errors)
{
    $smarty = new Smarty;
    $smarty->assign ('values', $values);
    $smarty->assign ('errors', $errors);

    $smarty->display ('views/update_geometry.tpl');
}

function VerifyForm (&$values, &$errors)
{
//    if (!preg_match("/^(https?:\/\/+[\w\-]+\.[\w\-]+)/i", $url))
//    {
//        $errors["website"] = "Please check the website and resubmit";
//        $ret = false;
//    }

    return true;
}

function ProcessForm ($values)
{
    $geometry = new Geometry ($values);
    $geometry->approved = 0;
    $geometry->user_id = get_user_id ();

    try
    {
//                echo __LINE__ . "\n";
        $geometryService = new GeometryService();
        $geometryService->updateGeometry ($geometry);
//                echo __LINE__ . "\n";
    }
    catch (Exception $e)
    {
//                echo 'Caught exception: ', $e->getMessage (), "\n";
        return;
    }

    header ('location:geometries.php?brand=' . $values['brand']);
}

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    $formValues = $_POST;
    $formErrors = array ();

    if (isset ($_POST['is_road']))
        $formValues['is_road'] = 1;
    else
        $formValues['is_road'] = 0;

    try
    {
        if (!VerifyForm ($formValues, $formErrors))
            DisplayForm ($formValues, $formErrors);
        else
            ProcessForm ($formValues);
    }
    catch (Exception $e)
    {
        echo $e->getMessage ();
        DisplayForm ($formValues, $formErrors);
    }
}
else
{
    $geoID = $_GET['id'];

    if ($geoID !== null)
    {
        $geometryService = new GeometryService();
        $geometry = $geometryService->getGeometryByID ($geoID);
        if ($geometry !== null)
            DisplayForm ((array) $geometry, null);
        else
            header ('location:geometries.php');
    }
}
?>
