<?php

use Mtc\Shop\Item;

/**
 * main controller for css folder
 */
$path = '../../';
require_once $path . 'core/includes/header.inc.php';

// pattern and layouts path name
$pattern_path_name = SITE_PATH . '/core/css/patterns/';
$layout_path_name = SITE_PATH . '/core/css/layouts';

$css_templating = true;

$layout_directories = new LayoutBrowser();
$template_menu = $layout_directories->getNavigation($layout_path_name);

// Remove dots from scandir
$remove_folders = [
    '..',
    '.'
];

$pattern_directories = array_values(array_diff(scandir($pattern_path_name), $remove_folders));

$patterns = [];

$template_info = [];
$template_info['assets'] = [];

if (isset($_REQUEST['twig_template_name']) && !empty($_REQUEST['twig_template_name'])) {

    $twig_template_name = $_REQUEST['twig_template_name'];

    $page_meta['title'] = 'Viewing layout' . $twig_template_name . ' on ' . config('app.name');
    $page_meta['page_title'] = 'Sample page';

} elseif (!empty($_REQUEST['patterns']) && $_REQUEST['patterns'] == true) {

    $page_meta['title'] = 'Pattern Browser for ' . config('app.name');

    $twig_template_name = '/chop/patterns.twig';

    foreach ($pattern_directories as $pattern_name) {
        $files = [];

        foreach (glob($pattern_path_name . $pattern_name . "/*.twig") as $filename) {
            $files[] = basename($filename);
        }

        $template_info['pattern_names'][] = $pattern_name;
        $template_info['pattern_paths'][] = $pattern_path_name . $pattern_name;
        $template_info['patterns'][] = $files;

    }

} else {

    $page_meta['title'] = 'Style Guide for ' . config('app.name');
    $twig_template_name = '/chop/style_guide.twig';

    $breadcrumbs = [
        [
            'url' => '/',
            'name' => 'Home',
        ], [
            'url' => '/about',
            'name' => 'About',
        ], [
            'url' => '/careers',
            'name' => 'Careers',
        ]
    ];

    $twig->addGlobal('breadcrumbs', $breadcrumbs);

}

// get template assets info and add to array
$template_info['assets'] = $layout_directories->getAssets($twig_template_name);

// get array of templates parent directories
$parent_directories = $layout_directories->getTemplateDirectories($twig_template_name);

// add some globals
$twig->addGlobal('template_info', $template_info);
$twig->addGlobal('template_menu', $template_menu);

// add page_meta data
$page_meta['robots'] = 'noindex, nofollow';

if (in_array('shop', $parent_directories) && in_array('item', $parent_directories)) {

    // set request id to a random item id for template to render
    $_REQUEST['id'] = Item::all()->random(1)->id;

    require_once $path . 'shop/item.php';

} elseif (in_array('shop', $parent_directories) && in_array('browse', $parent_directories)) {

    require_once $path . 'shop/browse/index.php';

} else {

    echo $twig->render($twig_template_name, [
        'page_meta' => $page_meta
    ]);

}
