<?php

declare(strict_types=1);

namespace Application;

use Application\Service\Extension\Laminas;
use Laminas\Http\Header\SetCookie;
use Laminas\Http\Response;
use Laminas\Mvc\MvcEvent;

class Module
{
    /**
     * @return array<string,mixed>
     */
    public function getConfig()
    {
        return include __DIR__ . '/../config/module.config.php';
    }

    public function onBootstrap($e)
    {
        Laminas::initialize($e->getApplication());

        // 全局设置响应头
        $e->getApplication()->getEventManager()->attach(MvcEvent::EVENT_RENDER, [$this, 'addHeader']);
    }

    public function addHeader(MvcEvent $e)
    {
        $response = $e->getResponse();
        if ($response instanceof Response) {
            $headers = $response->getHeaders();

            $responseHeaderConfig = $e->getApplication()->getServiceManager()->get('config')['response'];
            foreach(($responseHeaderConfig['header'] ?? []) as $key => $value) {
                if ($key == 'Set-Cookie') {
                    $cookies = $e->getApplication()->getRequest()->getCookie();
                    if(! empty($cookies)) {
                        $setCookie = new SetCookie();
                        foreach ($cookies as $cookieName => $cookieValue) {
                            $setCookie->setName($cookieName)
                            ->setValue($cookieValue)
                            ->setPath('/')
                            ->setSecure(true)
                            ->setHttpOnly(true);
                        }

                        $headers->addHeader($setCookie);
                    }

                }else {
                    $headers->addHeaderLine($key, $value);
                }
            }
        }
    }
}
