<?php

namespace KupShop\ElninoBundle\View;

use KupShop\I18nBundle\Translations\SectionsTranslation;
use Query\QueryBuilder;

class RedirectView extends \KupShop\ContentBundle\View\RedirectView
{
    public function handleProduct()
    {
        $data = sqlQueryBuilder()->select('am.old_kupshop_id')->from('products', 'p')
            ->join('p', 'abra_models', 'am', 'am.id_abra=p.id_model')
            ->join('am', 'abra_sections', 'abs', 'am.id_section=abs.id_abra')
            ->join('abs', 'sections', 's', 'abs.id_section=s.id')
            ->where('p.id=:product_id')->setParameter('product_id', $this->getId())
            ->andWhere(\Query\Translation::joinTranslatedFields(SectionsTranslation::class,
                function (QueryBuilder $qb, $columnName, $translatedField) {
                    if ($translatedField !== null) {
                        $qb->addSelect("CONCAT(COALESCE({$translatedField},s.name),' ',am.short_title) as model_title");
                    } else {
                        $qb->addSelect('CONCAT(s.name, " ", am.short_title) as model_title');
                    }
                }, ['name']))
            ->setMaxResults(1)
            ->execute()->fetch();

        return empty($data) ? path('home') : (path('kupshop_elnino_model_model', [
            'id' => $data['old_kupshop_id'],
            'name' => createScriptURL_Text($data['model_title']),
        ]).'#'.$this->getId());
    }
}
