<?php
namespace App\Libraries;

class BridgingBPJS
{
    protected $consID;
    protected $secretKey;
    protected $baseUrl;

    public function __construct()
    {
        $this->consID    = getenv('BPJS_CONS_ID');
        $this->secretKey = getenv('BPJS_SECRET_KEY');
        $this->baseUrl   = getenv('BPJS_BASE_URL'); // Contoh: https://new-api.bpjs-kesehatan.go.id:8080/VClaim-Rest
    }

    public function cekPesertaByNomor($no_kartu)
    {
        $url = $this->baseUrl . "/Peserta/nokartu/{$no_kartu}/tglSEP/" . date('Y-m-d');

        $response = $this->requestBPJS($url);

        return json_decode($response, true);
    }

    private function requestBPJS($url)
    {
        $timestamp = time();
        $signature = base64_encode(hash_hmac('sha256', $this->consID . "&" . $timestamp, $this->secretKey, true));

        $headers = [
            "X-cons-id: {$this->consID}",
            "X-timestamp: {$timestamp}",
            "X-signature: {$signature}",
            "Content-Type: Application/json",
        ];

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            return json_encode(['metaData' => ['code' => '500', 'message' => 'CURL Error: ' . curl_error($ch)]]);
        }
        curl_close($ch);

        return $result;
    }
}
