<?php

namespace bin\php\Classes;

if (!defined('APP_INIT')) {
    exit;
}

use api\classes\API;

require_once "{$_SERVER['DOCUMENT_ROOT']}/api/classes/API.php";

class pageBuilder
{

    private array $jsScriptLoadData;

    public function __construct()
    {
        # retrieve all the pages from the database
        $pages = [];
        $query = "SELECT page_name, page_icon, page_description, page_location, page_url, page_color, module_name, module_slugify  FROM system_pages 
                INNER JOIN system_modules ON system_pages.module_uuid = system_modules.module_uuid
                WHERE system_modules.module_enabled = 1 ";
        if ($stmt = $GLOBALS['conn']->prepare($query)) {
            $stmt->execute();
            $result = $stmt->get_result();

            while ($row = $result->fetch_assoc()) {
                $module = $row['module_slugify'];
                $pages[$module][$row['page_name']] = $row;
            }
            $stmt->close();
        }

        $GLOBALS['pages'] = $pages;

        $this->figureOutContent();
    }

    private function figureOutContent(): void
    {
        $requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

        // Remove trailing slash, but only if it’s not the root "/"
        if ($requestUri !== '/' && str_ends_with($requestUri, '/')) {
            $requestUri = rtrim($requestUri, '/');
        }

        $_SESSION['breadCrumbArray'] = array(array('display' => '<i class="fas fa-home"></i>', 'href' => '/'));

        $GLOBALS['pageContentToShow']['pageName'] = '404';
        $GLOBALS['pageContentToShow']['pageFile'] = 'pageNotFound.php';
        $GLOBALS['pageContentToShow']['pageIcon'] = '<i class="fa-solid fa-ban"></i>';
        $GLOBALS['pageContentToShow']['noUsersAllowed'] = false;

        foreach ($GLOBALS['pages'] as $module) {
            foreach ($module as $page) {
                if ($requestUri == $page['page_url']) {
                    $GLOBALS['pageContentToShow']['pageName'] = $page['page_name'];
                    $GLOBALS['pageContentToShow']['pageFile'] = $page['page_location'];
                    $GLOBALS['pageContentToShow']['pageIcon'] = '<i class="' . $page['page_icon'] . '"></i>';
                    $GLOBALS['pageContentToShow']['noUsersAllowed'] = false;
                }
            }
        }
    }

    public function buildPage(): void
    { ?>
        <!DOCTYPE html>
        <html lang="en">
        <?php $this->pageHeadContent(); ?>
        <body>
        <div class="wrapper<?= (($_COOKIE['sidebarMinimized'] ?? '') === 'true' ? ' sidebar_minimize' : '') . (($_COOKIE['sidebarHovered'] ?? '') === 'true' ? ' sidebar_minimize_hover' : '') ?>">
            <?php $this->pageSidebarContent(); ?>
            <div class="main-panel">
                <?php $this->pageNavbarContent() ?>
                <div class="container">
                    <div class="page-inner">
                        <?php
                        include_once './bin/pages/' . $GLOBALS['pageContentToShow']['pageFile'];
                        if (isset($jsScriptLoadData)) {
                            $this->jsScriptLoadData = $jsScriptLoadData;
                        }
                        ?>
                    </div>
                </div>
                <?php $this->pageFooterContent() ?>
            </div>
        </div>
        <?php $this->pageScriptContents(); ?>
        </body>
        </html>
    <?php }

