<?php

namespace ThurData\Servers\KerioEmail\App\Helpers;


use function ThurData\Servers\KerioEmail\Core\Helper\di;
use ThurData\Servers\KerioEmail\Core\UI\Traits\RequestObjectHandler;
use ThurData\Servers\KerioEmail\Core\Helper\BuildUrl;

/**
 *
 * Extended BuildUrl class, allow to create url for provisioning
 *
 * Created by PhpStorm.
 * User: ThurData
 * Date: 03.10.19
 * Time: 14:53
 * Class BuildUrlExtended
 */
class BuildUrlExtended extends BuildUrl
{

    const FILE_URI = 'clientarea.php';

    use RequestObjectHandler;

    /**
     * @param $controller
     * @return string
     */
    public static function getProvisioningUrl($controller = 'home', $isModParam = true, $isAParam = true, $action = null)
    {
        /**
         * uri params
         */
        $urlData = [
            'action'  => 'productdetails',
            'id'      => di('request')->get('id'),
        ];

        if($controller)
        {
            $urlData['mg-page'] = $controller;
        }

        if($isModParam)
        {
            $urlData['modop'] = 'custom';
        }

        if($isAParam)
        {
            $urlData['a'] = 'management';
        }

        if($action)
        {
            $urlData['mg-action'] = $action;
        }

        /**
         * build uri
         */
        $url = BuildUrlExtended::FILE_URI.'?'.http_build_query($urlData);

        /**
         * get base URL
         */
        $baseUrl = self::baseUrl();

        /**
         * build full url
         */
        $url     = $baseUrl . $url;

        return $url;
    }

    /**
     * @return string
     */
    private static function baseUrl()
    {
        $protocol = 'https';
        if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on')
        {
            $protocol = 'http';
        }
        $host   = $_SERVER['HTTP_HOST'];
        $surfix = $_SERVER['PHP_SELF'];
        $surfix = explode('/', $surfix);
        array_pop($surfix);
        $surfix = implode('/', $surfix);
        return "{$protocol}://{$host}{$surfix}/";
    }
}