<?php
declare(strict_types=1);

namespace App\Repository\Cotisation;


use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Query\ResultSetMapping;

class CotisationApiResourcesRepository
{
    public function __construct(private EntityManagerInterface $adminassosEntityManager)
    {
    }

    /**
     * Récupère l'état de la cotisation pour une structure et une année
     * @param int $organizationId
     * @param int $year
     * @return int|null
     */
    public function getAffiliationState(int $organizationId, int $year): ?int
    {
        $rsm = new ResultSetMapping();
        $rsm->addScalarResult('oa_miscellaneous_state_sta', 'oa_miscellaneous_state_sta');

        $sql = sprintf('SELECT oa_miscellaneous_state_sta as oa_miscellaneous_state_sta '
            . ' FROM oa_assos_state '
            . ' WHERE pid = %s AND year_sta = %s', $organizationId, $year);
        $query = $this->adminassosEntityManager->createNativeQuery($sql, $rsm);
        $result = $query->getOneOrNullResult();

        if (!empty($result)) {
            return (int) $result['oa_miscellaneous_state_sta'];
        }
        return null;
    }

    /**
     * Retourne vrai si la structure n'a pas rempli son assurance pour une année
     * @param int $organizationId
     * @param int $year
     * @return bool
     */
    public function isInsuranceNotDone(int $organizationId, int $year): bool
    {
        $rsm = new ResultSetMapping();
        $rsm->addScalarResult('done', 'done');

        $sql = sprintf('SELECT done as done '
            . ' FROM oa_contribution_fede_insurance '
            . ' INNER JOIN oa_assos ON oa_contribution_fede_insurance.pid = oa_assos.pid '
            . ' INNER JOIN dgv_assurance ON declare_nb_fed_aso = id_unique_dgv '
            . ' WHERE oa_contribution_fede_insurance.pid = %s AND year_cfi = %s ', $organizationId, $year);

        $query = $this->adminassosEntityManager->createNativeQuery($sql, $rsm);
        $result = $query->getOneOrNullResult();

        return !empty($result) && $result['done'] === 0;
    }

    /**
     * Retourne vrai si la structure n'est pas un client DGV
     * @param int $organizationId
     * @return bool
     */
    public function isNotDGVCustomer(int $organizationId): bool
    {
        $rsm = new ResultSetMapping();
        $rsm->addScalarResult('total', 'total');

        $sql = sprintf('SELECT COUNT(*) as total '
            . ' FROM dgv_assurance '
            . ' INNER JOIN oa_assos ON declare_nb_fed_aso = id_unique_dgv '
            . ' WHERE pid = %s ', $organizationId);

        $query = $this->adminassosEntityManager->createNativeQuery($sql, $rsm);
        $result = $query->getOneOrNullResult();

        return !empty($result) && $result['total'] === 0;
    }
}
