<?php

namespace ModulesGarden\Servers\OpenXchange\App\Helpers;


use function ModulesGarden\Servers\OpenXchange\Core\Helper\di;
use ModulesGarden\Servers\OpenXchange\Core\UI\Traits\RequestObjectHandler;
use ModulesGarden\Servers\OpenXchange\Core\Helper\BuildUrl;

/**
 *
 * Extended BuildUrl class, allow to create url for provisioning
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * 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}/";
    }
}
