<?php

namespace App\Services;

use App\Models\Organization;
use App\Models\Person;
use App\Models\Practitioner;
use App\Models\PractitionerRole;
use App\Models\Speciality;
use Exception;
use Illuminate\Support\Facades\Http;


class DoctorService
{
    public function getData()
    {
        $mapSpecialities = [
            'Akupunktur' => 'SP027',
            'Anak' => 'SP001',
            'Andrologi' => 'SP029',
            'Anastesia' => 'SP015',
            'Bedah Anak' => '',
            'Bedah Digestif' => '',
            'Bedah Mulut' => '',
            'Bedah Onkologi' => '',
            'Bedah Orthopedi' => 'SP007',
            'Bedah Plastik & Rekonstruksi' => 'SP005',
            'Bedah Saraf' => '',
            'Bedah Thorak & Kardiovaskuler' => '',
            'Bedah Umum' => 'SP004',
            'Bedah Vaskuler' => '',
            'Dokter Gigi' => 'SP026',
            'Fisik & Rehabilitasi' => 'SP014',
            'Gastroenterologi Hepatologi' => '',
            'Ginjal Hipertensi' => '',
            'Gizi Klinik' => 'SP019',
            'Hematologi Onkologi' => '',
            'Jantung & Pembuluh Darah' => 'SP008',
            'Kardio Vaskuler' => '',
            'Kebidanan & Kandungan' => 'SP003',
            'Kesehatan Jiwa' => 'SP018',
            'Kulit & Kelamin' => 'SP013',
            'Laboratorium' => '',
            'Mata' => 'SP011',
            'Okupasi' => 'SP016',
            'Paru' => 'SP009',
            'Patologi Klinik' => 'SP021',
            'Penyakit Dalam' => 'SP002',
            'Psikologi' => 'SP042',
            'Radiologi' => 'SP020',
            'Rehabilitasi Medik' => 'SP039',
            'Rheumatologi' => '',
            'Saraf' => 'SP012',
            'THT' => 'SP010',
            'Umum' => 'SP025',
            'Urologi' => 'SP006',
            'Lain-Lain' => '',
        ];

        $organizations = Organization::query()
            ->whereHas('metas', function ($meta) {
                $meta->where('type', 'KodeRS');
            })
            ->with('metas')
            ->get();
        $specialities = Speciality::pluck('id', 'name')->toArray();
        foreach ($organizations as $organization) {

            $hisOrganizationCode =  $organization->meta->KodeRS ?? null;

            if (empty($hisOrganizationCode)) {
                $this->command->warn('NO ORGANIZATION CODE' . $organization->name);
                continue;
            }
            $primayaApiService = new PrimayaApi($hisOrganizationCode);

            $this->command->info('Getting RS ' . $hisOrganizationCode . '-' . $organization->name . ' PractitionerRole');

            try {
                $doctors = $primayaApiService->doctors();
                $this->processDoctors($doctors, $mapSpecialities, $organization,  $specialities);
            } catch (Exception $e) {
                $this->command->warn('Something Went Wrong :' . $hisOrganizationCode . ' - ' . $organization->name . ' - ' . $e->getMessage());
            }
        }
    }



