<?php

namespace App\Repository;

use App\Entity\Bibliography;
use App\Entity\Site;
use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Query\ResultSetMappingBuilder;

/**
 * @extends ServiceEntityRepository<ConservationPlace>
 */
class SiteRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Site::class);
    }

    public function hasCreatorEditor(string $creator): bool
    {
        $em = $this->getEntityManager();
        $repo = $em->getRepository(User::class);
        
        $creator = $repo->findOneBy(['username' => $creator]);

        return in_array('ROLE_EDITOR', $creator->getRoles());
    }

    public function findAllByCollection(int $collectionId): ?ArrayCollection
    {
        $rsm = new ResultSetMappingBuilder($this->getEntityManager());
        $rsm->addRootEntityFromClassMetadata('App\Entity\ConservationPlace', 'c');

        $query = $this->getEntityManager()->createNativeQuery(
            "SELECT
                id,
                stato,
                editor,
                luogo_cons,
                com_cons
            FROM sito s
            JOIN rel_sito_collezione
            ON Sito_id_sito = id
            WHERE Collezione_id_coll = :collId",
            $rsm
        );
        $query->setParameter('collId', $collectionId);

        return new ArrayCollection($query->getResult());
    }

    public function findAllByObject(int $objectId): ?ArrayCollection
    {
        $rsm = new ResultSetMappingBuilder($this->getEntityManager());
        $rsm->addRootEntityFromClassMetadata('App\Entity\ConservationPlace', 'c');

        $query = $this->getEntityManager()->createNativeQuery(
            "SELECT
                id,
                stato,
                editor,
                luogo_cons,
                com_cons
            FROM conservation_place c
            JOIN rel_conservazione_reperto
            ON Conservazione_id_cons = id
            WHERE Reperto_id_rep = :objectId",
            $rsm
        );
        $query->setParameter('objectId', $objectId);

        return new ArrayCollection($query->getResult());
    }

    public function coordinates(int $id): ?array
    {
        $conn = $this->getEntityManager()->getConnection();

        $sql = '
            SELECT
                ST_X(coord_sito) as lng,
                ST_Y(coord_sito) as lat
            FROM site s
            WHERE s.id = :id
        ';

        $result = $conn->executeQuery($sql, ['id' => $id]);

        return $result->fetchAssociative();
    }
}
