<?php

# documentation :
# https://omines.github.io/datatables-bundle
# https://datatables.net/

namespace App\Controller\Admin;

use App\Entity\User;
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\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

#[Route("/admin/users", name: "admin_users_")]
class UsersController extends AbstractController
{

    const SESSION_FIELD = "users_list_from_field";
    const SESSION_VALUE = "users_list_from_value";

    protected function getUser() : User {
        return parent::getUser();
    }

    #[Route('/', name: 'list')]
    public function list(Request $request, DataTableFactory $dataTableFactory, TranslatorInterface $t, SessionInterface $session)
    {
        return $this->_list("", "", $request, $dataTableFactory, $t, $session);
    }

    #[Route('/{field}/{value}', name: 'list_by', requirements:[ 
        "field" => "partner",
        "value" => "\d+|my"
    ] )]
    public function list_by(Request $request, DataTableFactory $dataTableFactory, TranslatorInterface $t, SessionInterface $session, string $field = "", string $value = "")
    {
        return $this->_list($field, $value, $request, $dataTableFactory, $t, $session);
    }


    private function _list(string $field, string $value, Request $request, DataTableFactory $dataTableFactory, TranslatorInterface $t, SessionInterface $session)
    {
        if (!$this->getUser()) { return $this->redirectToRoute('auth_login');}
        if (!in_array("ROLE_ADMIN", $this->getUser()->getRoles())) throw new AccessDeniedException();

        $t_root = "admin.user";

        $sponsor_id = "";

        switch ($field) {
            case 'partner':
                if ($value == "my") {
                    $sponsor_id = $this->getUser()->getSponsor()->getId();
                } else {
                    $sponsor_id = $value;
                }
                break;
            
            default:
                # code...
                break;
        }


        $table = $dataTableFactory->create()

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

            ->add('name', TextColumn::class, ['label' => "$t_root.fields.name", 'className' => 'bold'])
            ->addOrderBy('name', \Omines\DataTablesBundle\DataTable::SORT_ASCENDING)

            ->add('email', TextColumn::class, [
                'label' => "$t_root.fields.email", 
                'className' => 'email',
                'render' => function($value, $context) {
                    return "<a href='mailto:$value'>$value</a>";
                }
            ])
            // ->add('sponsor', TextColumn::class, ['label' => 'Structure', 'className' => 'bold'])

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

            ->add('roles', TwigColumn::class, [
                'label' => "$t_root.fields.roles", 
                'className' => 'roles',
                'template' => 'admin/user/list-fields/roles.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'
            ])

            ->add('actions', TextColumn::class, ['label' => '',
                'className' => 'col-actions',
                'render' => function($r_value, $context) use ($t, $t_root, $field, $value) {

                    $route = $this->generateUrl('admin_user_edit', ["id" => $context->getId()]);
                    return RenderHelper::render_btn_action("pen", $t->trans("$t_root.actions.edit", domain: 'admin'), $route, true);
                }
            ])

            ->createAdapter(ORMAdapter::class, [
                'entity' => User::class,
                'query' => function (QueryBuilder $builder) use ($sponsor_id) {
                    $builder
                        ->select('user')
                        ->addSelect('sponsor')
                        ->from(User::class, 'user')
                        ->leftJoin('user.sponsor', 'sponsor');

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

        // dump($table);

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

        if ($field != "") {
            $create_new_route = $this->generateUrl('admin_user_new_by', ["field" => $field, "value" => $value]);
        } else {
            $create_new_route = $this->generateUrl('admin_user_new');
        }

        $session->set(UsersController::SESSION_FIELD, $field);
        $session->set(UsersController::SESSION_VALUE, $value);

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

    #[Route('/auto', name: 'auto_redirect', priority: 2)]
    public function auto(SessionInterface $session)
    {
        // on redirige vers la liste
        $from_field = $session->get(UsersController::SESSION_FIELD);
        $from_value = $session->get(UsersController::SESSION_VALUE);

        // on redirige vers la liste
        if ($from_field != "") {
            return $this->redirectToRoute("admin_users_list_by", ["field" => $from_field, "value" => $from_value]);
        } else {
            return $this->redirectToRoute("admin_users_list");
        }
    }
}