    protected function processDoctors($doctors, $mapSpecialities, $organization, $specialities)
    {
        // foreach ($doctors['data'] as $doctor) {

        // }

        $organizations = Organization::query()
            ->whereHas('metas', function ($meta) {
                $meta->where('type', 'KodeRS');
            })
            ->with('metas')
            ->get();
        $specialities = Speciality::pluck('id', 'name')->toArray();

        foreach ($organizations as $organization) {
            $response = Http::get('https://app.primaya.id/temp/practitioners?code=' . $organization->meta->KodeRS);

            foreach ($response->json()['practitioners'] as $practitioner) {
                $practitioner = json_decode(json_encode($practitioner));

                dd($practitioner);
                if (!empty($practitioner->meta->NIK)) {
                    $newPerson = Person::updateOrCreate([
                        'nik' => $practitioner->meta->NIK
                    ], [
                        'nik' => $practitioner->meta->NIK,
                        'name' => $practitioner->doctor->name,
                        'gender' => $practitioner->doctor->gender,
                        'birth_date' => !empty($practitioner->meta->TanggalLahir) && $practitioner->meta->TanggalLahir != '0000-00-00' ? $practitioner->meta->TanggalLahir :  null,
                    ]);
                } else {
                    $newPerson = Person::create([
                        'name' => $practitioner->doctor->name,
                        'gender' => $practitioner->doctor->gender,
                        'birth_date' => !empty($practitioner->meta->TanggalLahir) && $practitioner->meta->TanggalLahir != '0000-00-00' ? $practitioner->meta->TanggalLahir :  null,
                    ]);
                }
                $newPerson->addresses()->create([
                    'use' => 'both',
                    'type' => 'physical',
                    'text' => $practitioner->doctor->address,
                ]);

                $newPractitioner = Practitioner::updateOrCreate([
                    'person_id' => $newPerson->id
                ], [
                    'person_id' => $newPerson->id
                ]);
                $newPractitioner->metas()->create([
                    'system' => 'default',
                    'type' => 'medical_treatment',
                    'value' => $practitioner->doctor->meta->MedicalTreatment ?? null,
                ]);
                $newPractitioner->metas()->create([
                    'system' => 'default',
                    'type' => 'education',
                    'value' => $practitioner->doctor->meta->Education ?? null,
                ]);
                $newPractitioner->metas()->create([
                    'system' => 'default',
                    'type' => 'award',
                    'value' => $practitioner->doctor->meta->Award ?? null,
                ]);
                $newPractitioner->metas()->create([
                    'system' => 'default',
                    'type' => 'work_experience',
                    'value' => $practitioner->doctor->meta->WorkExperience ?? null,
                ]);
                $newPractitioner->metas()->create([
                    'system' => 'primaya-his',
                    'type' => 'alias',
                    'value' => $practitioner->meta->Sapaan ?? null,
                ]);
                $newPractitioner->metas()->create([
                    'system' => 'primaya-his',
                    'type' => 'Keilmuan',
                    'value' => $practitioner->meta->Keilmuan ?? null,
                ]);
                $newPractitioner->metas()->create([
                    'system' => 'primaya-his',
                    'type' => 'description',
                    'value' => $practitioner->doctor->description ?? null,
                ]);




                $newPractitionerRole = PractitionerRole::create([
                    'practitioner_id' => $newPractitioner->id,
                    'organization_id' => $organization->id,
                    'speciality_id' => $practitioner->speciality ? ($specialities[$practitioner->speciality->name] ?? null) : null,
                    'active' => 1,
                ]);

                if (empty($newPractitionerRole->speciality_id)) {
                    $newPractitionerRole->metas()->updateOrCreate([
                        'type' => 'speciality_code',
                    ], [
                        'system' => 'default',
                        'type' => 'speciality_code',
                        'value' => $practitioner->speciality->code ?? null,
                    ]);

                    $newPractitionerRole->metas()->updateOrCreate([
                        'type' => 'speciality',
                    ], [
                        'system' => 'default',
                        'type' => 'speciality',
                        'value' => $practitioner->speciality->name ?? null,
                    ]);

                    $newPractitionerRole->metas()->updateOrCreate([
                        'type' => 'speciality_image',
                    ], [
                        'system' => 'default',
                        'type' => 'speciality_image',
                        'value' => $practitioner->speciality->name ?? null,
                    ]);
                }

                $newPractitionerRole->metas()->updateOrCreate([
                    'type' => 'primaya-his',
                    'type' => 'DokterID',
                ], [
                    'system' => 'primaya-his',
                    'type' => 'DokterID',
                    'value' => $practitioner->meta->DokterID ?? null,
                ]);
            }
        }
    }
}
