<?php
	
	namespace AutoInstall\Core;
	
	use Tamtamchik\SimpleFlash\Flash;
	
	class Redirect
	{
		private string $page;
		private ?string $flashType;
		private ?array $flashMessage;
		
		public function __construct(string $page)
		{
			$this->page = $page;
			$this->flashType = null;
			$this->flashMessage = null;
		}
		
		/**
		 * Set redirect page to back
		 * @return void
		 */
		public function back() {
			$this->page = request()->getReferer();
		}
		
		
		/**
		 * Set flash message
		 * @param string $type
		 * @param string|array $message
		 * @return Redirect
		 */
		public function flash(string $type, $message): Redirect
		{
			$this->flashType = $type;
			if (is_array($message)) {
				$this->flashMessage = $message;
			} else {
				$this->flashMessage[] = $message;
			}

      if ($type === 'success') {
        if (isset($_SESSION['old'])) {
          unset($_SESSION['old']);
        }
      }

			return $this;
		}
		
		public function __destruct()
		{
			if ($this->flashType != null) {
				Flash::message($this->flashMessage, $this->flashType);
			}
			
			response()->redirect($this->page);
		}
	}