<?php

namespace App\Services;

class RenderService
{
    private $sort;
    private $settings;
    private $pageInfo;
    private $menu;
    private $background;

    public function __construct(SortingService $sortingService, SettingsService $settingsService)
    {
        $this->sort     = $sortingService;
        $this->settings = $settingsService;
    }

    public function tag()
    {
        $list = $this->sort->tags();
        foreach ($list as $item) {
            $template    = 'tags.twig';
            $pageOptions = [
                'title'      => 'Pages Tagged as ' . $item['tag_name'],
                'background' => $this->pageInfo['image'],
                'tag_list'   => $item['pages'],
                'info'       => $this->pageInfo,
                'menu'       => $this->menu,
                'media'      => [['file' => $this->pageInfo['image'], 'type' => trim(pathinfo($this->pageInfo['image'], PATHINFO_EXTENSION))]],
            ];

            $html = $this->twig->render($template, $pageOptions);

            $location = '../public/tags/' . $item['slug'] . '.html';

            //if tags folder doesn't exist, make it
            if (!is_dir('../public/tags')) {
                mkdir('../public/tags', 0755, true);
            } else {
            }

            if (!is_file($location)) {
                file_put_contents($location, $html);
            } else {
                ($new = fopen($location, 'w')) or die('Unable to open file!');
                fwrite($new, $html);
                fclose($new);
            }
        }
    }
}