<?php

namespace App\Controller;

use App\Entity\CompanyDocument;
use App\Entity\Member;
use App\Entity\MemberCase;
use App\Entity\MemberDocument;
use App\Entity\Messages;
use App\Entity\User;
use App\Entity\UserCase;
use App\Form\MemberFormType;
use App\Libs\Breadcrumb;
use App\Libs\Libs;
use App\Libs\NavList;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\CurrentUser;

class MemberController extends AbstractController
{
    public function __construct(
        private EntityManagerInterface $entityManager,
        private array $navLinks = [],
    ) {
        $this->navLinks = NavList::LIST;
        $this->navLinks['case_list'] = NavList::PRESENT_LINK;
    }

    #[Route('/list-members/{id}', name: 'app_case_members')]
    public function listMembers(Request $request, #[CurrentUser()] User $user, string $id): Response
    {
        $case = $this->entityManager->getRepository(MemberCase::class)->find($id);
        $members = $this->entityManager->getRepository(Member::class)->getCaseMembersByName($case);

        return $this->render(
            'internal/cases/members/list-members.html.twig',
            array_merge(
                $this->navLinks,
                [
                    'breadcrumbs' => [
                        new Breadcrumb($this->generateUrl('app_list_cases'), 'List Cases'),
                        new Breadcrumb($this->generateUrl('app_case_members', ['id' => $id]), 'List Members'),
                    ],
                    'notifications' => Libs::getMessages($user, $this->entityManager),
                    'case' => $case,
                    'members' => $members,
                ]
            )
        );
    }

    #[Route('/add-member/{id}', name: 'app_case_add_member')]
    public function addMember(Request $request, #[CurrentUser()] User $user, string $id): Response
    {
        /** @var MemberCase $case */
        $case = $this->entityManager->getRepository(MemberCase::class)->find($id);
        /** @var UserCase $userCase */
        $userCase = $this->entityManager->getRepository(UserCase::class)->findOneBy(['memberCase' => $case]);
        /** @var User $caseWorker */
        $caseWorker = $userCase->getUser();

        /** @var array $docs<int, CompanyDocuments> */
        $docs = $this->entityManager->getRepository(CompanyDocument::class)->findBy(['company' => $user->getCompany()], ['title' => 'ASC']);

        $member = new Member();
        $form = $this->createForm(MemberFormType::class, $member, ['docs' => $docs]);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $member = $form->getData();
            $member->setCaseId($case)
                   ->setChild(($form->get('isChild') ? true : false))
                   ->setParent(($form->get('isParent') ? true : false))
                   ->setAdultChild(($form->get('isAdultChild') ? true : false))
                   ->setLegalGuardian(($form->get('isLegalGuardian') ? true : false))
                   ->setParentsLiveTogether(($form->get('parentsLiveTogether') ? true : false))
                   ->setDcsApproved(($form->get('dcsApproved') ? true : false))
            ;

            $this->entityManager->persist($member);
            $this->entityManager->flush();

            $selectedDocs = $form->get('docs');
            foreach ($selectedDocs->getData() as $doc) {
                $dbDoc = $this->entityManager->getRepository(CompanyDocument::class)->find($doc);
                if (!$dbDoc) {
                    continue;
                }
                $md = new MemberDocument();
                $md->setClient($member)
                   ->setDocument($dbDoc)
                   ->setCaseWorker($caseWorker)
                ;
                $this->entityManager->persist($md);
                $this->entityManager->flush();
            }

            $this->addFlash(
                'success',
                'Member added successfully'
            );

            return $this->redirectToRoute('app_case_members', ['id' => $case->getId()]);
        }

        return $this->render(
            'internal/cases/members/add-member.html.twig',
            array_merge(
                $this->navLinks,
                [
                    'breadcrumbs' => [
                        new Breadcrumb($this->generateUrl('app_list_cases'), 'List Cases'),
                        new Breadcrumb($this->generateUrl('app_case_members', ['id' => $id]), 'List Members'),
                        new Breadcrumb($this->generateUrl('app_case_add_member', ['id' => $id]), 'Add Member'),
                    ],
                    'notifications' => Libs::getMessages($user, $this->entityManager),
                    'case' => $case,
                    'form' => $form->createView(),
                    'docs' => $docs,
                ]
            )
        );
    }

    #[Route('/case/{caseId}/edit-member/{memberId}', name: 'app_case_edit_member')]
    public function editMember(Request $request, #[CurrentUser()] User $user, string $caseId, string $memberId): Response
    {
        /** @var Member $member */
        $member = $this->entityManager->getRepository(Member::class)->find($memberId);
        /** @var MemberCase $case */
        $case = $this->entityManager->getRepository(MemberCase::class)->find($caseId);

        /** @var array<int, CompanyDocuments> $docs */
        $docs = $this->entityManager->getRepository(CompanyDocument::class)->findBy(['company' => $user->getCompany()], ['title' => 'ASC']);
        /** @var array<int, MemberDocument> $memberDocs */
        $memberDocs = $this->entityManager->getRepository(MemberDocument::class)->findBy(['client' => $member]);
        $memberDbDocs = [];
        foreach($memberDocs as $md) {
            $memberDbDocs[] = $md->getDocument()->getId()->toString();
        }

        foreach ($docs as $idx => $d) {
            if (in_array($d->getId()->toString(), $memberDbDocs)) {
                $docs[$idx]->setSelected();
            }
        }

        $form = $this->createForm(MemberFormType::class, $member, ['docs' => $docs]);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $member = $form->getData();
            $member->setChild(($form->get('isChild') ? true : false))
                   ->setParent(($form->get('isParent') ? true : false))
                   ->setAdultChild(($form->get('isAdultChild') ? true : false))
                   ->setLegalGuardian(($form->get('isLegalGuardian') ? true : false))
                   ->setParentsLiveTogether(($form->get('parentsLiveTogether') ? true : false))
                   ->setDcsApproved(($form->get('dcsApproved') ? true : false))
            ;

            $this->entityManager->getRepository(MemberDocument::class)->removeUnsigned($member);

            $selectedDocs = $form->get('docs')->getData();

            foreach ($selectedDocs as $d) {
                $md = new MemberDocument();
                $md->setClient($member)
                   ->setCaseWorker($user)
                   ->setDocument($d)
                ;

                $this->entityManager->persist($md);
                $this->entityManager->flush();
            }

            $this->entityManager->flush();

            $this->addFlash(
                'success',
                'Member updated successfully'
            );

            return $this->redirectToRoute('app_case_members', ['id' => $caseId]);
        }

        return $this->render(
            'internal/cases/members/edit-member.html.twig',
            array_merge(
                $this->navLinks,
                [
                    'breadcrumbs' => [
                        new Breadcrumb($this->generateUrl('app_list_cases'), 'Cases'),
                        new Breadcrumb($this->generateUrl('app_case_members', ['id' => $caseId]), 'Members'),
                        new Breadcrumb($this->generateUrl('app_case_edit_member', ['caseId' => $caseId, 'memberId' => $memberId]), 'Edit Member'),
                    ],
                    'notifications' => Libs::getMessages($user, $this->entityManager),
                    'member' => $member,
                    'form' => $form->createView(),
                    'caseId' => $caseId,
                    'docs' => $docs,
                    'selectedDocs' => $memberDbDocs,
                ]
            )
        );
    }
}
