<?php

namespace App\Patient\Entity;

use App\Appointment\Entity\Appointment;
use App\Insurance\Enum\ServiceCategory;
use App\Inventory\Entity\InventoryPackage;
use App\Patient\Repository\PatientSessionRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use App\Shared\Tenant\TenantOwnedTrait;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;

#[ORM\Entity(repositoryClass: PatientSessionRepository::class)]
#[ORM\Table(name: 'patient_sessions')]
#[ORM\Index(columns: ['entity_type', 'entity_id'], name: 'idx_patient_sessions_entity')]
#[ORM\Index(columns: ['created_at'], name: 'idx_patient_sessions_created_at')]
class PatientSession
{
    use TenantOwnedTrait;

    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private ?int $id = null;

    #[ORM\Column(type: 'string', length: 36, unique: true)]
    private string $uuid;

    #[ORM\ManyToOne(targetEntity: PatientRecord::class, inversedBy: 'sessions')]
    #[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
    private PatientRecord $record;

    #[ORM\ManyToOne(targetEntity: Appointment::class)]
    #[ORM\JoinColumn(nullable: true, onDelete: 'SET NULL')]
    private ?Appointment $appointment = null;

    /** زمان پذیرش (unix)؛ اگر ست نشود همان زمان ثبت است */
    #[ORM\Column(name: 'session_at', type: 'integer', nullable: true)]
    private ?int $sessionAt = null;

    /** پکیج مصرفی انتخاب‌شده برای این مراجعه (اختیاری، فقط مرجع) */
    #[ORM\ManyToOne(targetEntity: InventoryPackage::class)]
    #[ORM\JoinColumn(name: 'inventory_package_id', nullable: true, onDelete: 'SET NULL')]
    private ?InventoryPackage $inventoryPackage = null;

    #[ORM\Column(name: 'insurance_base_id', type: 'integer', nullable: true)]
    private ?int $insuranceBaseId = null;

    #[ORM\Column(name: 'insurance_supplementary_id', type: 'integer', nullable: true)]
    private ?int $insuranceSupplementaryId = null;

    /**
     * نوع خدمتِ بیمه‌ایِ این مراجعه (سرپایی/بستری) — مبنای درصد پوششِ ویزیت و
     * snapshotی که فاکتور از آن می‌سازد.
     */
    #[ORM\Column(name: 'insurance_service_category', type: 'string', length: 30, nullable: true, enumType: ServiceCategory::class)]
    private ?ServiceCategory $insuranceServiceCategory = null;

    #[ORM\Column(name: 'visit_price_rials', type: 'integer')]
    private int $visitPriceRials = 0;

    #[ORM\Column(name: 'base_insurance_discount_percent', type: 'decimal', precision: 5, scale: 2)]
    private string $baseInsuranceDiscountPercent = '0.00';

    #[ORM\Column(name: 'supplementary_discount_percent', type: 'decimal', precision: 5, scale: 2)]
    private string $supplementaryDiscountPercent = '0.00';

    #[ORM\Column(name: 'services_total_rials', type: 'integer')]
    private int $servicesTotalRials = 0;

    /**
     * تفکیک بیمه‌ی این مراجعه، محاسبه‌شده توسط PatientService::calculateFinalPrice.
     * پایاست تا صفحه‌ی پرداخت بدون صدور فاکتور هم سهم‌ها را داشته باشد.
     * ثابت: gross = baseInsurance + supplementaryInsurance + patientShare
     */
    #[ORM\Column(name: 'gross_total_rials', type: 'integer', options: ['default' => 0])]
    private int $grossTotalRials = 0;

    #[ORM\Column(name: 'base_insurance_rials', type: 'integer', options: ['default' => 0])]
    private int $baseInsuranceRials = 0;

    #[ORM\Column(name: 'supplementary_insurance_rials', type: 'integer', options: ['default' => 0])]
    private int $supplementaryInsuranceRials = 0;

    #[ORM\Column(name: 'patient_share_rials', type: 'integer', options: ['default' => 0])]
    private int $patientShareRials = 0;

    /** سهم بیمار پیش از تخفیف دستی — همیشه برابر patientShareRials */
    #[ORM\Column(name: 'final_price_rials', type: 'integer')]
    private int $finalPriceRials = 0;

    #[ORM\Column(name: 'payment_method', type: 'string', length: 15)]
    private string $paymentMethod = 'pending';

