<?php
// Allow CORS (optional, tergantung kebutuhan)
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");

// Hanya izinkan POST
if ($_SERVER['HTTP_HOST'] != 'localhost') {
   if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        $response = 'Not allowed, Private Property';
        $data_response = [
            "log_response" => $response
        ];
        echo json_encode($data_response);
        exit;
    }
}

$input = file_get_contents('php://input');
$parameter_data = json_decode($input);

$organization_id = @$parameter_data->organization_id;
$token = @$parameter_data->token;
$environment = @$parameter_data->environment;



if ($_SERVER['HTTP_HOST'] == 'localhost') {

    $organization_id = '007c79a3-f3e3-4301-b863-5d500d96e9ef';
    $token = '07G00SKdoBX71G4POXWGFHmeOTAo';
    $environment = 'sandbox';
    
    $id_ihs = '';
    $kapan_menjalani_pengobataan = '2025-05-06';
    $waktu_dilakukan = '11:00:00';
    $kapan_dicatat_dan_ditegaskan = '2025-05-06';
    $waktu_dicatat = '11:00:00';
    $id_ihs_pasien = 'P02478375538';
    $nama_pasien = 'Ardianto Putra';
    $id_ihs_dokter = '10009880728';
    $nama_dokter = 'dr. Alexander';
    $id_ihs_encounter = 'bf6ceebe-c3f5-4905-b073-65785cd181cb';

    $id_ihs_medication_request = '8fb1f426-403b-4d3f-b1e4-bc3e0d5c8ced';
    
}


//yang bisa masuk: dentology, bbmc
$arr_org_id = array(
    '05719fdf-2d2a-40af-abf3-8aa32ead653c', //dentology sandbox
    '007c79a3-f3e3-4301-b863-5d500d96e9ef', //bbmc sandbox
    '100471674', //dentology production
    '100019149', //bbmc production
);


if (in_array($organization_id, $arr_org_id) && $token != '') {

    if($id_ihs == 'null'){$id_ihs = null;}
    if($id_ihs_encounter == 'null'){$id_ihs_encounter = null;}

    $linkapi = '';
    if($environment == 'sandbox'){
        $linkapi = 'https://api-satusehat-stg.dto.kemkes.go.id/fhir-r4/v1';
    }else if($environment == 'production'){
        $linkapi = 'https://api-satusehat.kemkes.go.id/fhir-r4/v1';
    }
    
    $token_ihs = $token;
    $tgl_datang = date('Y-m-d ',strtotime($kapan_menjalani_pengobataan))." ".$waktu_dilakukan;
    $format1 = new DateTime($tgl_datang, new DateTimeZone('UTC'));
    $kapan_menjalani_pengobataan = $format1->format('Y-m-d\TH:i:sP');
    
    $tgl_hasil = date('Y-m-d ',strtotime($kapan_dicatat_dan_ditegaskan))." ".$waktu_dicatat;
    $format2 = new DateTime($tgl_hasil, new DateTimeZone('UTC'));
    $kapan_dicatat_dan_ditegaskan = $format2->format('Y-m-d\TH:i:sP');

    $id_text = '';
    $id_put = '';
    $tipe = 'Uploaded';
    $method = 'POST';
    if($id_ihs != null){
        $id_text = '"id" : "'.$id_ihs.'",';
        $tipe = 'Updated';
        $id_put = "/$id_ihs";
        $method = 'PUT';
    }
    
    $curl = curl_init();
    $organisasi_id = $organization_id;
    $curl_data = '
    {
        "resourceType": "MedicationStatement",
        "status": "active",
        "category": {
            "coding": [
                {
                    "system": "http://terminology.hl7.org/CodeSystem/medication-statement-category",
                    "code": "outpatient",
                    "display": "Outpatient"
                }
            ]
        },
        "medicationReference": {
            "reference": "Medication/'.$id_ihs_medication_request.'"
        },
        "subject": {
            "reference": "Patient/'.$id_ihs_pasien.'",
            "display": "'.$nama_pasien.'"
        },
        "dosage": [
            {
                "text": "1 kapsul setiap 8 jam untuk 7 hari",
                "timing": {
                    "repeat": {
                        "frequency": 1,
                        "period": 8,
                        "periodUnit": "h"
                    }
                }
            }
        ],
        "effectiveDateTime": "'.$kapan_menjalani_pengobataan.'",
        "dateAsserted": "'.$kapan_dicatat_dan_ditegaskan.'",
        "informationSource": {
            "reference": "Patient/'.$id_ihs_pasien.'",
            "display": "'.$nama_pasien.'"
        },
        "context": {
            "reference": "Encounter/'.$id_ihs_encounter.'"
        }
    }';
    

    curl_setopt_array($curl, array(
      CURLOPT_URL => $linkapi.'/MedicationStatement'.$id_put,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => $method,
      CURLOPT_POSTFIELDS => $curl_data,
      CURLOPT_HTTPHEADER => array(
        'Content-Type: application/json',
        'Authorization: Bearer '.$token_ihs
      ),
    ));

    $response = curl_exec($curl);
    $data = json_decode($response, true);
    curl_close($curl);


    if ($_SERVER['HTTP_HOST'] == 'localhost') {
        $response = json_decode($response);
    }

    $data_response = [
        "log_response" => $response,
        "id_ihs_riwayat_pengobatan" => @$data['id']
    ];
    echo json_encode($data_response);


} else {
    http_response_code(401); 
    $response = 'Invalid client credentials';
    $data_response = [
        "log_response" => $response
    ];
    echo json_encode($data_response);
}
?>