<?php
session_start();
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
include "../../inc/config.php";
$url = get_service_url('url_rest');
$token = get_token();
$session_name = $_GET['name'];
$data_ids = $_SESSION[$session_name];
unset($_SESSION[$session_name]);
$total = count($data_ids);

$sukses = 0;
$gagal = 0;
$successCount = 0;
$errorCount = 0;
$messages = [];
$id_reg = array();
$id_reg_quote = array();

foreach ($data_ids as $id) {  
$exp = explode("#", $id);
    $id_mhs[] = $exp[0];
    $id_reg[] = $exp[1];
    $id_reg_quote[] = "'".$exp[1]."'";
}

if (!empty($id_reg)) {
    $implode_id_reg = implode(",", $id_reg_quote);
}

$data_param = [
        'act' => 'GetListMahasiswa',
        'token' => $token,
        'filter' => "id_registrasi_mahasiswa in(".$implode_id_reg.")"
    ];
$data_nim = array();
$check_nim = json_decode($db->run($data_param,$url));
foreach ($check_nim->data as $nim) {
    $where_priode[] = "('".$nim->id_prodi."','".trim($nim->id_periode)."','1')";
    $data_nim[$nim->id_registrasi_mahasiswa] = $nim;
}

$implode_periode = implode(",", $where_priode);
$array_periode_aktif = array();
    $data_param_periode = [
        'act' => 'GetPeriode',
        'token' => $token,
        'filter' => "(id_prodi,periode_pelaporan,tipe_periode) in($implode_periode)"
    ];
    $check_periode_exist = json_decode($db->run($data_param_periode,$url));
    if (!empty($check_periode_exist->data)) {
        foreach ($check_periode_exist->data as $periode) {
            $array_periode_aktif[] = $periode->id_prodi.$periode->periode_pelaporan;
        }
    }

//dump($data_nim);

foreach ($id_reg as $reg_id) {
    //first check if periode aktif
    if (in_array($data_nim[$reg_id]->id_prodi.$data_nim[$reg_id]->id_periode, $array_periode_aktif)) {
        $data_param = [
        'act' => 'DeleteRiwayatPendidikanMahasiswa',
        'token' => $token,
        'key' => array(
                'id_registrasi_mahasiswa' => $reg_id
            )
        ];
    
        $check_nim_exist = json_decode($db->run($data_param,$url));
       echo "data: {\"status\": \"success\", \"message\": \"Berhasil Menghapus NIM ".$data_nim[$reg_id]->nipd." ".$data_nim[$reg_id]->nama_mahasiswa."\"}\n\n";
    } else {
        echo "data: {\"status\": \"error\", \"message\": \"Gagal Hapus NIM ".$data_nim[$reg_id]->nipd." ".$data_nim[$reg_id]->nama_mahasiswa." karena periode tidak aktif\"}\n\n";
    }
}


// Send final completion message
echo "data: {\"status\": \"complete\", \"success\": $successCount, \"error\": $errorCount}\n\n";

// Close the connection
exit();