<?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();
    $brand = $brandService->getBrandByName($values['brand']);

    $geometryService = new GeometryService();
    $geometries = $geometryService->getAllGeometriesByBrand($brand->id);

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


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

function ProcessForm($values)
{

    try
    {
        $frameService = new FrameService();
        $frame = new Frame($values);
        $frame->approved = 0;
        $frame->user_id = get_user_id();
        $frameService->createFrame($frame);
    }
    catch (Exception $e)
    {
        echo $e->getMessage();
        return;
    }

    header('location:frames.php');
}

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

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

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


    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);
    }
}
?>