    private function pageHeadContent(): void
    { ?>
        <head>
            <meta http-equiv="content-type" content="text/html; charset=UTF-8">
            <meta charset="utf-8">
            <meta content="width=device-width, initial-scale=1.0, shrink-to-fit=no" name="viewport"/>
            <title>
                <?php echo __($GLOBALS['pageContentToShow']['pageName']) ?>
            </title>

            <!-- Fonts and icons -->
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
            <link href="https://fonts.googleapis.com/css?family=Public+Sans:300,400,500,600,700|Quicksand:300,400,500,600,700&display=swap" rel="stylesheet">

            <!-- CSS Files -->
            <link rel="stylesheet" href="/src/css/bootstrap.gruvbox.min.css"/> <!-- Basic bootstrap and theming -->
            <link rel="stylesheet" href="/src/css/sentri.min.css"/> <!-- Special css tricks for Sentri -->
            <link rel="stylesheet" href="/src/css/plugins.min.css"/> <!-- need this for scroll bars and other small things -->
            <link rel="stylesheet" href="/src/js/plugin/sweetalert2/sweetalert2.min.css"/> <!-- need this for scroll bars and other small things -->
            <link rel="stylesheet" href="/src/js/plugin/toastify-js/toastify.css"/> <!-- This is used for the toasts -->
            <link rel="stylesheet" href="/src/css/fullcalendar/skeleton.css"/> <!-- Used for fullcalander.js -->
            <link rel="stylesheet" href="/src/css/fullcalendar/theme/theme.css"/> <!-- Used for fullcalander.js -->
            <link rel="stylesheet" href="/src/css/fullcalendar/theme/palettes/purple.css"/> <!-- Used for fullcalander.js -->

            <!--<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/lipis/flag-icons@7.2.3/css/flag-icons.min.css"/> -->

            <!-- favicon -->
            <link rel="icon" type="image/png" href="/src/images/favicon/favicon-96x96.png" sizes="96x96"/>
            <link rel="icon" type="image/svg+xml" href="/src/images/favicon/favicon-96x96.png"/>
            <link rel="shortcut icon" href="/src/images/favicon/favicon.ico"/>
            <link rel="apple-touch-icon" sizes="180x180" href="/src/images/favicon/apple-touch-icon.png"/>
            <link rel="manifest" href="/src/images/favicon/site.webmanifest"/>
        </head>
    <?php }

    private function pageSidebarContent(): void
    {

        $API = new API();
        function showSpan($module_name): void
        {
            ?>
            <li class="nav-section">
                <span class="sidebar-mini-icon my-3">
                  >
                </span>
                <h4 class="text-section">
                    <i class="fa-solid fa-cubes"></i> <?php echo $module_name ?>
                </h4>
            </li>
        <?php }

        function showPage($module_name, $page_name): void
        {
            $page = $GLOBALS['pages'][$module_name][$page_name];
            ?>
            <li class="nav-item <?php echo($_SERVER['REQUEST_URI'] == $page['page_url'] ? 'active' : '') ?>">
                <a href="<?php echo $page['page_url'] ?>">
                    <i class="<?php echo $page['page_icon'] ?>"></i>
                    <span><?php echo __($page['page_name']) ?></span>
                </a>
            </li>
        <?php } ?>

        <div class="sidebar">
            <div class="sidebar-logo">
                <div class="logo-header">
                    <a href="/" class="logo">
                        <img src="/src/images/logo-sidebar-dark.webp" alt="navbar brand" class="navbar-brand" height="60"/>
                    </a>
                    <div class="nav-toggle">
                        <button class="btn btn-toggle toggle-sidebar">
                            <i class="gg-menu-right"></i>
                        </button>
                        <button class="btn btn-toggle sidenav-toggler">
                            <i class="gg-menu-left"></i>
                        </button>
                    </div>
                    <button class="topbar-toggler more">
                        <i class="gg-more-vertical-alt"></i>
                    </button>
                </div>
            </div>
            <div class="sidebar-wrapper scrollbar scrollbar-inner">
                <div class="sidebar-content">
                    <ul class="nav nav-warning">

                        <?php
                        showPage('portal-management', 'dashboard');

                        if ($GLOBALS['modules_enabled']['office'] && $API->checkPermissions('office-stompjes', 'RO', true)) {
                            showSpan('office');
                            showPage('office', 'stompjeslist');
                            showPage('office', 'travelReimburse');
                        }

                        if ($GLOBALS['modules_enabled']['servers'] && $API->checkPermissions('servers', 'RO', true)) {
                            showSpan('servers');
                            showPage('servers', 'server_overview');
                        }

                        if ($GLOBALS['modules_enabled']['customers'] && $API->checkPermissions('customer-companies', 'RO', true)) {
                            showSpan('customers');
                            showPage('customers', 'companies');
                        }

                        if ($GLOBALS['modules_enabled']['autop']) {
                            showSpan('autop');
                            showPage('autop', 'platforms');
                            showPage('autop', 'vendors');
                            showPage('autop', 'devices');
                            showPage('autop', 'provisioning');
                            showPage('autop', 'phonebooks');
                            showPage('autop', 'device_settings');
                        }

                        showSpan(__('portal-management'));
                        showPage('portal-management', 'access_control');
                        showPage('portal-management', 'portal-management');
                        ?>
                    </ul>
                </div>
            </div>
        </div>
        <?php
    }

