<?php

namespace Layout\Controller;

use ArrayObject;

class Templates extends Controller {

    public function index() {
        return $this->render('layout:views/templates/index.php');
    }

    public function template($id = null) {

        $template = [
            'name' => null,
            'group' => null,
            'layout' => new ArrayObject([]),
        ];

        if ($id) {

            $_template = $this->app->dataStorage->findOne('layout/templates', ['_id' => $id]);

            if (!$_template) {
                return false;
            }

            $template = array_merge($template, $_template);
        }

        return $this->render('layout:views/templates/template.php', compact('template'));
    }

    public function save() {

        $this->hasValidCsrfToken(true);

        $template = $this->param('template');

        if (!$template) {
            return $this->stop(['error' => 'template data is missing'], 412);
        }

        $template['_modified'] = time();
        $isUpdate = isset($template['_id']);

        if (!$isUpdate) {
            $template['_created'] = $template['_modified'];
        }

        if (!isset($template['name']) || !trim($template['name'])) {
            return $this->stop(['error' => 'name required'], 412);
        }

        foreach (['name'] as $key) {
            $template[$key] = strip_tags(trim($template[$key]));
        }

        $this->app->dataStorage->save('layout/templates', $template);

        return $template;
    }

    public function clone($id = null) {

        if (!$id) {
            return false;
        }

        $template = $this->app->dataStorage->findOne('layout/templates', ['_id' => $id]);

        if (!$template) {
            return false;
        }

        unset($template['_id'], $template['_created'], $template['_modified']);

        if ($template['name']) {
            $template['name'] .= ' (Clone)';
        }

        return $this->render('layout:views/templates/template.php', compact('template'));
    }

    public function remove() {

        $this->hasValidCsrfToken(true);

        $template = $this->param('template');

        if (!$template || !isset($template['_id'], $template['name'])) {
            return $this->stop(['error' => 'template is missing'], 412);
        }

        $this->app->dataStorage->remove('layout/templates', ['_id' => $template['_id']]);

        return ['success' => true];
    }


    public function load() {

        $this->helper('session')->close();

        $templates = $this->app->dataStorage->find('layout/templates', [
            'sort' => ['name' => 1]
        ])->toArray();

        return $templates;
    }
}
