<?php
namespace Autogedal\InternalLinks\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Autogedal\InternalLinks\Model\Config;
use Magento\Framework\Controller\Result\ForwardFactory;
use Autogedal\InternalLinks\Service\SlugHandler;
use Autogedal\InternalLinks\Model\Brand;

class Details extends Action
{
    private $resultPageFactory;
    private $config;
    private $forwardFactory;
    private $slugHandler;
    private $brand;

    public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
        Config $config,
        ForwardFactory $forwardFactory,
        SlugHandler $slugHandler,
        Brand $brand
    ) {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
        $this->config = $config;
        $this->forwardFactory = $forwardFactory;
        $this->slugHandler = $slugHandler;
        $this->brand = $brand;
    }

    public function execute()
    {
        $brandSlug = $this->getRequest()->getParam('brand');

        if (
            !$this->config->isEnabled() ||
            !$brandSlug ||
            !$this->slugHandler->validateSlug($brandSlug) ||
            !$this->brand->getBySlug($brandSlug)
        ) {
            return $this->forwardFactory->create()->forward('noroute');
        }

        $brandOption = $this->brand->getBySlug($brandSlug);
        $resultPage = $this->resultPageFactory->create();

        $titleTemplate = $this->config->getBrandMetaTitle();
        $descriptionTemplate = $this->config->getBrandMetaDescription();
        $keywordsTemplate = $this->config->getBrandMetaKeywords();

        $title = str_replace('%s', $brandOption->value, $titleTemplate);
        $description = str_replace('%s', $brandOption->value, $descriptionTemplate);
        $keywords = str_replace('%s', $brandOption->value, $keywordsTemplate);

        $resultPage->getConfig()->getTitle()->set(__($title));
        $resultPage->getConfig()->setMetadata('description', __($description));
        $resultPage->getConfig()->setMetadata('keywords', __($keywords));

        return $resultPage;
    }
}
