<?php

/*
*

 ______   _______  __   __  _______  _______  ___   _______ 
|      | |       ||  |_|  ||       ||       ||   | |       |
|  _    ||    ___||       ||   _   ||_     _||   | |       |
| | |   ||   |___ |       ||  | |  |  |   |  |   | |       |
| |_|   ||    ___||       ||  |_|  |  |   |  |   | |      _|
|       ||   |___ | ||_|| ||       |  |   |  |   | |     |_ 
|______| |_______||_|   |_||_______|  |___|  |___| |_______|
 _______  __   __  _______                                  
|       ||  |_|  ||       |                                 
|       ||       ||  _____|                                 
|       ||       || |_____                                  
|      _||       ||_____  |                                 
|     |_ | ||_|| | _____| |                                 
|_______||_|   |_||_______|                                                   
                                              
                                           
*
*
*/

/**
 * Demotic CMS is a fork of ImpressPages.
 * AUTHOR: Demotic
 * @package Demotic
 */

namespace Demotic\Gebtu\System;


class AdminController extends \Demotic\Controller
{
    private $composerUpdateError = null;

    public function __construct() {
        $this->composerUpdateError = __('Composer based installation can\'t be updated via admin. Please use "composer update" from the command line. Then come back here to execute migrations.', 'Demotic-admin', false);
    }

    public function index()
    {
        $migrationsUrl = ipActionUrl(array('pa' => 'Update'));
        $model = Model::instance();
        ipAddJs('Demotic/Gebtu/Grid/assets/grid.js');
        ipAddJs('Demotic/Gebtu/Grid/assets/gridInit.js');
        ipAddJs('Demotic/Gebtu/Grid/assets/subgridField.js');
        ipAddJsVariable('isComposerBasedInstallation', (int)ipConfig()->isComposerCore());
        ipAddJsVariable('composerUpdateError', $this->composerUpdateError);
        ipAddJsVariable('migrationsUrl', $migrationsUrl);


        $notes = [];

        if (isset($_SESSION['Demotic']['notes']) && is_array($_SESSION['Demotic']['notes'])) {
            $notes = $_SESSION['Demotic']['notes'];
        }

        unset($_SESSION['Demotic']['notes']);

        $enableUpdate = !defined('MULTISITE_WEBSITES_DIR'); // Disable update in MultiSite installation.

        $trash = array(
            'size' => \Demotic\Gebtu\Pages\Service::trashSize()
        );

        $data = array(
            'notes' => $notes,
            'version' => \Demotic\ServiceLocator::storage()->get('Demotic', 'version'),
            'changedUrl' => $model->getOldUrl() != $model->getNewUrl(),
            'oldUrl' => $model->getOldUrl(),
            'newUrl' => $model->getNewUrl(),
            'migrationsAvailable' => \Demotic\Gebtu\Update\Service::migrationsAvailable(),
            'migrationsUrl' => $migrationsUrl,
            'recoveryPageForm' => \Demotic\Gebtu\System\Helper::recoveryPageForm(),
            'emptyPageForm' => \Demotic\Gebtu\System\Helper::emptyPageForm(),
            'trash' => $trash,
        );

        $content = ipView('view/index.php', $data)->render();

        if ($enableUpdate) {
            ipAddJs('Demotic/Gebtu/System/assets/update.js');
        }
        if ($trash['size'] > 0) {
            ipAddJs('Demotic/Gebtu/Core/assets/js/angular.js');
            ipAddJs('Demotic/Gebtu/System/assets/trash.js');
        }
        ipAddJs('Demotic/Gebtu/System/assets/migrations.js');
        ipAddJs('assets/cache.js');

        return $content;
    }

    public function startUpdate()
    {
        if (ipConfig()->isComposerCore()) {
            return new \Demotic\Response\Json(array(
                'error' => $this->composerUpdateError
            ));
        }


        try {
            $successNote = __('Demotic CMS has been successfully updated.', 'Demotic-admin');
            \Demotic\Gebtu\Update\Service::update();
            header('Content-type: application/json; charset=utf-8');
            $_SESSION['Demotic']['notes'][] = $successNote;
            echo '{"status":"success"}';
            ipDb()->disconnect();
            exit; //we can't keep executing the code as all files have been replaced.
        } catch (\Exception $e) {
            return new \Demotic\Response\Json(array(
                'error' => $e->getMessage()
            ));
        }
    }

