<?php

namespace engine\http\errors;

use engine\http\HTTPCode;
use Throwable;

abstract class BaseRedirect
    extends HTTPError
{
    protected bool $no_ajax = false;
    protected bool $replace = false;

    public function __construct(string $location = "",
                                bool $preserve_utm = true,
                                bool $replace = false,
                                bool $no_ajax = false,
                                ?Throwable $previous = null) {
        if (/*!is_cli() && */$_SERVER['REQUEST_METHOD'] == 'GET' && $preserve_utm) {
            $proxy_params = ['utm_source', 'utm_medium', 'utm_content', 'utm_campaign'];
            $params = [];
            foreach ($proxy_params as $p) {
                if (!empty($_GET[$p])) {
                    $params[$p] = (string)$_GET[$p];
                }
            }
            if (!empty($params)) {
                if (($anchor_pos = strpos($location, '#')) !== false) {
                    $anchor = substr($location, $anchor_pos+1);
                    $location = substr($location, 0, $anchor_pos);
                }
                $location .= (!str_contains($location, '?') ? '?' : '&').http_build_query($params);
                if ($anchor_pos !== false) {
                    $location .= '#'.$anchor;
                }
            }
        }

        parent::__construct(HTTPCode::Found, $location, $previous);

        $this->no_ajax = $no_ajax;
    }

    public function getLocation(): string {
        return $this->message;
    }

    public function shouldReplace(): bool {
        return $this->replace;
    }

    public function isNoAjaxSet(): bool {
        return $this->no_ajax;
    }
}