<?php

namespace App\Controller;

use App\Entity\MemberCase;
use App\Entity\Messages;
use App\Entity\Referral;
use App\Entity\User;
use App\Entity\UserCase;
use App\Factory\MessageFactory;
use App\Form\ReferralFormType;
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\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Attribute\CurrentUser;

class ReferralController extends AbstractController
{
    /**
     * Variable to store unread notification messages
     *
     * @var array
     */
    private array $msgs;

    public function __construct(
        private EntityManagerInterface $entityManager,
        private array $navLinks = []
    ) {
        $this->navLinks = NavList::LIST;
        if (strpos($_SERVER['HTTP_REFERER'], 'my-cases') !== false) {
            $this->navLinks['my_cases'] = NavList::PRESENT_LINK;
        } else {
            $this->navLinks['case_list'] = NavList::PRESENT_LINK;
        }
    }

    #[Route('/list-referrals/{id}', name: 'app_list_referrals')]
    public function listReferrals(#[CurrentUser()] User $user, string $id, Request $request): Response
    {
        $this->msgs = Libs::getMessages($user, $this->entityManager);

        $case = $this->entityManager->getRepository(MemberCase::class)->find($id);
        $openReferrals = $this->entityManager->getRepository(Referral::class)->getActiveReferrals($case);
        $closedReferrals = $this->entityManager->getRepository(Referral::class)->getClosedReferrals($case);

        return $this->render(
            'internal/cases/referrals/list-referrals.html.twig',
            array_merge(
                $this->navLinks,
                [
                    'breadcrumbs' => [
                        (
                            strpos($request->server->get('HTTP_REFERER'), 'my-cases') !== false
                                ? new Breadcrumb($this->generateUrl('app_my_cases'), 'My Cases')
                                : new Breadcrumb($this->generateUrl('app_list_cases'), 'List Cases')
                        ),
                        new Breadcrumb($this->generateUrl('app_list_referrals', ['id' => $case->getId()]), 'Referrals'),
                    ],
                    'notifications' => $this->msgs,
                    'case' => $case,
                    'openReferrals' => $openReferrals,
                    'closedReferrals' => $closedReferrals,
                ]
            )
        );
    }

    #[Route('/add-referral/{id}', name: 'app_case_add_referral')]
    public function addReferral(Request $request, #[CurrentUser()] User $user, string $id): Response
    {
        $this->denyAccessUnlessGranted(['ROLE_ADMIN', 'ROLE_CASE_MANAGER']);
        $this->msgs = Libs::getMessages($user, $this->entityManager);
        
        $case = $this->entityManager->getRepository(MemberCase::class)->find($id);
        /** @var UserCase $uc */
        $uc = $this->entityManager->getRepository(UserCase::class)->findBy(['memberCase' => $case]);

        $referral = new Referral();
        $form = $this->createForm(ReferralFormType::class, $referral);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $referral = $form->getData();
            $referral->setMemberCase($case);

            $msg = MessageFactory::createReferral($user, $uc->getUser(), $case);

            $this->entityManager->persist($msg);
            $this->entityManager->persist($referral);
            $this->entityManager->flush();

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

        return $this->render(
            'internal/cases/referrals/add-referral.html.twig',
            array_merge(
                $this->navLinks,
                [
                    'breadcrumbs' => [
                        new Breadcrumb($this->generateUrl('app_list_cases'), 'List Cases'),
                        new Breadcrumb($this->generateUrl('app_list_referrals', ['id' => $case->getId()]), 'Referrals'),
                        new Breadcrumb($this->generateUrl('app_case_add_referral', ['id' => $case->getId()]), 'Add Referral')
                    ],
                    'notifications' => $this->msgs,
                    'case' => $case,
                    'form' => $form,
                ]
            )
        );
    }

    #[Route('/case/{caseId}/edit-referral/{referralId}', name: 'app_case_edit_referral')]
    public function editReferral(Request $request, #[CurrentUser()] User $user, string $caseId, string $referralId): Response
    {
        $this->denyAccessUnlessGranted(['ROLE_ADMIN', 'ROLE_CASE_MANAGER']);
        $this->msgs = Libs::getMessages($user, $this->entityManager);
        
        $referral = $this->entityManager->getRepository(Referral::class)->find($referralId);
        $case = $this->entityManager->getRepository(MemberCase::class)->find($caseId);
        /** @var UserCase $uc */
        $uc = $this->entityManager->getRepository(UserCase::class)->findBy(['case' => $case]);

        $form = $this->createForm(ReferralFormType::class, $referral);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $referral = $form->getData();

            $msg = MessageFactory::createReferral($user, $uc->getUser(), $case);

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

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

        return $this->render(
            'internal/cases/referrals/edit-referral.html.twig',
            array_merge(
                $this->navLinks,
                [
                    'breadcrumbs' => [
                        new Breadcrumb($this->generateUrl('app_list_cases'), 'List Cases'),
                        new Breadcrumb($this->generateUrl('app_list_referrals', ['id' => $case->getId()]), 'Referrals'),
                        new Breadcrumb($this->generateUrl('app_case_edit_referral', ['caseId' => $case->getId(), 'referralId' => $referral->getId()]), 'Edit Referral'),
                    ],
                    'notifications' => $this->msgs,
                    'case' => $case,
                    'form' => $form,
                    'referral' => $referral,
                ]
            )
        );
    }
}
