<?php

namespace brain\controller;

use brain\data\Book;
use brain\data\Session;
use brain\data\Settings;
use brain\data\Themes;
use brain\utility\Setup;
use brain\utility\Sorting;
use Carbon\Carbon;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Views\Twig;

class DashControl
{
    public static function start(
        ServerRequestInterface $request,
        ResponseInterface $response,
        array $args
    ): ResponseInterface {
        $view        = Twig::fromRequest($request);
        $pageOptions = [];
        $template    = '';
        if (Setup::status()) {
            switch (isset($args['second']) ? $args['second'] : 'index') {
                case 'settings':
                    if (Session::active()) {
                        $config      = new Settings();
                        $settings    = $config->getSettings();
                        $themes      = (new Themes())->getThemes(); // $config->getThemes();
                        $template    = 'dash/settings.twig';
                        $member      = Session::get('member');
                        $form_token  = Session::get('form_token');
                        $updated     = new Carbon($settings['global']['last_backup']);
                        $pageOptions = [
                            'title'        => 'Settings',
                            'private'      => $settings['global']['private'],
                            'renderOnSave' => $settings['global']['renderOnSave'],
                            'background'   => $settings['global']['background'],
                            'member'       => $member,
                            'ftoken'       => $form_token,
                            'siteTitle'    => $settings['global']['title'],
                            'baseUrl'      => $settings['global']['base_url'],
                            'desc'         => $settings['global']['descriptions'],
                            'lastBackup'   => $updated->format('Y M D d'),
                            'currentTheme' => $settings['global']['theme'],
                            'themes'       => $themes,
                            'apiStatus'    => isset($settings['global']['externalAPI'])
                              ? $settings['global']['externalAPI']
                              : 'false',
                            'dynamicRenderStatus' => isset(
                                $settings['global']['dynamicRender']
                            )
                              ? $settings['global']['dynamicRender']
                              : 'false',
                            'mailOption' => $settings['email']['active'],
                            'mailConfig' => $settings['email'],
                            'status'     => Session::active(),
                        ];
                    } else {
                        header('Location: /dashboard');
                        exit();
                    }

                    break;
                case 'navigation':
                    if (Session::active()) {
                        $config      = new Settings();
                        $settings    = $config->getSettings();
                        $template    = 'dash/navigation.twig';
                        $pageOptions = [
                            'title'  => 'Edit Menu',
                            'status' => Session::active(),
                            'menu'   => $settings['menu'],
                        ];
                    } else {
                        header('Location: /dashboard');
                        exit();
                    }
                    break;
                case 'pages':
                    if (Session::active()) {
                        $currentPage = isset($args['fourth']) ? $args['fourth'] : 1;
                        $filter      = isset($args['third']) ? $args['third'] : 'all';
                        $data        = (new Book())->getPages($currentPage, 4, $filter);
                        $template    = 'dash/book.twig';
                        $pageOptions = [
                            'title'       => 'Contents',
                            'entryCount'  => $data['entryCount'],
                            'numOfPages'  => $data['numOfPages'],
                            'currentPage' => $currentPage,
                            'filter'      => $data['paginate']['sort'],
                            'stats'       => $data['stats'],
                            'pages'       => $data['pages'],
                            'paginate'    => $data['paginate'],
                            'status'      => Session::active(),
                        ];
                    } else {
                        header('Location: /dashboard');
                        exit();
                    }
                    break;
                case 'page':
                    if (Session::active()) {
                        $template = 'dash/page-edit.twig';
                        $mode     = $args['third'];
                        $uuid     = $args['fourth'];

                        switch ($mode) {
                            case 'edit':
                                $page  = (new Book())->findPageById($uuid);
                                $views = [];
                                if (!isset($page['layout'])) {
                                    $page['layout'] = "page";
                                }
                                if (str_contains($page['layout'], 'index')) {
                                    $views = (new Themes())->getCustomIndex();
                                } else {
                                    $views = (new Themes())->getCustomViews();
                                }
                                $imageList = [];
                                $fileList  = [];
                                if (isset($page['feature'])) {
                                    $imageList = explode(',', $page['feature']);
                                }
                                if (isset($page['files'])) {
                                    $fileList = explode(',', $page['files']);
                                }

                                $images = [];
                                $files  = [];
                                foreach ($imageList as $item) {
                                    $image = trim($item);
                                    if (!empty($image)) {
                                        array_push($images, $image);
                                    }
                                }

                                foreach ($fileList as $item) {
                                    $file = trim($item);
                                    if (!empty($file)) {
                                        array_push($files, $file);
                                    }
                                }

                                $pageOptions = [
                                    'title'  => $page['title'],
                                    'page'   => $page,
                                    'mode'   => $mode,
                                    'token'  => Session::get('form_token'),
                                    'status' => Session::active(),
                                    'images' => $images,
                                    'files'  => $files,
                                    'views'  => $views,
                                ];
                                break;
                            case 'preview':
                                $config   = new Settings();
                                $settings = $config->getSettings();
                                $loader   = new \Twig\Loader\FilesystemLoader(
                                    '../content/themes/' . $settings['global']['theme'] .
                                    '/'
                                );
                                $display = new \Twig\Environment($loader, []);

                                $book        = new Book();
                                $page        = $book->findPageById($uuid);
                                $pageOptions = Sorting::page($page);
                                $preview     = $page['layout'] .
                                '.twig';
                                $html = $display->render($preview, $pageOptions);
                                $response->getBody()->write($html);

                                return $response;
                                break;
                            default:
                                $pageOptions = [
                                    'title'  => 'Fipamo | Create Page',
                                    'token'  => Session::get('form_token'),
                                    'mode'   => $mode,
                                    'status' => Session::active(),
                                ];
                                break;
                        }
                    } else {
                        header('Location: /dashboard');
                        exit();
                    }
                    break;
                case 'logout':
                    Session::kill();
                    header('Location: /dashboard');
                    exit();
                    break;
                case 'reset-password':
                    $template    = 'dash/reset-password.twig';
                    $pageOptions = [
                        'title' => 'Reset Password',
                    ];
                    break;
                default:
                    $template = 'dash/start.twig';
                    if (Session::active()) {
                        $pageOptions = [
                            'title'  => 'Start',
                            'status' => Session::active(),
                            'data'   => (new Book())->getPages(1, 4),
                        ];
                    } else {
                        $pageOptions = [
                            'title'  => 'Welcome to Fipamo',
                            'status' => Session::active(),
                        ];
                    }
                    break;
            }
        } else {
            $template    = 'dash/init.twig';
            $pageOptions = ['title' => 'Fipamo Setup'];
        }

        return $view->render($response, $template, $pageOptions);
    }
}
