<?php

namespace App\Controller\Admin;
use App\Entity\User;
use App\Entity\Event;
use App\Utils\RenderHelper;
use Doctrine\ORM\QueryBuilder;
use Omines\DataTablesBundle\DataTableFactory;
use Symfony\Component\HttpFoundation\Request;
use Omines\DataTablesBundle\Column\BoolColumn;
use Omines\DataTablesBundle\Column\TextColumn;
use Symfony\Component\Routing\Annotation\Route;
use Omines\DataTablesBundle\Column\TwigStringColumn;
use Symfony\Contracts\Translation\TranslatorInterface;
use Omines\DataTablesBundle\Adapter\Doctrine\ORMAdapter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

#[Route("/admin", name: "admin_")]
class HomeController extends AbstractController
{
    protected function getUser() : User {
        return parent::getUser();
    }
    
    #[Route("/", name: "home")]
    public function index(Request $request, DataTableFactory $dataTableFactory, TranslatorInterface $t) {

        if (!$this->getUser()) { return $this->redirectToRoute('auth_login');}
        if (!in_array("ROLE_EDITOR", $this->getUser()->getRoles())) throw new AccessDeniedException();

        $user = $this->getUser();
        $sponsor_id = $user->getSponsor()->getId();
        $t_root_event = "admin.event";
        $event_with_actions = $dataTableFactory->create()

        ->setTranslationDomain('admin')

        ->add('id', TextColumn::class, ['label' => 'id', 'className' => 'id'])

        ->add('status', TwigStringColumn::class, [
            'label' => "$t_root_event.fields.status",
            'className' => 'status',
            'template' => '<img src="{{ asset(\'build/img/icon/admin-event-status-\' ~ row.status.value ~\'.png\') }}" alt="{{row.status.name}}" />'
        ])

        ->add('title', TextColumn::class, ['label' => "$t_root_event.fields.title", 'className' => 'bold'])

        ->add('imgPresentationFileName', TwigStringColumn::class, [
            'label' => "$t_root_event.fields.presentation",
            'className' => 'event-presentation',
            'template' => '<twig:ImageOrVideo entity="{{ row }}" imageFileNameField="imgPresentationFileName" imageFileField="imgPresentationFile" videoField="videoPresentation" alt="{{ row.title }}" filter="admin_event_list_filter" />',
        ])

        // ->add('sponsors', TwigColumn::class, [
        //     'label' => "$t_root.fields.sponsor",
        //     'className' => 'sponsors-logo',
        //     'template' => 'admin\event\list-fields\sponsors.html.twig',
        // ])

        // ->add('dates', TwigColumn::class, [
        //     'label' => "$t_root.fields.dates",
        //     'className' => 'event-dates',
        //     'template' => 'admin\event\list-fields\dates.html.twig',
        // ])

        // ->add('type', TextColumn::class, [
        //     'label' => "$t_root.fields.type",
        //     'className' => 'type',
        //     'render' => function($value, $context) {
        //         return $context->getType()->getName();
        //     }
        // ])

        // ->add('performers', TwigColumn::class,
        //     ['label' => "$t_root.fields.performers",
        //     'className' => 'event-performers',
        //     'template' => 'admin\event\list-fields\performers.html.twig'
        //     ]
        // )

        ->add('medias', TextColumn::class,
             ['label' => "$t_root_event.fields.media",
             'className' => 'list-count',
             'render' => function($value, $context) {

                $count = $context->getMedias()->count();

                $route_list = $this->generateUrl("admin_event_medias_list", ['event_id' => $context->getId()]);
                return RenderHelper::render_linked_list($count, "images", $route_list);
            }],
        )

        ->add('active', BoolColumn::class, ['label' => "$t_root_event.fields.active",
            'trueValue' => '<span class="badge bg-success"><i class="fa fa-check"></i>&nbsp;' . $t->trans('active.true', domain: 'fields') . '</span>',
            'falseValue' => '<span class="badge bg-danger"><i class="fa fa-ban"></i>&nbsp;' . $t->trans('active.false', domain: 'fields') . '</span>',
            'nullValue' => 'unknown'
        ])

        ->add('actions', TextColumn::class, ['label' => '',
            'className' => 'col-actions',
            'render' => function($value, $context) use ($t, $t_root_event, $user) {
                $route = $this->generateUrl('admin_event_edit', ["id" => $context->getId()]);
                return RenderHelper::render_btn_action("pen", $t->trans("$t_root_event.actions.edit", domain: 'admin'), $route, $context->getRealRoleForUser($user) == "ROLE_EDITOR");
            }
        ])

        ->createAdapter(ORMAdapter::class, [
            'entity' => Event::class,
            'query' => function (QueryBuilder $builder) use ($sponsor_id) {
                $builder
                    ->select('event')
                    ->addSelect('typeevent')
                    ->from(Event::class, 'event')
                    ->innerJoin('event.type', 'typeevent')
                    ->distinct()->innerJoin('event.dates', 'ed')
                    ->leftJoin('event.medias', 'media')
                    ->andWhere('event.force_no_media = 0')
                    ->andWhere("event.status in ('done', 'pending')")
                    ->andWhere('ed.date < CURRENT_TIMESTAMP()')
                    ->andWhere('media is null')
                    ;

                if (!empty($sponsor_id)) {
                    $builder
                        ->distinct()->innerJoin('event.sponsors', 'sponsors')
                        ->andWhere("sponsors.sponsor = :sponsor_id")->setParameter("sponsor_id", $sponsor_id)
                    ;
                }
            },
        ])
        ->handleRequest($request);

    // dump($table);

    if ($event_with_actions->isCallback()) {
        // dump($table);
        return $event_with_actions->getResponse();
    }

    return $this->render("admin/home.html.twig", [
        'datatable_events_actions' => $event_with_actions,
    ]);
    }
}