<?php
session_start();
$time_start = microtime(true); 
include "../../inc/config.php";
session_check();
require('../../lib/simplexlsx.class.php');

switch ($_GET["act"]) {
case 'down_template':
    require_once '../Writer.php';

$writer = new XLSXWriter();
$style =
        array (
                      array(
              'border' => array(
                'style' => 'thin',
                'color' => '000000'
                ),
            'allfilleddata' => true
            ),
            array(
                'fill' => array(
                    'color' => 'ff0000'
                    ),
                'cells' => array(
                    'A1',
                    'B1',
                    'D1',
                    'E1',
                    'F1',
                    'H1',
                    'J1',
                    ),
                'border' => array(
                    'style' => 'thin',
                    'color' => '000000'
                    ),
                'verticalAlign' => 'center',
                'horizontalAlign' => 'center',
            ),
                        array(
                'fill' => array(
                    'color' => '00ff00'
                    ),
                'cells' => array(
                      'C1',
                      'G1',
                        'I1',
                       'K1'
                    ),
                'border' => array(
                    'style' => 'thin',
                    'color' => '000000'
                    ),
                'verticalAlign' => 'center',
                'horizontalAlign' => 'center',
                )
            );

//column width
$col_width = array(
  1 => 15,
  2 => 43,
  3 => 35,
  4 => 17,
  5 => 15,
  6 => 19,
  7 => 17,
  8 => 17,
  9 => 17,
  10 => 15,
  11 => 39
  );
$writer->setColWidth($col_width);

$header = array(
  'Semester'=>'string',
  'NIDN/NUPTK/ID Dosen NEO'=>'string',
  'Nama Dosen'=>'string',
  'Kode Matakuliah'=>'string',
  'Nama Kelas' => 'string',
  'Rencana Tatap Muka' => 'string',
  'Tatap Muka Real' => 'string',
  'Kode Prodi'=>'string',
  'SKS Ajar' => 'string',
  'Jenis Evaluasi' => 'string',
  'ID Substansi Perkuliahan' => 'string'
);


    $data_rec = array(); 
             $datas = json_decode(file_get_contents('data.json'));
              foreach ($datas as $key) {
                    $data_rec[] = array(
                      $key->semester,
                      $key->nidn,
                      $key->nama_dosen,
                      $key->kode_mk,
                      $key->nama_kelas,
                      $key->rencana_tatap_muka,
                      $key->tatap_muka_real,
                      $key->kode_jurusan,
                      $key->sks_ajar,
                      $key->id_jenis_evaluasi,
                      ''
                    );

              }

            $filename = 'template_dosen_ajar.xlsx';


$comments = array(
'A1' => 'Semester Pelaporan
format : tahun+semester (1 : Ganjil, 2 : Genap, 3 : Pendek)
contoh : 20231 (berarti 2023 ganjil)
info : Wajib disi',
'B1' => 'NIDN / NUPTK/ ID DOSEN NEO
Gunakan NIDN atau NUPTK atau gunakan ID Dosen NEO,
ID Dosen Neo Bisa di download di Menu Tool -> Data Downloader -> Download Data Dosen
info : Wajib disi',
'C1' => 'Nama Dosen
info : Boleh di Kosongkan',
'D1' => 'Kode Matakuliah
Info : Wajib Diisi',
'E1' => 'Nama Kelas Kuliah
Ket : Nama kelas tidak boleh melebihi 5 karakter
Info : Wajib Diisi',
'F1' => 'Tatap Muka:
Jumlah Total Tatap Muka Satu Semester

Info : Wajib Diisi',
'G1' => '
Jumlah Tatap Muka Realisasi.
Jika dikosongkan, Sistem akan menyamakan realisasi dengan jumlah tatap muka

info : Boleh di Kosongkan',
'H1' => 'Lihat di menu master data -> jurusan

Info : Wajib Diisi',
'I1' => 'SKS AJAR:
Jika kosong, sks akan diambil dari matakuliah.

info : Boleh di Kosongkan',
'J1' => 'Jenis Evaluasi
ID Nama Jenis
1: Evaluasi Akademik
2: Aktivitas Partisipatif
3: Hasil Proyek
4: Kognitif/ Pengetahuan

Info : Wajib Diisi',
'K1' => '
ID Substansi Kuliah Neo Bisa di download di Menu Tool -> Data Downloader -> Download Substansi Kuliah
info : Boleh Kosong',
);
$writer->setComment($comments);

    header('Content-disposition: attachment; filename="'.XLSXWriter::sanitize_filename($filename).'"');
    header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    header('Content-Transfer-Encoding: binary');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');



    $writer->writeSheet($data_rec,'Ajar dosen', $header, $style);
    $writer->writeToStdOut();
    exit(0);
    break;
  case 'delete_error':
    $db->fetch_custom("delete from ajar_dosen where status_error=2 and kode_jurusan='".$_POST['id']."'");
    break;
     case 'delete_all':
  
    $status = $_POST['status'];
    if ($status=='all') {
        $status = '';
    } elseif ($status=='0') {
        $status = "and status_error ='0'";
    } elseif ($status=='1') {
        $status = "and status_error ='1'";
    } elseif ($status=='2') {
        $status = "and status_error ='2'";
    }
    if ($_POST['jurusan']=='all') {
        $jurusan = "";
    } else {
        $jurusan = "and kode_jurusan='".$_POST['jurusan']."'";
    }

        if ($_POST['sem']=='all') {
        $semester = "";
    } else {
        $semester = "and semester='".$_POST['sem']."'";
    }
     if ($status=="" && $jurusan=="" && $semester=="") {
        if ($_SESSION['level']==1) {
         $db->fetch_custom("TRUNCATE `ajar_dosen`");
       } else {
          $db->fetch_custom("delete from ajar_dosen where kode_jurusan='".$_SESSION['jurusan']."'");
       }
    } else {
      $ids = $db->fetch_custom("select id from ajar_dosen where id is not null $semester $jurusan $status");
      foreach ($ids as $id) {
        $id_delete[] = $id->id;
      }
        $data_id = implode(",", $id_delete);
       $data_mhs_pt = $db->fetch_custom("delete from ajar_dosen where id is not null $semester $jurusan $status and id in ($data_id)");

    }



    break;
    
  case 'import':
     if (!is_dir("../../../upload/dosen_ajar")) {
              mkdir("../../../upload/dosen_ajar");
            }


   if (!preg_match("/.(xls|xlsx)$/i", $_FILES["semester"]["name"]) ) {

              echo "pastikan file yang anda pilih xls|xlsx";
              exit();

            } else {
              move_uploaded_file($_FILES["semester"]["tmp_name"], "../../../upload/dosen_ajar/".$_FILES['semester']['name']);
              $semester = array("semester"=>$_FILES["semester"]["name"]);

            }



$error_count = 0;
$error = array();
$sukses = 0;
$values = "";
$array_insert = array();
  $Reader = new SimpleXLSX("../../../upload/dosen_ajar/".$_FILES['semester']['name']);
  foreach( $Reader->rows() as $key => $val ) {
    if ($key>0) {
      if ($val[0]!='') {

        if (isset($val[8])) {
          $sks_ajar = $val[8];
        } else {
          $sks_ajar = "";
        } 

         $check = $db->check_exist('ajar_dosen',array(
          'semester'=>$db->trimmer($val[0]),
          'nidn' => $db->trimmer($val[1]), 
          'kode_mk'=> $db->trimmer($val[3]),
          'nama_kelas'=> $db->trimmer($val[4]),
          'kode_jurusan' => $db->trimmer($val[7])
        ));
                  if ($check==true) {
                    $error_count++;
                    $error[] = $val[1]." ".$val[3]." Sudah Ada";
                  } else {
                      $sukses++;
                      $realisasi = $val[6];
                      if ($realisasi=="") {
                        $realisasi = $val[5];
                      } else {
                        $realisasi = $val[6];
                      }
                        $array_insert[] = array(
                          'semester' => $db->trimmer($val[0]),
                          'nidn' => $db->trimmer($val[1]),
                          'nama_dosen' => $db->trimmer($val[2]),
                          'kode_mk' => $db->trimmer($val[3]),
                          'nama_kelas' => $db->trimmer($val[4]),
                          'rencana_tatap_muka' => $db->trimmer($val[5]),
                          'tatap_muka_real' => $realisasi,
                          'kode_jurusan' => $db->trimmer($val[7]),
                          'sks_ajar' => $sks_ajar,
                          'id_jenis_evaluasi' => $db->trimmer($val[9]),
                          'id_substansi' => $db->trimmer($val[10])
                          
                        );

              }
      }

    }

}

if (!empty($array_insert)) {
  $db->insertMulti('ajar_dosen',$array_insert);
  echo $db->getErrorMessage();
}

    unlink("../../../upload/dosen_ajar/".$_FILES['semester']['name']);
        $msg = '';
$time_end = microtime(true);
$execution_time = ($time_end - $time_start);
if (($sukses>0) || ($error_count>0)) {
  $msg =  "<div class=\"alert alert-warning alert-dismissible\" role=\"alert\" >
  <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">�</button>
      <font color=\"#3c763d\">".$sukses." Data Ajar Dosen berhasil di import</font><br />
      <font color=\"#ce4844\" >".$error_count." data tidak bisa ditambahkan </font>";
      if (!$error_count==0) {
        $msg .= "<a data-toggle=\"collapse\" href=\"#collapseExample\" aria-expanded=\"false\" aria-controls=\"collapseExample\">Detail error</a>";
      }
      //echo "<br />Total: ".$i." baris data";
      $msg .= "<div class=\"collapse\" id=\"collapseExample\">";
          $i=1;
          foreach ($error as $pesan) {
              $msg .= "<div class=\"bs-callout bs-callout-danger\">".$i.". ".$pesan."</div><br />";
            $i++;
            }
      $msg .= "</div>
    </div>";
 $msg .= "<p>Total Waktu Import : ". waktu_import($execution_time);
}
  echo $msg;
  
    break;
  case 'del_massal':
   $data_ids = $_REQUEST['data_ids'];
       if(trim($data_ids)!="") {
        $delete =  $db->fetch_custom("delete from ajar_dosen where id in ($data_ids)");
    }
    break;
  case "in":
  
  
  
  $data = array(
    "semester"=>$_POST["semester"],
    "nidn"=>$_POST["nidn"],
    "nama_dosen"=>$_POST["nama_dosen"],
    "kode_mk"=>$_POST["kode_mk"],
    "nama_kelas"=>$_POST["nama_kelas"],
    "rencana_tatap_muka" => $_POST['tatap_muka'],
    "tatap_muka_real" => $_POST['tatap_muka_real'],
    "sks_ajar" => $_POST['sks_ajar'],
    "kode_jurusan" => $_POST['kode_jurusan'],
    "id_jenis_evaluasi" => $_POST['id_jenis_evaluasi']
    );
  
  
  
   
    $in = $db->insert("ajar_dosen",$data);
    
    if ($in=true) {
      echo "good";
    } else {
      return false;
    }
    break;
  case "delete":
    
    
    
    $db->delete("ajar_dosen","id",$_GET["id"]);
    break;
  case "up":
$data = array(
    "semester" => $_POST["semester"],
    "nidn" => $_POST["nidn"],
    "nama_dosen" => $_POST["nama_dosen"],
    "kode_mk" => $_POST["kode_mk"],
    "nama_kelas" => $_POST["nama_kelas"],
    "rencana_tatap_muka" => $_POST['tatap_muka'],
    "tatap_muka_real" => $_POST['tatap_muka_real'],
    "sks_ajar" => $_POST['sks_ajar'],
    "id_jenis_evaluasi" => $_POST['id_jenis_evaluasi'],
    "id_substansi" => $_POST['id_substansi'],
    
    "kode_jurusan" => $_POST['kode_jurusan']
);
    
    $up = $db->update("ajar_dosen",$data,"id",$_POST["id"]);
    if ($up=true) {
      echo "good";
    } else {
      return false; 
    }
    break;
  default:
    # code...
    break;
}

?>