<?php

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

if ( ! is_logged_in($user) ) {
    return header("location: $site_url");
}

function DisplayForm ($values, $errors)
{

//    $brandService = new BrandService();
//    $brands = $brandService->getAllBrands();
//    if (count($brands) == 0)
//    {
//        header('location:add_brand.php');
//        return;
//    }

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

function VerifyForm (&$values, $errors)
{
    return true;
}

function ProcessForm ($values)
{
    $service = new BrandService();
    $brand = $service->getBrandByName ($values['brand']);
    $geometry = new Geometry ($values);
    $geometry->brand_id = $brand->id;
    $geometry->approved = 0;
    $geometry->user_id = get_user_id ();

    $geometryService = new GeometryService();
    $geometryService->createGeometry ($geometry);
    header ('location:geometries.php');
}

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

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

    if (!VerifyForm ($formValues, $formErrors))
        DisplayForm ($formValues, $formErrors);
    else
        ProcessForm ($formValues);
}
else
{
    if (!isset ($_SESSION['brand']))
    {
        $brandService = new BrandService();
        $brands = $brandService->getAllBrands ();

        $smarty = new Smarty;
        $smarty->assign ('brands', $brands);
        $smarty->assign ('action', "add_frame.php");
        $smarty->display ('views/selectbrand.tpl');
    }
    else
    {
        $formValues['brand'] = $_SESSION['brand'];
        DisplayForm ($formValues, null);
    }
}
?>
