<?php
session_start();
include "../../inc/config.php";
$json_response = array();
$jumlah = array();
if ($_POST['total_data']>0) {
    $url_rest = get_service_url('rest');

    $offset = $_POST['offset'];
    $token = $_POST['token'];

    $jumlah['offset'] = $offset;
    $jumlah['token'] = $_POST['token'];

    if ($offset==0) {
      $token = get_token();
        $jumlah['token'] = $token;
    }

    $jumlah_sukses = 0;
    $jumlah_error = 0;
    $all_errors = array();
    $msg = "";
    $all_id = array();
    $nim_data = array();
    $data_loop = array();
    $nidn_pembimbing_1 = array();
    $nidn_pembimbing_2 = array();
    $nidn_pembimbing_3 = array();
    $nidn_penguji_1 = array();
    $nidn_penguji_2 = array();
    $nidn_penguji_3 = array();
    $data_nidn_pembimbing_1 = array();
    $data_nidn_pembimbing_2 = array();
    $data_nidn_pembimbing_3 = array();
    $data_nidn_penguji_1 = array();
    $data_nidn_penguji_2 = array();
    $data_nidn_penguji_3 = array();
    $data_pembimbing1_pd = array();
    $data_pembimbing2_pd = array();
    $data_pembimbing3_pd = array();
    $data_penguji1_pd = array();
    $data_penguji2_pd = array();
    $data_penguji3_pd = array();
    $array_mhs = array();
    $array_aktivitas = array();
    $error_code = "";


    if ($_POST['jurusan']!='all') {
      $query_jurusan = "and trim(jurusan.kode_jurusan)='".trim($_POST['jurusan'])."'";
    } else {
       if ($_SESSION['level']!=1) {
        $query_jurusan = "and trim(jurusan.kode_jurusan)='".$_SESSION['jurusan']."'";
        if ($_SESSION['jurusan']=='0') {
                   $query_jurusan = "";
                }
      } else {
        $query_jurusan = "";
      }
    }


     $query_not_in = "and unik_id not in(".$_POST['random_number'].")"; ;

    $data = $db->fetch_custom("select kelulusan.*,id_sms from kelulusan inner join jurusan on kelulusan.kode_jurusan=jurusan.kode_jurusan where kelulusan.id is not null $query_jurusan and status_error!=1 $query_not_in limit 11");

    foreach ($data as $dt_id) {
      //$nim_concat[convert_ascii($dt_id->nim).$dt_id->id_sms] = "('".$dt_id->nim."','".$dt_id->id_sms."')";
      $nim_like[$dt_id->nim] = "nim like '%$dt_id->nim%'";
      $sms_and[$dt_id->id_sms] = "('".$dt_id->id_sms."')";
      $data_loop[] = $dt_id;
    }
 
    //$nim_concat_where = implode(",", $nim_concat);
    //$filter_mhs = "(regexp_replace(trim(nim), '\s', 'g'), id_prodi) in ($nim_concat_where)";
    //$filter_mhs = "(trim(nim), id_prodi) in ($nim_concat_where)";
    $implode_nim_like = implode(" or ",$nim_like);
    $implode_prodi = implode(",",$sms_and);
    $data_req_mhs = [
      'act' => 'GetListMahasiswa',
        'token' => $token,
        //'filter' => $filter_mhs,
        'filter' => "id_registrasi_mahasiswa is not null and ($implode_nim_like) and id_prodi in($implode_prodi)",
        'order' => "",
        'limit' => "",
        'offset' => ""

    ];

    $nim_concat_lulus = array();

    $check_nim_exist = json_decode($db->run($data_req_mhs,$url_rest));

    if (!empty($check_nim_exist->data)) {
      foreach ($check_nim_exist->data as $nim_mhs) {
        $nim_data[convert_ascii($nim_mhs->nim).$nim_mhs->id_prodi] = array(
          'id_registrasi_mahasiswa' => $nim_mhs->id_registrasi_mahasiswa,
          'nama' => $nim_mhs->nama_mahasiswa,
          'nim' => convert_ascii($nim_mhs->nim)
        );
        $nim_concat_lulus[] = "('".$nim_mhs->id_registrasi_mahasiswa."')";
      }
    }


    $nim_data_lulus = array();
   /*   if (!empty($nim_concat_lulus)) {
        $nim_concat_where_lulus = implode(",", $nim_concat_lulus);
          $data_req_mhs_lulus = [
            'act' => 'ExportDataMahasiswaLulus',
              'token' => $token,
              'filter' => "(id_registrasi_mahasiswa) in ($nim_concat_where_lulus)",
              'order' => "",
              'limit' => "",
              'offset' => ""

          ];
          $check_nim_lulus_exist = json_decode($db->run($data_req_mhs_lulus,$url_rest));

          //dump($check_nim_lulus_exist);
          $nim_data_lulus_sinkron = array();

          if (!empty($check_nim_lulus_exist->data)) {
            foreach ($check_nim_lulus_exist->data as $lulus_mhs) {
              if ($lulus_mhs->status_sync=='belum sync') {
                  $nim_data_lulus[convert_ascii($lulus_mhs->nim).$lulus_mhs->id_prodi] = array(
                    'id_registrasi_mahasiswa' => $lulus_mhs->id_registrasi_mahasiswa,
                    'nim' => convert_ascii($lulus_mhs->nim)
                  );
              } else {
                  $nim_data_lulus_sinkron[convert_ascii($lulus_mhs->nim).$lulus_mhs->id_prodi] = array(
                    'id_registrasi_mahasiswa' => $lulus_mhs->id_registrasi_mahasiswa,
                    'nim' => convert_ascii($lulus_mhs->nim)
                  );
              }

            }
          }
      }*/



    $array_id_jns_akt_mhs = array(1,2,3,4);

$array_mhs_insert = array();

//dump($nim_data);

  foreach ($data_loop as $value) {


    $nim = convert_ascii($value->nim);
    $id_sms = $value->id_sms;
    
    if (in_array($nim.$id_sms, array_keys($nim_data))) {
      if ($_POST['jenis_method']=='1') {
/*        if (in_array($nim.$id_sms, array_keys($nim_data_lulus_sinkron))) {
          $error_update_data[] = array(
            'keterangan' => 'Data ini sudah diinputkan dan di sinkronisasi, jadi tidak dapat diubah kembali. Untuk merubahnya bisa dilakukan di website https://pddikti-admin.kemdikbud.go.id',
            'status_error' => 2
          );
          $data_id_error[] = $value->id;
        } else*/
    /*    if (in_array($nim.$id_sms, array_keys($nim_data_lulus))) {
          $error_update_data[] = array(
            'keterangan' => 'Data kelulusan Mahasiswa ini sudah ada di feeder, silakan pilih method Update jika ingin merubah',
            'status_error' => 2
          );
          $data_id_error[] = $value->id;
        } else {*/
          $array_mhs = array(
              'id_registrasi_mahasiswa' => $nim_data[$nim.$id_sms]['id_registrasi_mahasiswa'],
              'id_jenis_keluar' => $value->id_jenis_keluar,
              'tanggal_keluar' => $value->tanggal_keluar,
              'id_periode_keluar' => $value->semester,
              'keterangan' => $value->keterangan_kelulusan,
              'nomor_sk_yudisium' => $value->sk_yudisium,
              'tanggal_sk_yudisium' => $value->tgl_sk_yudisium,
              'ipk' => $value->ipk
          );

         // $data_ids[] = $value->id;

              $data_dic = [
                  'act' => 'InsertMahasiswaLulusDO',
                    'token' => $token,
                    'record' => $array_mhs,
                ];


               // exit();
              $temp_recs = service_request($data_dic);
              /*dump($data_dic);
              dump($temp_recs);*/
              //exit();
              
              //print_r($temp_recs);
                  $value_data = addslashes($temp_recs->error_desc);

                  if ($value_data!='') {
                    $error_update_data[] = array(
                      'keterangan' => $value_data,
                      'status_error' => 2
                    );
                    $data_id_error[] = $value->id;
                  } else {
                    $update_data[] = array(
                      'keterangan' => '',
                      'status_error' => 1
                    );
                    $data_id_sukses[] = $value->id;
                  } 
        //}
      } elseif ($_POST['jenis_method']=='2') {
       // if (in_array($nim.$id_sms, array_keys($nim_data_lulus))) {
            $key['id_registrasi_mahasiswa'] = $nim_data[$nim.$id_sms]['id_registrasi_mahasiswa'];
          $array_mhs = array(
              'id_jenis_keluar' => $value->id_jenis_keluar,
              'tanggal_keluar' => $value->tanggal_keluar,
              'id_periode_keluar' => $value->semester,
              'keterangan' => $value->keterangan_kelulusan,
              'nomor_sk_yudisium' => $value->sk_yudisium,
              'tanggal_sk_yudisium' => $value->tgl_sk_yudisium,
              'ipk' => $value->ipk,
          );

              $data_dic = [
                  'act' => 'UpdateMahasiswaLulusDO',
                  'key' => $key,
                    'token' => $token,
                    'record' => $array_mhs,
                ];


               // exit();
              $temp_recs = service_request($data_dic);
/*              dump($data_dic);
              dump($temp_recs);*/
              //exit();
              
              //print_r($temp_recs);
                  $value_data = addslashes($temp_recs->error_desc);

                  if ($value_data!='') {
                    $error_update_data[] = array(
                      'keterangan' => $value_data,
                      'status_error' => 2
                    );
                    $data_id_error[] = $value->id;
                  } else {
                    $update_data[] = array(
                      'keterangan' => '',
                      'status_error' => 1
                    );
                    $data_id_sukses[] = $value->id;
                  }
        /*} elseif (in_array($nim.$id_sms, array_keys($nim_data_lulus_sinkron))) {
          $error_update_data[] = array(
            'keterangan' => 'Data ini sudah diinputkan dan di sinkronisasi, jadi tidak dapat diubah kembali. Untuk merubahnya bisa dilakukan di website https://pddikti-admin.kemdikbud.go.id',
            'status_error' => 2
          );
          $data_id_error[] = $value->id;
        } else {
          $error_update_data[] = array(
            'keterangan' => 'Data kelulusan Mahasiswa ini belum ada di feeder, silakan pilih method Insert',
            'status_error' => 2
          );
          $data_id_error[] = $value->id;
        }*/
      } else {
         /* if (in_array($nim.$id_sms, array_keys($nim_data_lulus_sinkron))) {
            $error_update_data[] = array(
              'keterangan' => 'Data ini sudah diinputkan dan di sinkronisasi, jadi tidak dapat diubah kembali. Untuk merubahnya bisa dilakukan di website https://pddikti-admin.kemdikbud.go.id',
              'status_error' => 2
            );
            $data_id_error[] = $value->id;
          } else*/
          if (in_array($nim.$id_sms, array_keys($nim_data_lulus))) {
              $error_update_data[] = array(
                'keterangan' => 'Data kelulusan Mahasiswa ini sudah ada di feeder, silakan pilih method Update jika ingin merubah',
                'status_error' => 2
              );
              $data_id_error[] = $value->id;
          }
      }
    } else {
          $error_update_data[] = array(
            'keterangan' => "Nim Mahasiswa ini tidak ditemukan di feeder",
            'status_error' => 2
          );
          $data_id_error[] = $value->id;
    }

    $all_id[] = $value->id;
    $error_code = "";
}


    
    //update error
    if (!empty($error_update_data)) {
      updateMulti('kelulusan',$error_update_data,'id',$data_id_error);
    }
    $error_update_data = array();
    $data_id_error = array();
    //update sukses
    if (!empty($update_data)) {
      updateMulti('kelulusan',$update_data,'id',$data_id_sukses);
    }
    $update_data = array();
    $data_id_sukses = array();

    $implode_id = implode(",", $all_id);
    

    $db->fetch_custom("update kelulusan set unik_id=".$_POST['random_number']." where id in (".$implode_id.")");


  if (isset($_POST['id_data'])) {

    $jml_error_sukses = $db->fetch_custom_single("SELECT COUNT(IF(status_error='1',1,NULL)) AS jml_sukses,COUNT(IF(status_error='2',1,NULL)) AS jml_error FROM kelulusan where unik_id=".$_POST['random_number']);

    $jumlah_sukses = $jml_error_sukses->jml_sukses;
    $jumlah_error = $jml_error_sukses->jml_error;

    $db->fetch_custom("update kelulusan set unik_id=0 where  unik_id=".$_POST['random_number']);

  
    $msg =  "<div class=\"alert alert-warning \" role=\"alert\">
    <font color=\"#3c763d\">".$jumlah_sukses." data Kelulusan berhasil ditambah</font><br />
    <font color=\"#ce4844\" >".$jumlah_error." data tidak bisa ditambahkan </font>";
    
    if (!$jumlah_error==0) {
      $msg .= "<a data-toggle=\"collapse\" href=\"#collapseExample\" aria-expanded=\"false\" aria-controls=\"collapseExample\">Detail error</a>";
      //pesan error 

      $all_errors = array('Silakan lihat detail error di list data');
      
    }
    //echo "<br />Total: ".$i." baris data";
    $msg .= "<div class=\"collapse\" id=\"collapseExample\">";
        $i=1;
        foreach ($all_errors as $pesan) {
            $msg .= "<div class=\"bs-callout bs-callout-danger\">".$i.". ".$pesan."</div><br />";
          $i++;
          }
    $msg .= "</div>
    </div>";


    $jumlah['last_notif'] = $msg;
  }


} else {
  $msg =  "Tidak ada data yang bisa diproses<p>";
    $jumlah['last_notif'] = $msg;
}

array_push($json_response, $jumlah);
echo json_encode($json_response);
//echo convert(memory_get_usage(true)); // 123 kb