<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

abstract class CommonController extends BaseController
{
    private $_viewDatas = [];
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        // 세션 서비스 초기화
        $this->session = \Config\Services::session();
    }
    final public function __get($name)
    {
        if (!array_key_exists($name, $this->_viewDatas)) {
            return null;
        }
        return $this->_viewDatas[$name];
    }
    final public function __set($name, $value): void
    {
        $this->_viewDatas[$name] = $value;
    }
    final public function getViewDatas(): array
    {
        return $this->_viewDatas;
    }

    final protected function pushCurrentUrl()
    {
        $urlStack = $this->session->get('url_stack', []) ?? [];
        $urlStack[] = current_url() . ($this->request->getUri()->getQuery() ? "?" . $this->request->getUri()->getQuery() : "");
        $this->session->set('url_stack', $urlStack);
    }

    final protected function popPreviousUrl()
    {
        $urlStack = $this->session->get('url_stack', []);
        if (!empty($urlStack)) {
            return array_pop($urlStack);
        }
        return '/';  // 기본 URL
    }
}
