<?php

namespace Modules\Linksehat\Transformers\Appointment;

use App\Helpers\Helper;
use App\Models\Person;
use App\Models\PractitionerRole;
use Carbon\Carbon;
use Illuminate\Http\Resources\Json\JsonResource;

class AppointmentDetailResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request
     * @return array
     */
    public function toArray($request)
    {
        foreach ($this->appointmentParticipants as $appoinmentParticipant) {
            if ($appoinmentParticipant->participantable_type == Person::class) {
                $patiendId = $appoinmentParticipant->participantable_id;
            } elseif ($appoinmentParticipant->participantable_type == PractitionerRole::class) {
                $doctorId = $appoinmentParticipant->participantable_id;
            }
        }

        $queryPatient = Person::query()
            ->find($patiendId);

        $patient = [
            'id' => $queryPatient->id,
            'name' => $queryPatient->name,
            'email' => $queryPatient->email,
            'phone' => $queryPatient->phone,
        ];

        $queryDoctor = PractitionerRole::query()
            ->with(['practitioner.person', 'speciality', 'practices.prices'])
            ->where('practitioner_id', $doctorId)
            ->first();

        foreach ($queryDoctor->practices as $qPractice) {
            foreach ($qPractice->prices as $qPrice) {
                if (strtolower($qPractice->service_code) == strtolower($this->appointment_type)) {
                    $price = $qPrice->price_net;
                }
            }
        }

        $doctor = [
            'id' => $doctorId,
            'name' => $queryDoctor->person->name,
            'speciality' => 'Spesialis ' . $queryDoctor->speciality->name,
            'length_of_work_year' => rand(1, 10)
        ];

        return [
            'id' => $this->id,
            'date' => Carbon::createFromFormat('Y-m-d H:i:s', $this->start_time)->format('Y-m-d'),
            'time' => Carbon::createFromFormat('Y-m-d H:i:s', $this->start_time)->format('H:i'),
            'doctor' => $doctor,
            'organization' => [
                'id' => $this->organization->id,
                'name' => $this->organization->name,
                'address' => $this->organization->currentAddress->text,
            ],
            'patient' => $patient,
            'price' => Helper::currencyIdrFormat($price)
        ];
    }
}
