<?php

namespace App\Controller;

use App\Entity\CompanyDocument;
use App\Entity\Member;
use App\Entity\MemberDocument;
use App\Entity\User;
use App\Libs\Breadcrumb;
use App\Libs\NavList;
use App\Libs\Libs;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\CurrentUser;

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

    #[Route('/member/{memberId}', name: 'app_display_case_doc')]
    public function displayCaseDocument(string $memberId, #[CurrentUser()] User $user): Response
    {
        /** @var Member $member */
        $member = $this->entityManager->getRepository(Member::class)->find($memberId);
        $memberDocs = $this->entityManager->getRepository(MemberDocument::class)->findBy(['client' => $member]);

        return $this->render(
            'internal/cases/members/documents/list-member-docs.html.twig',
            array_merge(
                $this->navLinks,
                [
                    'notifications' => Libs::getMessages($user, $this->entityManager),
                    'breadcrumbs' => [
                        new Breadcrumb($this->generateUrl('app_my_cases'), 'Cases'),
                        new Breadcrumb($this->generateUrl('app_case_members', ['id' => $member->getCaseId()->getId()->toString()]), 'Members'),
                    ],
                    'docs' => $memberDocs,
                ]
            )
        );
    }

    #[Route('/member/{memberId}/document/{docId}/sign', name: 'app_member_sign_case_doc')]
    public function signCaseDocument(string $memberId, string $docId, #[CurrentUser()] User $user): Response
    {
        /** @var Member $member */
        $member = $this->entityManager->getRepository(Member::class)->find($memberId);
        $doc = $this->entityManager->getRepository(CompanyDocument::class)->find($docId);

        $memDoc = $this->entityManager->getRepository(MemberDocument::class)->findOneBy([
            'document' => $doc,
            'client' => $member,
            'caseWorker' => $user
        ]);
        
        if (!$memDoc) {
            throw new NotFoundHttpException('Document not found');
        }

        return $this->render(
            'internal/cases/members/documents/sign-member-doc.html.twig', [
                'doc' => $memDoc,
                'caseWorkerSignature' => $user->getSignature(),
            ]
        );
    }
}