<?php

namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestEvent;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity;
use App\Entity\Blog;
use App\Entity\BlogTag;
use App\Entity\BlogLang;
use App\Controller\DefaultController;

class BlogController extends AbstractController{

    private $em;
    private $defaultController;

    public function __construct(EntityManagerInterface $em, DefaultController $defaultController){
        $this->em = $em;
        $this->defaultController = $defaultController;
    }

    public function getBlogTags(Request $request): array{
        $tagArray = [];
        $tags = $this->em->getRepository(BlogTag::class)->findAll();
        foreach($tags as $tag){
            // Sets the identifier as key and the text as value
            $tagArray[$tag->getIdentifier()] = $this->defaultController->getLangText($tag->getIdentifier(), $request);
        };
        return $tagArray;
    }

    public function getBlogLang(Blog $blog, string $locale){
        return $this->em->getRepository(BlogLang::class)->findOneBy(['blog'=>$blog->getId(), 'lang' => $this->defaultController->localeIndex[$locale]]);
    }

    public function getBlogs(array $args=[], Request $request): array{
        $perPage=6;
        $page=1;
        if (array_key_exists('perPage', $args)){ $perPage = $args['perPage']; } 
        if (array_key_exists('page', $args) && $args['page']){ $page = $args['page']; }
        $firstResult = ($page - 1) * $perPage;

        $blogs = $this->em->getRepository(Blog::class)->createQueryBuilder('blog')->select('blog')->where('blog.is_enabled = 1');
        $mainBlog = null;
        // Checks if there is a search query and shows the main blog only if there is not.
        if ((!array_key_exists('query', $args) || !$args['query']) && (!array_key_exists('tags', $args) || !$args['tags'])){
            $mainBlog = $this->em->getRepository(Blog::class)->findOneBy(['is_main'=>true, 'is_enabled'=>true]);
            if ($mainBlog){
                $blogs = $blogs->andwhere("blog.id != ".$mainBlog->getId());
            }else{
                $mainBlog = $this->em->getRepository(Blog::class)->createQueryBuilder('blog')
                ->select('blog')
                ->where('blog.is_enabled = 1')
                ->setMaxResults(1)
                ->leftJoin('blog.blogLangs', 'lang')
                ->addSelect('lang')
                ->andwhere("lang.lang = ".$this->defaultController->localeIndex[$request->getLocale()])
                ->addOrderBy('blog.created_at', 'DESC')
                ->getQuery()->getResult();
                if(count($mainBlog) > 0){
                    $firstResult = $firstResult + 1;
                    $mainBlog = $mainBlog[0];
                }
            }
        }

        $blogs = $blogs
            ->leftJoin('blog.blogLangs', 'lang')
            ->addSelect('lang')
            ->andwhere("lang.lang = ".$this->defaultController->localeIndex[$request->getLocale()])
            ->setFirstResult($firstResult)
            ->addOrderBy('blog.created_at', 'DESC');
        
        if (array_key_exists('query', $args) && $args['query']){
            $keywords = explode(' ', $args['query']);
            foreach($keywords as $keyword){
                $blogs->andwhere("lang.title LIKE '%".$keyword."%'");
            }
        }

        if (array_key_exists('tags', $args) && $args['tags']){
            foreach(explode(',', $args['tags']) as $tag){
                $blogs->andwhere('JSON_CONTAINS(blog.tagIdentifierArray, \'"' . $tag . '"\') = true');
            }
        }

        if (array_key_exists('exclude', $args) && $args['exclude']){
            foreach($args['exclude'] as $id){
                $blogs->andwhere("blog.id != ".$id);
            }
        }
        
        $pageCount = ceil(count($blogs->getQuery()->getResult()) / $perPage);
        if($pageCount == 1){$pageCount = $page;}
        else{$pageCount = $page + $pageCount - 1;}
        $blogs = $blogs->setMaxResults($perPage)->getQuery()->getResult();
        if($pageCount==0){$pageCount=1;}
        return [
            'blogs' => $blogs,
            'mainBlog' => $mainBlog,
            'pageCount' => $pageCount
        ];    
    }

    #[Route('/{_locale}/blog-search', name: 'blog_search')]
    public function blogsearch(Request $request): Response{
        $s=$request->query->get('s');
        $tags=$request->query->get('tags');
        $page=$request->query->get('page');
        return $this->defaultController->renderPage('components/_blog-content.html.twig');
    }
    
    #[Route([
        'tr' => '/haberler',
        'en' => '/{_locale}/news',
        'de' => '/{_locale}/nachrichten'
    ], name: 'blog')]
    public function blogpage(Request $request): Response{
        $s=$request->query->get('s');
        $tags=$request->query->get('tags');
        $page=$request->query->get('page');
        return $this->defaultController->renderPage('blog.html.twig');
    }

    #[Route([
        'tr' => '/haberler/{alias}',
        'en' => '/{_locale}/news/{alias}',
        'de' => '/{_locale}/news/{alias}'
    ], name: 'blog_detail')]
    public function blogdetailpage(Request $request, string $alias, string $_locale): Response{
        $blogLangs = $this->em->getRepository(BlogLang::class);
        $blogLang = $blogLangs->findOneBy(['alias' => $alias]);
        if ($blogLang->getLang()->getId() != $_locale){
            $blogLangDirect = $blogLangs->findOneBy(['lang'=>$_locale, 'blog'=>$blogLang->getBlog()->getId()]);
            if ($blogLangDirect){
                $alias = $blogLangDirect->getAlias();
                return $this->redirectToRoute('blog_detail', ['alias'=>$alias]);
            }
        }
        $blog = $blogLang->getBlog();
        return $this->defaultController->renderPage('blog-detail.html.twig', [
            "blog" => $blog,
            "breadcrumb" => ["blogs"]
        ]);
    }

}
