<?php

namespace App\Billing\Repository;

use App\Billing\Entity\InvoiceItem;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

    public function save(InvoiceItem $entity, bool $flush = true): void
    {
        $this->getEntityManager()->persist($entity);
        if ($flush) {
            $this->getEntityManager()->flush();
        }
    }

    /**
     * جزئیات چند آیتم صورتحساب برای نمایش در مطالبات — کلیددار بر اساس id آیتم.
     * @param int[] $ids
     * @return array<int, array{title: string, service_item_id: int|null, quantity: int, total_rials: int, patient_session_id: int|null}>
     */
    public function detailsForIds(array $ids): array
    {
        if ($ids === []) {
            return [];
        }

        $rows = $this->createQueryBuilder('ii')
            ->select('ii.id AS id', 'ii.title AS title', 'ii.serviceItemId AS service_item_id',
                     'ii.quantity AS quantity', 'ii.totalRials AS total_rials',
                     'inv.patientSessionId AS patient_session_id')
            ->join('ii.invoice', 'inv')
            ->where('ii.id IN (:ids)')
            ->setParameter('ids', $ids)
            ->getQuery()
            ->getArrayResult();

        $out = [];
        foreach ($rows as $r) {
            $out[(int) $r['id']] = [
                'title'              => $r['title'],
                'service_item_id'    => $r['service_item_id'] !== null ? (int) $r['service_item_id'] : null,
                'quantity'           => (int) $r['quantity'],
                'total_rials'        => (int) $r['total_rials'],
                'patient_session_id' => $r['patient_session_id'] !== null ? (int) $r['patient_session_id'] : null,
            ];
        }
        return $out;
    }
}
