<?php

namespace App\Patient\Entity;

use App\Appointment\Entity\Appointment;
use App\Patient\Repository\PatientSessionRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;

#[ORM\Entity(repositoryClass: PatientSessionRepository::class)]
#[ORM\Table(name: 'patient_sessions')]
#[ORM\Index(columns: ['created_at'], name: 'idx_patient_sessions_created_at')]
class PatientSession
{
    #[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;

    #[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;

    #[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;

    #[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';

    #[ORM\Column(type: 'text', nullable: true)]
    private ?string $notes = 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;

    public function __construct(PatientRecord $record, ?Appointment $appointment = null)
    {
        $this->uuid        = Uuid::v4()->toRfc4122();
        $this->record      = $record;
        $this->appointment = $appointment;
        $this->createdAt   = time();
        $this->updatedAt   = time();
        $this->services    = 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 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 getFinalPriceRials(): int  { return $this->finalPriceRials; }
    public function getPaymentMethod(): string { return $this->paymentMethod; }
    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 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->updatedAt = time(); return $this; }
    public function setPaymentMethod(string $v): self                  { $this->paymentMethod = $v; $this->updatedAt = time(); return $this; }
    public function setNotes(?string $v): self                         { $this->notes = $v; $this->updatedAt = time(); return $this; }

    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,
            'visit_price_rials'                  => $this->visitPriceRials,
            'base_insurance_discount_percent'    => (float) $this->baseInsuranceDiscountPercent,
            'supplementary_discount_percent'     => (float) $this->supplementaryDiscountPercent,
            'services_total_rials'               => $this->servicesTotalRials,
            'final_price_rials'                  => $this->finalPriceRials,
            'payment_method'                     => $this->paymentMethod,
            'is_paid'                            => $this->paymentMethod !== 'pending',
            'services'                           => array_map(
                fn(SessionService $s) => $s->toArray(),
                $this->services->toArray()
            ),
            'notes'                              => $this->notes,
            'created_at'                         => $this->createdAt,
            'updated_at'                         => $this->updatedAt,
        ];
    }
}
