<?php

include_once './config.php';
include_once './models/services/Database.php';
include_once './models/services/BrandService.php';
include_once'./libs/Smarty.class.php';


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

function DisplayForm($values, $errors)
{    
    $smarty = new Smarty;
    $smarty->assign('values', $values);
    $smarty->assign('errors', $errors);
    $smarty->display('views/add_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']) < 4)
    {
        $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();
    $brandService->createBrand($brand);

    header('location:brands.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
{
        
    DisplayForm(null, null);
}

?>