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

case 'download':
  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',
                    'F1',
                    ),
                'border' => array(
                    'style' => 'thin',
                    'color' => '000000'
                    ),
                'verticalAlign' => 'center',
                'horizontalAlign' => 'center',
            ),
                     array(
                'fill' => array(
                    'color' => '00ff00'
                    ),
                'cells' => array(
                    'B1',
                    'C1',
                    'D1',
                    'E1'
                    ),
                'border' => array(
                    'style' => 'thin',
                    'color' => '000000'
                    ),
                'verticalAlign' => 'center',
                'horizontalAlign' => 'center',
                ),
            );


//column width
$col_width = array(
  1 => 20,
  2 => 20,
  3 => 20,
  4 => 20,
  5 => 20,
  6 => 20
  );
$writer->setColWidth($col_width);
$header = array(
  'Nama Substansi'=>'string',
  'SKS Tatap Muka Indeks'=>'string',
  'SKS Praktek' => 'string',
  'SKS Praktek Lapangan' =>'string',
  'SKS Simulai' =>'string',
  'Kode Prodi' =>'string'
);
$data_rec = array();

        $data_json = json_decode(file_get_contents('data.json'));

        foreach ($data_json as $key) {
                      $data_rec[] = array(
                          $key->nama_substansi,
                          $key->sks_tatap_muka,
                          $key->sks_praktek,
                          $key->sks_praktek_lapangan,
                          $key->sks_simulasi,
                          $key->kode_jurusan,
                        );
        }

$comments = array(
'A1' => 'Nama Substansi Kuliah
info : Wajib disi',
'B1' => 'Bobot SKS Tatap Muka
Info : Boleh Kosong',
'C1' => 'Bobot SKS Praktek
Info : Boleh Kosong',
'D1' => 'Bobot SKS Praktek Lapangan
Info : Boleh Kosong',
'E1' => 'Bobot SKS Simulasi
Info : Boleh Kosong',
'F1' => 'Kode Prodi/Jurusan, 
Lihat di menu master data -> jurusan
Wajib diisi'
);
        $writer->setComment($comments);
        $filename = 'template_substansi_matakuliah.xlsx';

        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,'Substansi', $header, $style);
        $writer->writeToStdOut();
        exit(0);
  break;

  case 'delete_error':
    $db->fetch_custom("delete from substansi_kuliah 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 ($status=="" && $jurusan=="") {
       if ($_SESSION['level']==1) {
         $db->fetch_custom("TRUNCATE `substansi_kuliah`");
       } else {
          $db->fetch_custom("delete from substansi_kuliah where kode_jurusan='".$_SESSION['jurusan']."'");
       }
    } else {
      $ids = $db->fetch_custom("select id from substansi_kuliah where id!='' $jurusan $status");
      foreach ($ids as $id) {
        $id_delete[] = $id->id;
      }
        $data_id = implode(",", $id_delete);
       $data_mhs_pt = $db->fetch_custom("delete from substansi_kuliah where id!='' $jurusan $status and id in ($data_id)");
    }

    break;
  case 'import':
   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/skala_nilai/".$_FILES['semester']['name']);
              $semester = array("semester"=>$_FILES["semester"]["name"]);

            }



$error_count = 0;
$error = array();
$sukses = 0;
$values = "";


$array_insert = array();

  $Reader = new SimpleXLSX("../../../upload/skala_nilai/".$_FILES['semester']['name']);
  foreach( $Reader->rows() as $key => $val ) {
      if ($key>0) {
           if ($val[0]!="") {
          $check = $db->check_exist('substansi_kuliah',array(
            'nama_substansi'=>  $db->trimmer($val[0]),
            'kode_jurusan' =>  $db->trimmer($val[5])
          ));
            if ($check==true) {
              $error_count++;
              $error[] = "Nilai ".$val[0]." Sudah Ada";
            } else {
              $sukses++;
            $array_insert[] = array(
              'nama_substansi' => $db->trimmer($val[0]),
              'sks_tatap_muka' => $db->trimmer($val[1]),
              'sks_praktek' => $db->trimmer($val[2]),
              'sks_praktek_lapangan' => $db->trimmer($val[3]),
              'sks_simulasi' => $db->trimmer($val[4]),
              'kode_jurusan' => $db->trimmer($val[5])
            );
              }
      }
    }
  }

if (!empty($array_insert)) {
  $db->insertMulti('substansi_kuliah',$array_insert);
}
unlink("../../../upload/skala_nilai/".$_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 Substansi Kuliah baru 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 "in":
  
  $data = array("nilai_huruf"=>$_POST["nilai_huruf"],"nilai_indeks"=>$_POST["nilai_indeks"],"bobot_nilai_min"=>$_POST["bobot_nilai_min"],"bobot_nilai_maks"=>$_POST["bobot_nilai_maks"],"tgl_mulai_efektif"=>$_POST["tgl_mulai_efektif"],"tgl_akhir_efektif"=>$_POST["tgl_akhir_efektif"],"kode_jurusan"=>$_POST["kode_jurusan"],);
  
  
  
  
   
    $in = $db->insert("skala_nilai",$data);
    
    if ($in=true) {
      echo "good";
    } else {
      return false;
    }
    break;
  case "delete":
    
    
    
    $db->delete("substansi_kuliah","id",$_GET["id"]);
    break;

      case 'del_massal':
    $data_ids = $_REQUEST['data_ids'];
    if(trim($data_ids)!="") {
        $delete =  $db->fetch_custom("delete from substansi_kuliah where id in ($data_ids)");
    }
    break;
  case "up":
  $data = array(
    "nama_substansi"=>$_POST["nama_substansi"],
    "sks_tatap_muka"=>$_POST["sks_tatap_muka"],
    "sks_praktek"=>$_POST["sks_praktek"],
    "sks_praktek_lapangan"=>$_POST["sks_praktek_lapangan"],
    "sks_simulasi"=>$_POST["sks_simulasi"],
    "kode_jurusan"=>$_POST["kode_jurusan"]
  );

    
    $up = $db->update("substansi_kuliah",$data,"id",$_POST["id"]);
    if ($up=true) {
      echo "good";
    } else {
      return false; 
    }
    break;
  default:
    # code...
    break;
}
?>