    private function pageNavbarContent(): void
    {
        ?>
        <div class="main-header">
            <div class="main-header-logo">
                <!-- Logo Header -->
                <div class="logo-header">
                    <a href="/" class="logo">
                        <img src="/src/images/logo-sidebar-dark.webp" alt="navbar brand" class="navbar-brand" height="60"/>
                    </a>
                    <div class="nav-toggle">
                        <button class="btn btn-toggle toggle-sidebar">
                            <i class="gg-menu-right"></i>
                        </button>
                        <button class="btn btn-toggle sidenav-toggler">
                            <i class="gg-menu-left"></i>
                        </button>
                    </div>
                    <button class="topbar-toggler more">
                        <i class="gg-more-vertical-alt"></i>
                    </button>
                </div>
                <!-- End Logo Header -->
            </div>
            <!-- Navbar Header -->
            <nav class="navbar navbar-header navbar-header-transparent navbar-expand-lg border-bottom">
                <div class="container-fluid">
                    <ul class="navbar-nav topbar-nav ms-md-auto align-items-center">
                        <li class="nav-item topbar-icon dropdown hidden-caret d-flex d-lg-none"></li>

                        <li class="nav-item topbar-user dropdown hidden-caret">
                            <a class="dropdown-toggle profile-pic" data-bs-toggle="dropdown" href="#" aria-expanded="false">
                                <div class="avatar-sm">
                                    <img src="<?php echo(($_SESSION['user']['user_profile_picture_thumbnail'] != null) ? 'data:image/png;base64, ' . $_SESSION['user']['user_profile_picture_thumbnail'] : '/src/images/user-avatar-default-small.png') ?>" alt="..." class="avatar-img rounded-circle">
                                </div> &nbsp;
                                <span class="op-7"> <?php echo __('hi') ?>,&nbsp;</span>
                                <span class="fw-bold"><?php echo $_SESSION['user']['user_first_name'] ?></span>
                            </a>
                            <ul class="dropdown-menu dropdown-user animated fadeIn">
                                <li>
                                    <div class="user-box">
                                        <div class="avatar-lg">
                                            <img src="<?php echo(($_SESSION['user']['user_profile_picture_thumbnail'] != null) ? 'data:image/png;base64, ' . $_SESSION['user']['user_profile_picture_thumbnail'] : '/src/images/user-avatar-default-small.png') ?>" alt="image profile" class="avatar-img rounded">
                                        </div>
                                        <div class="u-text">
                                            <h4><?php echo $_SESSION['user']['user_email'] ?></h4>
                                            <p class="text-muted"><?php echo $_SESSION['user']['user_email'] ?></p>
                                        </div>
                                    </div>
                                </li>
                                <li>
                                    <?php
                                    if ($_SESSION['user']['user_group_type'] == 'user' || $_SESSION['user']['user_group_type'] == 'admin') { ?>
                                        <a class="dropdown-item" href="/userprofile/"><i class="fa-solid fa-address-card"></i> <?php echo __('user_profile') ?>
                                        </a>
                                        <div class="dropdown-divider"></div>
                                    <?php } else { ?>
                                        <div class="dropdown-divider"></div>
                                    <?php } ?>
                                    <form id="logoutform" class="form-inline logoutform" action="/login/logout.php" method="POST">
                                        <input type="hidden" name="logout">
                                        <button type="submit" form="logoutform" class="dropdown-item">
                                            <i class="fas fa-sign-out-alt"></i> Logout
                                        </button>
                                    </form>
                                </li>
                            </ul>
                        </li>
                    </ul>
                </div>
            </nav>
            <!-- End Navbar -->
        </div>
    <?php }

