<?php

namespace Modules\Internal\Transformers;

use Carbon\Carbon;
use Illuminate\Http\Resources\Json\JsonResource;

class LivechatResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request
     * @return array
     */
    public function toArray($request)
    {
        $livechat = [
            'id' => $this->nID,
            'doctor_name' => isset($this->doctor->user->sFirstName) ? $this->doctor->user->sFirstName . ' ' . $this->doctor->user->sLastName : null,
            'speciality' => $this->doctor->speciality->sKeterangan ?? null,
            'health_care' => $this->healthCare->sHealthCare ?? null,
            'date_appointment' => Carbon::parse($this->appointment->appointmentDetail->dTanggalAppointment)->format('d-m-Y')
                . ' ' . $this->appointment->appointmentDetail->tTimeAppointment ?? null,
            'status_appointment' => $this->appointment->status_name ?? null,
            'date_created' => Carbon::parse($this->appointment->dCreateOn)->format('d-m-Y H:i:s') ?? null,
            'patient_media' => $this->sMedia ?? null,
            'doctor_media' => $this->sMediaDokter ?? null,
            'appointment_media' => $this->appointment->sMedia ?? null,
            'status_chat' => $this->status_name ?? null,
            'payment_method' => $this->appointment->payment_method ?? null,
        ];

        $start_time = $this->dStartTime;
        $end_time = $this->dEndTime;
        $data_duration = 0 . ' jam ' . 0 . ' menit ' . 0 . ' detik';
        if ($start_time != null && $end_time != null) {
            $duration = Carbon::parse($start_time)->diffInMinutes(Carbon::parse($end_time));
            $hours = floor($duration / 60);
            $minutes = $duration % 60;
            $seconds = ($duration - ($hours * 60) - $minutes) * 60;

            $data_duration = $hours . ' jam ' . $minutes . ' menit ' . $seconds . ' detik';
        }

        $livechat['duration'] = $data_duration;

        $payment_detail = null;
        if ($this->appointment->appointmentDetail->sPaymentDetails != null) {
            $payment_detail = [
                'payment_type' => $this->appointment->appointmentDetail->sPaymentDetails['payment_type'],
                'transaction_time' => $this->appointment->appointmentDetail->sPaymentDetails['transaction_time'],
                'gross_amount' => $this->appointment->appointmentDetail->sPaymentDetails['gross_amount'],
                'currency' => $this->appointment->appointmentDetail->sPaymentDetails['currency'],
                'status_message' => $this->appointment->appointmentDetail->sPaymentDetails['status_message'],
            ];
        }

        $livechat['payment_detail'] = $payment_detail;
        return $livechat;
    }
}
