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


if (! get_user_id())
{
    echo "you must be logged in to use this feature, redirecting...";
    sleep(3);
    header('location:http://forum.slowtwitch.com/gforum.cgi?do=login&from=stackreach');
}



try
{
    $dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);

    $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

    # creating the statement
    $sql = "SELECT brand_id from preferred where user_id=:user_id";
    $sth = $dbh->prepare($sql);
    $sth->setFetchMode(PDO::FETCH_OBJ);
    $sth->execute(array(':user_id' => get_user_id()));
    $preferred = $sth->fetchAll();


    foreach ($preferred as $brand)
    {
        $bs = new BrandService();
        $brands[] = $bs->getBrandByID($brand->brand_id);
        $bs = null;
    }
    
    $brandMap = array();

    foreach ($brands as $brand)
    {
        
        $geometryService = new GeometryService();
        $geometries = $geometryService->getAllGeometriesByBrand($brand->id);

        foreach ($geometries as $geometry)
        {
            $modelService = new ModelService();
            $brandMap[$brand->name][$geometry->name]['models'] = $modelService->getAllModelsByGeometry($geometry->id);

            $frameService = new FrameService();
            $frames = $frameService->getAllFramesByGeometry($geometry->id);


            if ($frames === null) { header('location:add_frame.php');}

            foreach ($frames as $frame)
            {
                $brandMap[$brand->name][$geometry->name]['geometries'][] = $frame;
            }
        }
    }

    $smarty = new Smarty;
    $smarty->assign('brandMap', $brandMap);
    $smarty->display('views/index.tpl');

}
catch(PDOException $e)
{
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}
catch (Exception $e) 
{
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

?>

