<?php
/**
 * CMS part 2 installer
 * @author Rihards Silins <rihards.silins@mtcmedia.co.uk>
 * @version 1 02/03/2017
 */

if (!isset($path)) {
    $path = "../../../";
}
require_once($path . "/core/includes/header.inc.php");

use Mtc\Core\Setting;
use Mtc\Cms\Handlers\PagesSetupHandler;

$pages_setup_list = PagesSetupHandler::listPagesSetups($twig_loader);

$errors = [];

if (!empty($_POST['pages_structure'])) {
    if (($pages_structure = json_decode($_POST['pages_structure'], true)) == null) {
        $errors[] = "Submitted pages structure is not valid JSON.";
    }
}

if (defined('CMS_USE_DEFAULT_CMS_SETUP') && CMS_USE_DEFAULT_CMS_SETUP) {
    foreach ($pages_setup_list as $pages_setup) {
        if ($pages_setup['filename'] == "default.json") {
            $result = json_decode($pages_setup['setup'], true);
            if (!empty($result)) {
                $pages_structure = $result;
                break;
            }
        }
    }
}

if (empty($pages_structure) || !empty($errors)) {
    echo $twig->render(
        'install/install.twig',
        [
            'errors' => $errors,
            'title' => 'CMS Setup',
            'pages_setup_list' => $pages_setup_list
        ]
    );
    exit();
} elseif (empty($errors)) {

    $content_manager = new ContentManager();
    $content_manager->setTwigLoader($twig_loader);
    $first_level_generated_pages = $content_manager->processLapsg($pages_structure, 0);

    for ($i = 0; $i < count($first_level_generated_pages); $i++) {
        $content_manager->processSlugsForPageAndSubs($first_level_generated_pages[$i]);
    }

    if (!defined('CMS_SETUP') || !CMS_SETUP) {
        //Insert settings, CMS_SETUP used to determine if already setup
        Setting::insert([
            [
                'key'         => 'CMS_SETUP',
                'type'        => 'bool',
                'value'       => true,
                'module'      => 'CMS',
                'description' => 'Indicates if CMS is fully setup.',
                'created_at'  => new \DateTime(),
            ]
        ]);
    }
}
