<?php

namespace App\Controllers;

use CodeIgniter\API\ResponseTrait;

class Satusehat extends BaseController
{
    use ResponseTrait;

    public function cekNik()
    {
        $nik = $this->request->getPost('nik');

        if (!$nik || strlen($nik) != 16) {
            return $this->failValidationErrors('NIK tidak valid');
        }

        $token = $this->getToken();
        if (!$token) {
            return $this->failServerError('Gagal mengambil token dari SATUSEHAT');
        }

        $client = service('curlrequest');
        $response = $client->get(getenv('SATUSEHAT_FHIR_URL') . '/Patient', [
            'headers' => [
                'Authorization' => 'Bearer ' . $token,
                'Accept'        => 'application/json'
            ],
            'query' => [
                'identifier' => 'https://fhir.kemkes.go.id/id/nik|' . $nik
            ]
        ]);

        $data = json_decode($response->getBody(), true);

        if (!empty($data['entry']) && $data['total'] > 0) {
            return $this->respond([
                'status' => 'found',
                'total' => $data['total'],
                'entry' => $data['entry']
            ]);
        } else {
            return $this->respond([
                'status' => 'not_found',
                'message' => 'Data tidak ditemukan di SATUSEHAT.'
            ]);
        }
    }

    private function getToken()
    {
        $client = service('curlrequest');

        $url = getenv('SATUSEHAT_BASE_URL') . '/accesstoken?grant_type=client_credentials';

        $response = $client->post($url, [
            'form_params' => [
                'client_id'     => getenv('SATUSEHAT_CLIENT_ID'),
                'client_secret' => getenv('SATUSEHAT_CLIENT_SECRET')
            ],
            'headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded'
            ]
        ]);

        $result = json_decode($response->getBody(), true);

        return $result['access_token'] ?? null;
    }
}
