<?php
// Copyright 1999-2017. Plesk International GmbH. All rights reserved.

namespace Plesk\MigrationLibV8\MailImport\Backend\Files;

use Plesk\MigrationLibV8\Utils\FileUtils;

class Status
{
    private $_statusData;
    private string $_statusFilePath;

    public function __construct($statusFilePath)
    {
        $this->_statusFilePath = $statusFilePath;
        $this->_read();
    }
    /**
     * Get whole set of site status data as array.
     *
     * @return array
     */
    public function getStatusData()
    {
        return $this->_statusData;
    }

    /**
     * Get full path to file with the mail import status info.
     *
     * @return string
     */
    private function getFilePath()
    {
        return $this->_statusFilePath;
    }

    private function _read()
    {
        if (FileUtils::fileExists($this->getFilePath())) {
            $data = json_decode(FileUtils::fileGetContents($this->getFilePath()), true);

            // Leave issue details only for administrator:
            // - for better security (details could accidentally contain sensitive data)
            // - for better user experience (in most cases user won't understood the details, and there is no sense
            // to show that useless info).
            // So, only administrator could see logs, stack traces, etc.
            if (!\pm_Session::getClient()->isAdmin()) {
                $data = $this->_filterOutDetails($data);
            }
        } else {
            $data = [];
        }

        $this->_statusData = $data;
    }

    /**
     * Remove issue details from migration status data structure
     *
     * @param mixed $data
     * @return mixed
     */
    private function _filterOutDetails($data)
    {
        if (is_array($data)) {
            $result = [];

            foreach ($data as $key => $value) {
                if ($key !== 'details_text' && $key !== 'error_details') {
                    $result[$key] = $this->_filterOutDetails($value);
                }
            }

            return $result;
        } else {
            return $data;
        }
    }
}
