<?php

namespace Database\Seeders;

use App\Models\Address;
use App\Models\Organization;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Http;

class OrganizationSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {

        $response = Http::get('https://app.primaya.id/temp/organizations');

        foreach ($response->json()['organizations'] as $organization) {
            $newOrganization = Organization::updateOrCreate([
                'code' => 'ORG000' . $organization['code'],
            ], [
                'code' => 'ORG000' . $organization['code'],
                'name' => $organization['name'],
                'type' => 'hospital',
            ]);

            $newAddress = $newOrganization->addresses()->updateOrCreate([
                'id' => $newOrganization->main_address_id
            ], [
                'use' => 'both',
                'type' => 'physical',
                'text' => $organization['address'],
                'lat' => $organization['lat'],
                'lng' => $organization['lng'],
            ]);

            $newOrganization->main_address_id = $newAddress->id;
            $newOrganization->save();

            $newOrganization->metas()->updateOrCreate([
                'type' => 'KodeRS',
            ], [
                'system' => 'primaya-his',
                'type' => 'KodeRS',
                'value' => $organization['code']
            ]);
            $newOrganization->metas()->updateOrCreate([
                'type' => 'phone',
            ], [
                'system' => 'default',
                'type' => 'phone',
                'value' => $organization['phone']
            ]);
            $newOrganization->metas()->updateOrCreate([
                'type' => 'timezone',
            ], [
                'system' => 'default',
                'type' => 'timezone',
                'value' => $organization['timezone']
            ]);
        }
    }
}