    /** نوع تخفیف تسویه: percent | fixed | null (بدون تخفیف) */
    #[ORM\Column(name: 'discount_type', type: 'string', length: 10, nullable: true)]
    private ?string $discountType = null;

    /** مقدار خام تخفیف (درصد یا ریال، بسته به نوع) */
    #[ORM\Column(name: 'discount_value', type: 'integer', options: ['default' => 0])]
    private int $discountValue = 0;

    /** مبلغ محاسبه‌شده‌ی تخفیف به ریال (سقف: مبلغ نهایی) */
    #[ORM\Column(name: 'discount_rials', type: 'integer', options: ['default' => 0])]
    private int $discountRials = 0;

    /** منبع تخفیف: id قانون تخفیف اعمال‌شده (audit)؛ null اگر دستی یا بدون تخفیف */
    #[ORM\Column(name: 'applied_discount_rule_id', type: 'integer', nullable: true)]
    private ?int $appliedDiscountRuleId = null;

    /** کشِ نام قانون اعمال‌شده برای نمایش/گزارش بدون join */
    #[ORM\Column(name: 'applied_discount_rule_label', type: 'string', length: 120, nullable: true)]
    private ?string $appliedDiscountRuleLabel = null;

    /** زمان تسویه‌ی کامل (unix)؛ تا قبل از صفر شدن بدهی null است */
    #[ORM\Column(name: 'paid_at', type: 'integer', nullable: true)]
    private ?int $paidAt = null;

    #[ORM\Column(type: 'text', nullable: true)]
    private ?string $notes = null;

    /** آرشیو نرم: مراجعه‌ی اشتباه از لیست پیش‌فرض مخفی می‌شود ولی سابقه حفظ می‌گردد. */
    #[ORM\Column(type: 'boolean', options: ['default' => false])]
    private bool $archived = false;

    #[ORM\Column(name: 'archived_at', type: 'integer', nullable: true)]
    private ?int $archivedAt = null;

    #[ORM\Column(name: 'created_at', type: 'integer')]
    private int $createdAt;

    #[ORM\Column(name: 'updated_at', type: 'integer')]
    private int $updatedAt;

    #[ORM\OneToMany(targetEntity: SessionService::class, mappedBy: 'session', cascade: ['remove'])]
    private Collection $services;

    #[ORM\OneToMany(targetEntity: SessionPayment::class, mappedBy: 'session', cascade: ['remove'])]
    private Collection $payments;

    #[ORM\OneToMany(targetEntity: SessionConsumable::class, mappedBy: 'session', cascade: ['remove'])]
    private Collection $consumables;

    public function __construct(PatientRecord $record, ?Appointment $appointment = null)
    {
        $this->uuid        = Uuid::v4()->toRfc4122();
        $this->record      = $record;
        $this->assignTenantPair($record->getEntityType(), $record->getEntityId());
        $this->appointment = $appointment;
        $this->createdAt   = time();
        $this->updatedAt   = time();
        $this->services    = new ArrayCollection();
        $this->payments    = new ArrayCollection();
        $this->consumables = new ArrayCollection();
    }

    public function getId(): ?int             { return $this->id; }
    public function getUuid(): string         { return $this->uuid; }
    public function getRecord(): PatientRecord { return $this->record; }
    public function getAppointment(): ?Appointment { return $this->appointment; }
    public function getInsuranceBaseId(): ?int { return $this->insuranceBaseId; }
    public function getInsuranceSupplementaryId(): ?int { return $this->insuranceSupplementaryId; }
    public function getInsuranceServiceCategory(): ?ServiceCategory { return $this->insuranceServiceCategory; }
    public function getServices(): Collection { return $this->services; }

    public function addService(SessionService $service): self
    {
        if (!$this->services->contains($service)) {
            $this->services->add($service);
        }
        return $this;
    }
    public function getVisitPriceRials(): int { return $this->visitPriceRials; }
    public function getBaseInsuranceDiscountPercent(): float { return (float) $this->baseInsuranceDiscountPercent; }
    public function getSupplementaryDiscountPercent(): float { return (float) $this->supplementaryDiscountPercent; }
    public function getServicesTotalRials(): int { return $this->servicesTotalRials; }
    public function getGrossTotalRials(): int  { return $this->grossTotalRials; }
    public function getBaseInsuranceRials(): int { return $this->baseInsuranceRials; }
    public function getSupplementaryInsuranceRials(): int { return $this->supplementaryInsuranceRials; }
    public function getPatientShareRials(): int { return $this->patientShareRials; }
    public function getFinalPriceRials(): int  { return $this->finalPriceRials; }
    public function getPaymentMethod(): string { return $this->paymentMethod; }
    public function getDiscountType(): ?string { return $this->discountType; }
    public function getDiscountValue(): int    { return $this->discountValue; }
    public function getDiscountRials(): int    { return $this->discountRials; }
    public function getPaidAt(): ?int          { return $this->paidAt; }
    public function getPayments(): Collection  { return $this->payments; }

