<?php

namespace App\Patient\Repository;

use App\Patient\Entity\PatientRecord;
use App\Patient\Entity\PatientSession;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

class PatientSessionRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, PatientSession::class);
    }

    public function findByUuid(string $uuid): ?PatientSession
    {
        return $this->findOneBy(['uuid' => $uuid]);
    }

    public function findByRecord(PatientRecord $record, int $page = 1, int $limit = 20): array
    {
        return $this->createQueryBuilder('s')
            ->where('s.record = :record')
            ->setParameter('record', $record)
            ->orderBy('s.id', 'DESC')
            ->setFirstResult(($page - 1) * $limit)
            ->setMaxResults($limit)
            ->getQuery()
            ->getResult();
    }

    public function countByRecord(PatientRecord $record): int
    {
        return (int) $this->createQueryBuilder('s')
            ->select('COUNT(s.id)')
            ->where('s.record = :record')
            ->setParameter('record', $record)
            ->getQuery()
            ->getSingleScalarResult();
    }

    public function sumRevenue(string $entityType, int $entityId, int $from, int $to): int
    {
        $result = $this->createQueryBuilder('s')
            ->select('SUM(s.finalPriceRials)')
            ->join('s.record', 'r')
            ->where('r.entityType = :type')
            ->andWhere('r.entityId = :id')
            ->andWhere('s.createdAt BETWEEN :from AND :to')
            ->setParameter('type', $entityType)
            ->setParameter('id', $entityId)
            ->setParameter('from', $from)
            ->setParameter('to', $to)
            ->getQuery()
            ->getSingleScalarResult();

        return (int) ($result ?? 0);
    }

    public function save(PatientSession $session): void
    {
        $this->getEntityManager()->persist($session);
        $this->getEntityManager()->flush();
    }

    /**
     * تاریخ ثبت چند مراجعه — کلیددار بر اساس id جلسه.
     * @param int[] $ids
     * @return array<int, int> sessionId => createdAt
     */
    public function datesForIds(array $ids): array
    {
        if ($ids === []) {
            return [];
        }

        $rows = $this->createQueryBuilder('s')
            ->select('s.id AS id', 's.createdAt AS created_at')
            ->where('s.id IN (:ids)')
            ->setParameter('ids', $ids)
            ->getQuery()
            ->getArrayResult();

        $out = [];
        foreach ($rows as $r) {
            $out[(int) $r['id']] = (int) $r['created_at'];
        }
        return $out;
    }

    /**
     * نام و موبایل بیمار هر مراجعه — کلیددار بر اساس id جلسه.
     * @param int[] $ids
     * @return array<int, array{name: ?string, mobile: ?string}>
     */
    public function patientInfoForIds(array $ids): array
    {
        if ($ids === []) {
            return [];
        }

        $rows = $this->createQueryBuilder('s')
            ->select('s.id AS id', 'u.realName AS name', 'u.mobileNumber AS mobile')
            ->join('s.record', 'r')
            ->join('r.user', 'u')
            ->where('s.id IN (:ids)')
            ->setParameter('ids', $ids)
            ->getQuery()
            ->getArrayResult();

        $out = [];
        foreach ($rows as $r) {
            $out[(int) $r['id']] = ['name' => $r['name'], 'mobile' => $r['mobile']];
        }
        return $out;
    }
}