    private function pageFooterContent(): void
    { ?>
        <footer class="footer py-2">
            <div class="container-fluid d-flex justify-content-between">
                <nav class="pull-left">
                    <ul class="nav">
                        <li class="nav-item">
                            <a class="nav-link" href="https://docs.sentri.mooij.me" target="_blank"><i class="far fa-question-circle"></i> Docs</a>
                        </li>
                    </ul>
                </nav>
                <div class="copyright">
                    <?php echo __('version') ?>
                    <a class="text-primary" href="/changelog/">1.3.0</a>
                </div>
                <div>
                    <span class="navbar-text">Sentri</span>
                </div>
            </div>
        </footer>
    <?php }

    private function pageScriptContents(): void
    { ?>
        <!-- always load these -->
        <script src="/src/js/core/jquery-3.7.1.min.js"></script>
        <script src="/src/js/core/popper.min.js"></script>
        <script src="/src/js/core/bootstrap.min.js"></script>

        <!-- Load the locales in js -->
        <script src="/src/js/i18n-loader.js"></script>

        <!-- Toastify js for toasts after actions are peformed -->
        <script src="/src/js/plugin/toastify-js/toastify.js"></script>

        <!-- Sweet Alert -->
        <script src="/src/js/plugin/sweetalert2/sweetalert2.min.js"></script>

        <!-- Kaiadmin JS -->
        <script src="/src/js/kaiadmin.dark.min.js"></script>

        <!-- jQuery Scrollbar -->
        <script src="/src/js/plugin/jquery-scrollbar/jquery.scrollbar.min.js"></script>

        <script src="/src/js/sentri/response.js"></script>

        <!-- Load Other Js scripts -->
        <?php
        if (isset($this->jsScriptLoadData)) {
            foreach ($this->jsScriptLoadData as $key => $script) {
                if ($key === 'form') { ?>
                    <script src="/src/js/plugin/select2/select2.full.min.js"></script><!-- Bootstrap Tagsinput -->
                    <script src="/src/js/plugin/bootstrap-tagsinput/bootstrap-tagsinput.min.js"></script><!-- jQuery Moment.JS -->
                    <script src="/src/js/plugin/moment/moment.min.js"></script><!-- Bootstrap datetimepicker -->
                    <script src="/src/js/plugin/bootstrap-datetimepicker/bootstrap-datetimepicker.min.js"></script><!-- validate forms -->
                    <script src="/src/js/plugin/jquery.validate/jquery.validate.min.js"></script><!-- dropzone -->
                    <script src="/src/js/plugin/dropzone/dropzone.min.js"></script>
                    <script src="/src/js/sentri/form.js"></script>

                <?php } elseif ($key === 'codeblocks') { ?>
                    <link rel="stylesheet" href="/src/css/prism.css">
                    <script src="https://cdn.jsdelivr.net/npm/prismjs/prism.min.js"></script>
                    <script src="https://cdn.jsdelivr.net/npm/prismjs/components/prism-json.min.js"></script>
                    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs/plugins/toolbar/prism-toolbar.css">
                    <script src="https://cdn.jsdelivr.net/npm/prismjs/plugins/toolbar/prism-toolbar.min.js"></script>
                    <script src="https://cdn.jsdelivr.net/npm/prismjs/plugins/copy-to-clipboard/prism-copy-to-clipboard.min.js"></script>
                <?php } elseif ($key === 'datepicker') { ?>
                    <script src="/src/js/plugin/moment/moment.min.js"></script>
                    <script src="/src/js/plugin/datepicker/bootstrap-datetimepicker.min.js"></script>

                    <script src="/src/js/sentri/datepicker.js"></script>
                <?php } else { ?>
                    <script src="<?php echo $key ?>"></script>
                <?php } ?><?php }
        }
        # keeps refreshing the timeZoneCookie
        setTimeZoneCookie();

    }
}
