<?php
umask(0000);
set_time_limit(0);

$accession_number = trim($_GET["accession_number"]);
if (strlen($accession_number) == 0) die("Accession Error");

$unique_id = md5(microtime() . $accession_number);
//$base_dir = "/dicom_temp/iso_" . $unique_id;
$base_dir = "/tmp/iso_" . $unique_id;
$image_store = $base_dir . "/DICOMDIR";

if (!is_dir($image_store)) mkdir($image_store, 0777, true);

// 1. Download dari PACS
$modalities = ["CR", "CT", "MR", "US", "NM", "PET", "SC", "XA", "XRF", "DX", "MG", "PR", "KO", "SR"];
foreach ($modalities as $cstore) {
    $cmd = "JAVA_HOME=/usr/lib/jvm/jdk1.8.0_144 /usr/local/dcm4che/dcm4che2/bin/dcmqr -L CDRECORD:10104 ABPACS@localhost:11112 -cmove CDRECORD -qAccessionNumber=" . escapeshellarg($accession_number) . " -cstore $cstore -cstoredest " . escapeshellarg($image_store) . " 2>&1";
    exec($cmd);
}

exec("sync");
sleep(2);

// 2. KUNCI: Rename file menggunakan iterator agar tidak 'nyangkut'
$i = 1;
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($image_store, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);

foreach ($iterator as $file) {
    if ($file->isFile()) {
        // Ganti nama file menjadi angka sederhana 1.dcm, 2.dcm agar sistem tidak bingung
        $new_name = $image_store . "/" . $i . ".dcm";
        @rename($file->getRealPath(), $new_name);
        $i++;
    } else {
        // Hapus sub-folder kosong yang dibuat dcmqr
        @rmdir($file->getRealPath());
    }
}

// 3. Copy Viewer
exec("/bin/cp -r /var/www/html/microdicom/* " . escapeshellarg($base_dir) . "/");

// 4. Buat ISO (Sekarang sangat lancar karena nama filenya simpel)
$iso_name = "/dicom_temp/RESULT_" . $accession_number . "_" . $unique_id . ".iso";
$cmd_iso = "/usr/bin/genisoimage -o " . escapeshellarg($iso_name) . " -V DICOM -R -J " . escapeshellarg($base_dir) . " 2>&1";
exec($cmd_iso);

// 5. Kirim ke Browser
if (file_exists($iso_name)) {
    while (ob_get_level()) ob_end_clean();
    header("Content-type: application/octet-stream");
    header('Content-Disposition: attachment; filename="' . $accession_number . '.iso"');
    header('Content-Length: ' . filesize($iso_name));
    readfile($iso_name);

    // 6. CLEANUP (Wajib)
    @unlink($iso_name);
    
    // Gunakan perintah ini untuk menghapus folder sesi ini secara total
    exec("rm -rf " . escapeshellarg($base_dir));

    // OTOMATISASI PEMBERSIH SAMPAH:
    // Menghapus folder iso_... yang gagal hapus di masa lalu dan sudah lebih tua dari 15 menit
    exec("find /dicom_temp/ -maxdepth 1 -name 'iso_*' -type d -mmin +15 -exec rm -rf {} \;");
    
    exit;
}
?>
