<?php

namespace App\Controller;

use App\Entity\Member;
use App\Entity\MemberCase;
use App\Entity\Referral;
use App\Entity\StandardNote;
use App\Entity\StandardNoteMember;
use App\Entity\User;
use App\Entity\UserCase;
use App\Entity\VisitNote;
use App\Entity\VisitNoteMembers;
use App\Enums\NoteLocation;
use App\Enums\NoteMethod;
use App\Enums\ReferralServiceType;
use App\Form\StandardNoteFormType;
use App\Form\VisitNoteFormType;
use App\Libs\Breadcrumb;
use App\Libs\Libs;
use App\Libs\NavList;
use DateTime;
use DateTimeZone;
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 NoteController extends AbstractController
{
    public function __construct(
        private EntityManagerInterface $entityManager,
        private array $navLinks = [],
    ) {
        $this->navLinks = NavList::LIST;
        $this->navLinks['case_notes'] = NavList::PRESENT_LINK;
    }

    #[Route('/list-notes/{caseId?null}', name: 'app_list_notes')]
    public function listNotes(string $caseId = null, #[CurrentUser()] User $user, Request $request): Response
    {
        /** @var UserCase[] $cases */
        $cases = $this->entityManager->getRepository(UserCase::class)->findBy(['user' => $user]);
        $caseNotes = null;
        $case = null;

        if ($caseId != 'null') {
            $case = $this->entityManager->getRepository(MemberCase::class)->find($caseId);
            $params = [
                'case' => $case,
                'referral' => null,
                'startDate' => null,
                'endDate' => null,
            ];
            $caseNotes = array_merge(
                $this->entityManager->getRepository(VisitNote::class)->filterNotes($user, $params),
                $this->entityManager->getRepository(StandardNote::class)->filterNotes($user, $params),
            );
        }

        return $this->render(
            'internal/cases/notes/list-notes.html.twig',
            array_merge(
                $this->navLinks,
                [
                    'breadcrumbs' => [
                        new Breadcrumb($this->generateUrl('app_list_notes'), 'List Notes')
                    ],
                    'notifications' => Libs::getMessages($user, $this->entityManager),
                    'cases' => $cases,
                    'caseNotes' => $caseNotes,
                    'case' => $case,
                ]
            )
        );
    }

    #[Route('/add-note/{referralId}', name: 'app_add_note')]
    public function addNote(#[CurrentUser()] User $user, Request $request, ?string $referralId = null): Response
    {
        /** @var Referral $referral */
        $referral = $this->entityManager->getRepository(Referral::class)->find($referralId);
        $this->entityManager->getRepository(Referral::class)->populateNotes($referral);

        $members = $this->entityManager->getRepository(Member::class)->findBy(['memberCase' => $referral->getMemberCase()]);
        $defaultMethod = NoteMethod::BILLABLE;
        $defaultLocation = NoteLocation::COMMUNITY_OUTING;
        $form = $this->createForm(StandardNoteFormType::class, null, ['members' => $members]);
        $template = 'internal/cases/notes/add-standard-note.html.twig';

        if ($referralId == 'null') {
            $referralId = null;
        }

        if ($referral->getServiceCode() == ReferralServiceType::VS_THBB) {
            $form = $this->createForm(VisitNoteFormType::class, null, ['members' => $members]);
            $template = 'internal/cases/notes/add-visit-note.html.twig';
            $defaultMethod = NoteMethod::BILLABLE_SUPERVISED_VISIT;
        } elseif ($referral->getServiceCode() == ReferralServiceType::VS_THBBT) {
            $defaultMethod = NoteMethod::BILLABLE;
            $defaultLocation = NoteLocation::VEHICLE_TRANSPORTATION;
        }

        $form = $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var VisitNote|StandardNote $note */
            $note = $form->getData();
            $note->setReferral($referral);

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

            if ($form->get('members')->getData()) {
                foreach ($form->get('members')->getData() as $mem) {
                    if ($referral->getServiceCode() == ReferralServiceType::VS_THBB) {
                        $nm = new VisitNoteMembers();
                        $nm->setVisitNote($note)
                           ->setPerson($mem)
                        ;
                    } else {
                        $nm = new StandardNoteMember();
                        $nm->setStandardNote($note)
                           ->setPerson($mem)
                        ;
                    }

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

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

            return $this->redirectToRoute('app_list_notes');
        }

        return $this->render(
            $template,
            array_merge(
                $this->navLinks,
                [
                    'breadcrumbs' => [
                        new Breadcrumb($this->generateUrl('app_list_notes'), 'List Notes')
                    ],
                    'notifications' => Libs::getMessages($user, $this->entityManager),
                    'referral' => $referral,
                    'form' => $form,
                    'members' => $members,
                    'default_method' => $defaultMethod,
                    'default_location' => $defaultLocation,
                ]
            )
        );
    }

    #[Route('/edit-note/{noteType}/{noteId}', name: 'app_edit_note')]
    public function editNote(string $noteId, string $noteType, #[CurrentUser()] User $user, Request $request): Response
    {
        $form = null;

        /** @var VisitNote|StandardNote $note */
        if ($noteType == 'visit') {
            $note = $this->entityManager->getRepository(VisitNote::class)->find($noteId);
            $members = $this->entityManager->getRepository(Member::class)->findBy(['memberCase' => $note->getReferral()->getMemberCase()]);
            $form = $this->createForm(VisitNoteFormType::class, $note, ['members' => $members]);
        } elseif ($noteType == 'standard') {
            $note = $this->entityManager->getRepository(StandardNote::class)->find($noteId);
            $members = $this->entityManager->getRepository(Member::class)->findBy(['memberCase' => $note->getReferral()->getMemberCase()]);
            $form = $this->createForm(StandardNoteFormType::class, $note, ['members' => $members]);
        }

        return $this->render(
            'internal/cases/notes/edit-note.html.twig',
            array_merge(
                $this->navLinks,
                [
                    'breadcrumbs' => [
                        new Breadcrumb($this->generateUrl('app_list_notes'), 'List Notes')
                    ],
                    'notifications' => Libs::getMessages($user, $this->entityManager),
                    'note' => $note,
                    'referral' => $note->getReferral(),
                    'form' => $form,
                    'noteType' => $noteType
                ]
            )
        );
    }
}