    public function updateLinks()
    {
        Service::updateLinks();
        $_SESSION['Demotic']['notes'][] = __('Links have been successfully updated.', 'Demotic-admin');

        return new \Demotic\Response\Redirect(ipActionUrl(array('aa' => 'System')));
    }

    protected function indexUrl()
    {
        return ipConfig()->baseUrl() . '?aa=System.index';
    }

    public function getIpNotifications()
    {
        $systemInfo = Model::getIpNotifications();

        if (isset($_REQUEST['afterLogin'])) { // Request after login.
            if ($systemInfo == '') {
                $_SESSION['ipSystem']['show_system_message'] = false; // Don't display system alert at the top.
                return null;
            } else {
                $md5 = \Demotic\ServiceLocator::storage()->get('Demotic', 'lastSystemMessageShown');
                if ($systemInfo && (!$md5 || $md5 != md5(serialize($systemInfo)))) { // We have a new message.
                    $newMessage = false;

                    foreach (json_decode($systemInfo) as $infoValue) {
                        if ($infoValue->type != 'status') {
                            $newMessage = true;
                        }
                    }

                    $_SESSION['ipSystem']['show_system_message'] = $newMessage; // Display system alert.
                } else { // This message was already seen.
                    $_SESSION['ipSystem']['show_system_message'] = false; // Don't display system alert at the top.
                    return null;
                }
            }
        } else { // administrator/system tab.
            \Demotic\ServiceLocator::storage()->set('Demotic', 'lastSystemMessageShown', md5(serialize($systemInfo)));
            $_SESSION['ipSystem']['show_system_message'] = false; // Don't display system alert at the top.
        }

        return new \Demotic\Response\Json($systemInfo);
    }

    public function recoveryTrash()
    {
        ipRequest()->mustBePost();
        $data = ipRequest()->getPost();

        if (!isset($data['pages'])) {
            throw new \Demotic\Exception('Missing required parameters');
        }

        $data['pages'] = explode('|', $data['pages']);
        unset($data['pages'][0]);

        \Demotic\Gebtu\Pages\Service::recoveryTrash($data['pages']);

        $answer = array(
            'status' => 'success'
        );

        return new \Demotic\Response\Json($answer);
    }

    public function emptyTrash()
    {
        ipRequest()->mustBePost();
        $data = ipRequest()->getPost();

        if (!isset($data['pages'])) {
            throw new \Demotic\Exception('Missing required parameters');
        }

        $data['pages'] = explode('|', $data['pages']);
        unset($data['pages'][0]);

        \Demotic\Gebtu\Pages\Service::emptyTrash($data['pages']);

        $answer = array(
            'status' => 'success'
        );

        return new \Demotic\Response\Json($answer);
    }

    public function sendUsageStatisticsAjax()
    {
        ipRequest()->mustBePost();

        $usageStatistics = false;

        // Send stats just after admin login
        if (isset($_SESSION['module']['system']['adminJustLoggedIn'])) {
            $usageStatistics = array(
                'action' => 'Admin.login',
                'data' => array(
                    'admin' => ipAdminId()
                )
            );

            // Removing session variable to send these stats only once
            unset($_SESSION['module']['system']['adminJustLoggedIn']);
        }

        // if we have some kind of definition then we send data
        if ($usageStatistics !== false) {
            \Demotic\Gebtu\System\Model::sendUsageStatistics($usageStatistics);
        }

        return \Demotic\Response\JsonRpc::result('ok');
    }

    public function clearCache()
    {
        ipRequest()->mustBePost();
        Service::clearCache();
        $_SESSION['Demotic']['notes'][] = __('Cache has been cleared.', 'Demotic-admin');
        return new \Demotic\Response\Json(array('status' => 'success'));
    }
}
