<?php
include_once './config.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)
{
    $smarty = new Smarty;
    $smarty->assign('values', $values);
    $smarty->assign('errors', $errors);
    $smarty->display('views/update_brand.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 $ret;
}

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

    $brandService = new BrandService();
    $ret = $brandService->updateBrand($brand);

    header("location:brands.php?brand=$brand->name");
}

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['brand_id']))
    {
        $brand_id = $_GET['brand_id'];

        $brandService = new BrandService();
        $brand = $brandService->getBrandByID($brand_id);
        if ($brand !== null)
            DisplayForm((array) $brand, null);
        else
            header('location:brands.php');
    }
}


?>

