<?php
include_once 'config.php';
include_once './models/services/ModelService.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)
{
    $geometryService = new GeometryService();
    $geometries = $geometryService->getAllGeometriesByBrand($values['brand_id']);

    $smarty = new Smarty;
    $smarty->assign('values', $values);
    $smarty->assign('geometries', $geometries);
    $smarty->assign('errors', $errors);
    $smarty->display('views/update_model.tpl');
}

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

    return true;
}

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

    $modelService = new ModelService();
    $modelService->updateModel($model);
    header('location:models.php');
}

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

    try
    {
        if (!VerifyForm($formValues, $formErrors))
            DisplayForm($formValues, $formErrors);
        else
            ProcessForm($formValues);
    }
    catch (Exception $e)
    {
        echo $e->getMessage();
        DisplayForm($formValues, $formErrors);
    }
}
else
{
    if (isset($_GET['model_id']))
    {
        $model_id = $_GET['model_id'];
        $modelService = new ModelService();
        $model = $modelService->getModelByID($model_id);
        if ($model !== null)
            DisplayForm((array) $model, null);
        else
            header('location:models.php');
    }
}

?>
