<?php

include_once './config.php';
include_once './models/services/Database.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 ($_SERVER['REQUEST_METHOD'] == 'GET')
{
    if (isset($_SESSION['brand']))
    {
        $name = $_SESSION['brand'];
        $brandService = new BrandService();
        $brand = $brandService->getBrandByName($name);
        
        $brandMap = array();
                
        $geometryService = new GeometryService();
        $geometries = $geometryService->getAllGeometriesByBrand($brand->id, is_updater());

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

            $frameService = new FrameService();
            $frames = $frameService->getAllFramesByGeometry($geometry->id, is_updater());
        
            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->assign('brand', $brand);
        $smarty->assign('user_can_update', is_updater());
        $smarty->assign('user_logged_in', is_logged_in($user));        
        $smarty->display('views/frames.tpl');

//        $frameService = new FrameService();
//        $frames = $frameService->getAllFramesByBrand($brand->id, is_updater());
//
//        if ($frames)
//        {
//            $smarty = new Smarty;
//            $smarty->assign('brand', $brand);
//            $smarty->assign('frames', $frames);
//            $smarty->assign('user_can_update', is_updater());        
//            $smarty->display('views/frames.tpl');
//        }
//        else
//        {
//            header("location:add_frame.php?brand=$name");
//        }
    }
    else
    {
        $brandService = new BrandService();
        $brands = $brandService->getAllBrands();

        $smarty = new Smarty;
        $smarty->assign('brands', $brands);
        $smarty->assign('action', "frames.php");
        $smarty->display('views/selectbrand.tpl');
    }
}

?>
