<?php

include_once './config.php';
include_once './models/services/FrameService.php';
include_once './models/services/GeometryService.php';
include_once './models/services/BrandService.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']);

    $brandService = new BrandService();
    $brand = $brandService->getBrandByID ($values['brand_id']);

    $smarty = new Smarty;
    $smarty->assign ('values', $values);
    $smarty->assign ('errors', $errors);
    $smarty->assign ('geometries', $geometries);
    $smarty->assign ('brand', $brand);

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

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

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


    $frameService = new FrameService();
    $frameService->updateFrame ($frame);

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

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;    
    
    try
    {
        if (!VerifyForm ($formValues, $formErrors))
            DisplayForm ($formValues, $formErrors);
        else
            ProcessForm ($formValues);
    }
    catch (Exception $e)
    {
        echo $e->getMessage ();
        DisplayForm ($formValues, $formErrors);
    }
}
else
{

    $frame_id = $_GET['id'];

    if ($frame_id !== null)
    {

        $frameService = new FrameService();
        $frame = $frameService->getFrameByID ($frame_id);

        if ($frame !== null)
            DisplayForm ((array) $frame, null);
        else
            header ('location:frames.php');
    }
}
?>