    public function addPayment(SessionPayment $payment): self
    {
        if (!$this->payments->contains($payment)) {
            $this->payments->add($payment);
        }
        return $this;
    }

    /** مجموع پرداخت‌های ثبت‌شده روی این مراجعه (ریال) */
    public function getPaidTotalRials(): int
    {
        return array_sum(array_map(
            fn(SessionPayment $p) => $p->getAmountRials(),
            $this->payments->toArray(),
        ));
    }

    /** مبلغ قابل پرداخت بیمار: سهم بیمار پس از کسر تخفیف دستی */
    public function getPayableRials(): int
    {
        return max(0, $this->finalPriceRials - $this->discountRials);
    }

    /** مانده‌ی بدهی پس از کسر تخفیف و پرداخت‌ها؛ هرگز منفی نمی‌شود */
    public function getRemainingRials(): int
    {
        return max(0, $this->getPayableRials() - $this->getPaidTotalRials());
    }

    public function getSessionAt(): ?int       { return $this->sessionAt; }
    public function getInventoryPackage(): ?InventoryPackage { return $this->inventoryPackage; }
    public function getConsumables(): Collection { return $this->consumables; }

    public function addConsumable(SessionConsumable $consumable): self
    {
        if (!$this->consumables->contains($consumable)) {
            $this->consumables->add($consumable);
        }
        return $this;
    }

    /** مجموع قیمت کالاهای مصرفی این مراجعه (ریال) */
    public function getConsumablesTotalRials(): int
    {
        return array_sum(array_map(
            fn(SessionConsumable $c) => $c->getLineTotalRials(),
            $this->consumables->toArray(),
        ));
    }

    public function getNotes(): ?string        { return $this->notes; }
    public function getCreatedAt(): int        { return $this->createdAt; }
    public function getUpdatedAt(): int        { return $this->updatedAt; }

    public function setInsuranceBaseId(?int $id): self                 { $this->insuranceBaseId = $id; $this->updatedAt = time(); return $this; }
    public function setInsuranceSupplementaryId(?int $id): self        { $this->insuranceSupplementaryId = $id; $this->updatedAt = time(); return $this; }
    public function setInsuranceServiceCategory(?ServiceCategory $c): self { $this->insuranceServiceCategory = $c; $this->updatedAt = time(); return $this; }
    public function setVisitPriceRials(int $v): self                   { $this->visitPriceRials = $v; $this->updatedAt = time(); return $this; }
    public function setBaseInsuranceDiscountPercent(float $v): self    { $this->baseInsuranceDiscountPercent = (string) $v; $this->updatedAt = time(); return $this; }
    public function setSupplementaryDiscountPercent(float $v): self    { $this->supplementaryDiscountPercent = (string) $v; $this->updatedAt = time(); return $this; }
    public function setServicesTotalRials(int $v): self                { $this->servicesTotalRials = $v; $this->updatedAt = time(); return $this; }
    public function setFinalPriceRials(int $v): self                   { $this->finalPriceRials = $v; $this->patientShareRials = $v; $this->updatedAt = time(); return $this; }

