<?php

/**
 * Questo file è parte di Pongho.
 *
 * @author    Daniele Termini
 * @copyright Web Agency Meta Line S.r.l.
 * @package   Application\Admin
 */

namespace Application\Admin\Utilities;

use Application\Core\Model\Site;
use Pongho\Http\Request;

class PonghoUrl
{
    /**
     * @var \Application\Core\Model\Site
     */
    protected $site;

    /**
     * @var \Pongho\Http\Request
     */
    protected $request;

    /**
     * @var ContentLanguage
     */
    protected $content_language;

    public function __construct(Site $site, Request $request, ContentLanguage $contentLanguage)
    {
        $this->site = $site;
        $this->request = $request;
        $this->content_language = $contentLanguage;
    }

    /**
     * @return int
     */
    public function getLanguageId()
    {
        return $this->content_language->getId();
    }

    /**
     * @return int
     */
    public function getSiteId()
    {
        return $this->site->getId();
    }

    /**
     * Restituisce l’url passato aggiungendo i parametri `site` e `language`.
     *
     * @param string $url
     * @param string $arg_separator
     * @return string
     * @throws \InvalidArgumentException
     */
    public function url($url, $arg_separator = '&amp;')
    {
        $url = '/' . ltrim($url, '/');

        if (str_starts_with($url, '/pongho/')) {
            throw new \InvalidArgumentException(
                sprintf(
                    'Il metodo `%s` aggiunge automaticamente il prefisso `/pongho/` agli indirizzi passati.',
                    __METHOD__
                )
            );
        }

        $info = parse_url($url);
        $qs = [];

        if (isset($info['query'])) {
            parse_str($info['query'], $qs);
        }

        $qs['language'] = $this->getLanguageId();
        $qs['site'] = $this->getSiteId();

        return pongho_url($info['path'] . '?' . http_build_query($qs, '', $arg_separator));
    }

    /**
     * Restituisce l'url corrente.
     *
     * @param string $arg_separator
     * @return string
     */
    public function currentUrl($arg_separator = '&amp;')
    {
        return $this->url(substr($this->request->getRelativeUri(), 7), $arg_separator);
    }

    /**
     * Restituisce i campi hidden da inserire in una form di tipo GET per mantenere lingua e sito.
     *
     * @return string
     */
    public function formFields()
    {
        return '<input type="hidden" name="language" value="' . $this->getLanguageId() . '"><input type="hidden" name="site" value="' . $this->getSiteId() . '">';
    }
}
