<?php

namespace App\Controller\Admin;

use App\Entity\User;
use App\Entity\Sponsor;
use App\Utils\RenderHelper;
use Doctrine\ORM\QueryBuilder;
use Omines\DataTablesBundle\Column\MapColumn;
use Omines\DataTablesBundle\DataTableFactory;
use Symfony\Component\HttpFoundation\Request;
use Omines\DataTablesBundle\Column\BoolColumn;
use Omines\DataTablesBundle\Column\TextColumn;
use Omines\DataTablesBundle\Column\TwigColumn;
use Symfony\Component\HttpFoundation\Response;
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;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

#[Route("/admin/sponsors", name: "admin_sponsors_")]
class SponsorsController extends AbstractController
{
    protected function getUser() : User {
        return parent::getUser();
    }

    #[Route('/', name: 'list')]
    public function list(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();
        $t_root = "admin.sponsor";

        $table = $dataTableFactory->create()
            
            ->setTranslationDomain('admin')

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

            // ->add('dump', TwigStringColumn::class, ['template' => '{{ dump(row) }}'])

            ->add('logoFileName', TwigStringColumn::class, [
                'label' => "$t_root.fields.logo", 
                'className' => 'sponsor-logo',
                'template' => '<img src="{{ vich_uploader_asset(row, \'logoFile\') | imagine_filter_cache(\'sponsor_logo_filter\') }}" alt="{{row.name}}" />',
            ])

            ->add('name', TextColumn::class, ['label' => "$t_root.fields.name"])

            ->add('type', TwigColumn::class, 
                ['label' => "$t_root.fields.type", 
                    'template' => 'admin\sponsor\list-fields\type.html.twig'
                ],
            )
            ->addOrderBy('type', \Omines\DataTablesBundle\DataTable::SORT_ASCENDING)

            ->add('sort_name', TextColumn::class, ['visible' => false])
            ->addOrderBy('sort_name', \Omines\DataTablesBundle\DataTable::SORT_ASCENDING)

            # besoin des champs pour les afficher dans le template suivant
            ->add('url', TextColumn::class, ['visible' => false])
            ->add('address', TextColumn::class, ['visible' => false])
            ->add('email', TextColumn::class, ['visible' => false])
            ->add('phone', TextColumn::class, ['visible' => false])

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

            ->add('active', BoolColumn::class, ['label' => "$t_root.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'
            ]);

            if ($user->isAdmin()) {
                $table->add('users', TextColumn::class, 
                    ['label' => "$t_root.fields.@users.short",
                    'className' => 'list-count',
                    'render' => function($value, $context) {

                        $render = "";

                        $count = $context->getUsers()->count();
                        $route_list = $this->generateUrl("admin_users_list_by", ['field' => 'partner', 'value' => $context->getId()]);
                        $render .= RenderHelper::render_linked_list($count, "users", $route_list);

                        $route_add = $this->generateUrl('admin_user_new_by', ["field" => 'partner', "value" => $context->getId()]);
                        $render .= RenderHelper::render_btn_action_quick("plus", $route_add, true /* déjà admin */, false);
    
                        return $render;
                    }],
                );
            }

            $table->add('events', TextColumn::class, 
                 ['label' => "$t_root.fields.@events.short",
                 'className' => 'list-count',
                 'render' => function($value, $context) use ($user) {

                        $render = "";

                        $count = $context->getEvents()->count();
                        $route_list = $this->generateUrl("admin_events_list_by", ['field' => 'partner', 'value' => $context->getId()]);
                        $render .= RenderHelper::render_linked_list($count, "calendar-days", $route_list);

                        $route_add = $this->generateUrl('admin_event_new_by', ["field" => 'partner', "value" => $context->getId()]);
                        $render .= RenderHelper::render_btn_action_quick("plus", $route_add, $context->getRealRoleForUser($user) == "ROLE_EDITOR", false);

                        return $render;
                }],
            )

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

            ->createAdapter(ORMAdapter::class, [
                'entity' => Sponsor::class
            ])

            ->handleRequest($request);

        // dump($table);

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

        return $this->render('admin/sponsor/list.html.twig', [
            'datatable' => $table,
            'allow_create_new' => $user->isAdmin(),
            'create_new_route'  => $this->generateUrl('admin_sponsor_new'),
        ]);
    }
}
