<?php

include_once('class/database.php');

$db = new Database("localhost","root","12Digit","pacsdb_his",3306);
$dbhis = new Database("192.168.2.7","remote","12Digit","rsabt201107",3306);

$list_accession_number = trim($_GET["accession_number"]);
$as = explode(",",$list_accession_number);

$list_accession_number = implode("-",$as);

$first_accession_number = $as[0];

$sql = "SELECT MEDRECID,RegID FROM pacs_result_series WHERE AccessionNumber = '$first_accession_number' LIMIT 1";
$result = $dbhis->query($sql);
if($dbhis->getRowsNum($result)>0) {
   list($MEDRECID,$RegID)=$dbhis->fetchRow($result);
   $sql = "SELECT Nama FROM medrec WHERE MEDRECID = '$MEDRECID'";
   $result = $dbhis->query($sql);
   if($dbhis->getRowsNum($result)>0) {
      list($NamaPasien)=$dbhis->fetchRow($result);
   } else {
      echo "Accession Number Error";
      exit(0);
   }
} else {
   echo "Accession Number Error";
   exit(0);
}

$dicomdir = "/tmp/".uniqid("dicomdir_");

if(strlen($list_accession_number)==0) {
   echo "Accession Number Error";
   exit(0);
}

// $accession_number = "MR.180505.026";

$filename_pasien = preg_replace( '/[^a-zA-Z0-9]+/', '', strtoupper($NamaPasien) );
$filename = $filename_pasien."-".preg_replace( '/[^a-zA-Z0-9\-\.]+/', '', strtoupper($list_accession_number) );

header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="'.$filename.'.iso"');

mkdir($dicomdir);
mkdir("$dicomdir/DICOMDIR");

$cmd = "/bin/cp -r /var/www/html/microdicom/* ${dicomdir}/";
exec($cmd, $outputRes);


/*
    CR  - Computed Radiography Image Storage
    CT  - CT Image Storage
    MR  - MRImageStorage
    US  - Ultrasound Image Storage
    NM  - Nuclear Medicine Image Storage
    PET - PET Image Storage
    SC  - Secondary Capture Image Storage
    XA  - XRay Angiographic Image Storage
    XRF - XRay Radiofluoroscopic Image Storage
    DX  - Digital X-Ray Image Storage for Presentation
    MG  - Digital Mammography X-Ray Image Storage for Presentation
    PR  - Grayscale Softcopy Presentation State Storage
    KO  - Key Object Selection Document Storage
    SR  - Basic Text Structured Report Document Storage
*/

$modalities["CR"] = 1;
$modalities["CT"] = 1;
$modalities["MR"] = 1;
$modalities["US"] = 1;
$modalities["NM"] = 1;
$modalities["PET"] = 1;
$modalities["SC"] = 1;
$modalities["XA"] = 1;
$modalities["XRF"] = 1;
$modalities["DX"] = 1;
$modalities["MG"] = 1;
$modalities["PR"] = 1;
$modalities["KO"] = 1;
$modalities["SR"] = 1;



foreach($modalities as $cstore=>$v) {
   foreach($as as $accession_number) {
      $cmd = "JAVA_HOME=/usr/lib/jvm/jdk1.8.0_144 LANG=en_US.iso-8859-1 /usr/local/dcm4che/dcm4che2/bin/dcmqr -L CDRECORD:10104 ABPACS@localhost:11112 -cmove CDRECORD -qAccessionNumber=${accession_number} -cstore $cstore -cstoredest $dicomdir/DICOMDIR";
      exec($cmd, $outputRes);
   }
}

$cmd = "/usr/bin/dcmsend +sd +rd 172.16.0.120 104 $dicomdir/DICOMDIR";
exec($cmd, $outputRes);

