<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use GuzzleHttp\Client;
use App\Models\TestResult;
use App\Pasien;

class SyncLabResults extends Command
{
    // Nama dan deskripsi command
    protected $signature    = 'lab:sync-results';
    protected $description  = 'Sync lab results from external instruments';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        // Instance Guzzle client
        $client = new Client();

        // URL endpoint API dari alat (ganti dengan URL alat kamu)
        $url = 'https://api.examplelab.com/results';

        // Contoh request ke API alat untuk mengambil hasil tes
        try {
            $response = $client->request('GET', $url, [
                'headers' => [
                    'Authorization' => 'Bearer your_api_token', // Jika alat memerlukan token API
                    'Accept'        => 'application/json'
                ]
            ]);

            // Parsing data JSON yang diterima dari API
            $data = json_decode($response->getBody()->getContents(), true);

            // Menyimpan hasil tes ke database
            foreach ($data as $result) {
                // Mencari pasien berdasarkan ID
                $patient = Pasien::find($result['patient_id']);
                if ($patient) {
                    TestResult::create([
                        'patient_id'    => $patient->id,
                        'test_id'       => $result['test_id'],
                        'result_value'  => $result['result_value'],
                        'result_status' => $result['status'],
                        'timestamp'     => $result['timestamp']
                    ]);
                }
            }

            $this->info('Lab results synchronized successfully.');
        } catch (\Exception $e) {
            $this->error('Error syncing lab results: ' . $e->getMessage());
        }
    }
}