    /**
     * تفکیک بیمه را یکجا می‌نشاند تا سهم‌ها و مبلغ نهایی نتوانند ناسازگار شوند.
     * مبلغ نهایی همیشه سهم بیمار است؛ تخفیف دستی جدا و بعد از این اعمال می‌شود.
     */
    public function applyShares(int $gross, int $baseInsurance, int $supplementaryInsurance, int $patientShare): self
    {
        $this->grossTotalRials              = $gross;
        $this->baseInsuranceRials           = $baseInsurance;
        $this->supplementaryInsuranceRials  = $supplementaryInsurance;
        $this->patientShareRials            = $patientShare;
        $this->finalPriceRials              = $patientShare;
        $this->updatedAt                    = time();
        return $this;
    }
    public function setPaymentMethod(string $v): self                  { $this->paymentMethod = $v; $this->updatedAt = time(); return $this; }
    public function setDiscount(?string $type, int $value, int $rials, ?int $ruleId = null, ?string $ruleLabel = null): self
    {
        $this->discountType  = $type;
        $this->discountValue = $type === null ? 0 : $value;
        $this->discountRials = $type === null ? 0 : $rials;
        $this->appliedDiscountRuleId    = $type === null ? null : $ruleId;
        $this->appliedDiscountRuleLabel = $type === null ? null : $ruleLabel;
        $this->updatedAt     = time();
        return $this;
    }
    public function getAppliedDiscountRuleId(): ?int    { return $this->appliedDiscountRuleId; }
    public function getAppliedDiscountRuleLabel(): ?string { return $this->appliedDiscountRuleLabel; }
    public function setSessionAt(?int $v): self                        { $this->sessionAt = $v; $this->updatedAt = time(); return $this; }
    public function setInventoryPackage(?InventoryPackage $v): self    { $this->inventoryPackage = $v; $this->updatedAt = time(); return $this; }
    public function setPaidAt(?int $v): self                           { $this->paidAt = $v; $this->updatedAt = time(); return $this; }
    public function setNotes(?string $v): self                         { $this->notes = $v; $this->updatedAt = time(); return $this; }
    public function isArchived(): bool { return $this->archived; }
    public function setArchived(bool $v): self { $this->archived = $v; $this->archivedAt = $v ? time() : null; $this->updatedAt = time(); return $this; }
    public function getArchivedAt(): ?int { return $this->archivedAt; }

    public function toArray(): array
    {
        return [
            'uuid'                               => $this->uuid,
            'record_uuid'                        => $this->record->getUuid(),
            'appointment_uuid'                   => $this->appointment?->getUuid(),
            'doctor_uuid'                        => $this->appointment?->getDoctor()->getUuid(),
            'doctor_name'                        => $this->appointment?->getDoctor()->getName(),
            'insurance_base_id'                  => $this->insuranceBaseId,
            'insurance_supplementary_id'         => $this->insuranceSupplementaryId,
            'insurance_service_category'         => $this->insuranceServiceCategory?->value,
            'insurance_service_category_label'   => $this->insuranceServiceCategory?->label(),
            'visit_price_rials'                  => $this->visitPriceRials,
            'base_insurance_discount_percent'    => (float) $this->baseInsuranceDiscountPercent,
            'supplementary_discount_percent'     => (float) $this->supplementaryDiscountPercent,
            'services_total_rials'               => $this->servicesTotalRials,
            'gross_total_rials'                  => $this->grossTotalRials,
            'base_insurance_rials'               => $this->baseInsuranceRials,
            'supplementary_insurance_rials'      => $this->supplementaryInsuranceRials,
            'patient_share_rials'                => $this->patientShareRials,
            'final_price_rials'                  => $this->finalPriceRials,
            'remaining_rials'                    => $this->getRemainingRials(),
            'payment_method'                     => $this->paymentMethod,
            'is_paid'                            => $this->getRemainingRials() === 0,
            'discount_type'                      => $this->discountType,
            'discount_value'                     => $this->discountValue,
            'discount_rials'                     => $this->discountRials,
            'applied_discount_rule_id'           => $this->appliedDiscountRuleId,
            'applied_discount_rule_label'        => $this->appliedDiscountRuleLabel,
            'paid_at'                            => $this->paidAt,
            'paid_total_rials'                   => $this->getPaidTotalRials(),
            'payments'                           => array_map(
                fn(SessionPayment $p) => $p->toArray(),
                $this->payments->toArray()
            ),
            'services'                           => array_map(
                fn(SessionService $s) => $s->toArray(),
                $this->services->toArray()
            ),
            'session_at'                         => $this->sessionAt,
            'inventory_package_uuid'             => $this->inventoryPackage?->getUuid(),
            'inventory_package_title'            => $this->inventoryPackage?->getTitle(),
            'consumables'                        => array_map(
                fn(SessionConsumable $c) => $c->toArray(),
                $this->consumables->toArray()
            ),
            'consumables_total_rials'            => $this->getConsumablesTotalRials(),
            'notes'                              => $this->notes,
            'archived'                           => $this->archived,
            'archived_at'                        => $this->archivedAt,
            'created_at'                         => $this->createdAt,
            'updated_at'                         => $this->updatedAt,
        ];
    }
}
