<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Uplbahanbaku extends MY_Controller {
	
	function __construct()
	{
		parent::__construct();
		$this->modul = 'uplbahanbaku';
		$this->title = 'UPLOAD DATA BAHAN BAKU';
		$this->kd_cmpy=$this->session->userdata('kd_cmpy');
	}
	
	public function index()
	{
		$data = array(
			'content' 	=> 	$this->modul.'/index'
		);
		$this->load('tpl',$data['content'], $data);
		$this->load->view($this->modul.'/_cjs');
	}
	
	public function run_upload(){
		$file   = explode('.',$_FILES['h']['name']);
		$length = count($file);
		if($file[$length -1] == 'xlsx' || $file[$length -1] == 'xls'){//jagain barangkali uploadnya selain file excel <span class="wp-smiley wp-emoji wp-emoji-smile" title=":-)">:-)</span>
			$tmp    = $_FILES['h']['tmp_name'];//Baca dari tmp folder jadi file ga perlu jadi sampah di server :-p
			$this->load->library('excel');//Load library excelnya
			$read   = PHPExcel_IOFactory::createReaderForFile($tmp);
			$read->setReadDataOnly(true);
			$excel  = $read->load($tmp);
			$_sheet = $excel->setActiveSheetIndex(0);//Kunci sheetnye biar kagak lepas :-p
			$maxRow = $_sheet->getHighestRow();
			// nilai awal counter untuk jumlah data yang sukses dan yang gagal diimport
			$sukses = 0;
			$gagal = 0;
			$child_no = 1;
			$kd_cmpy = $this->kd_cmpy;
			for($i = 5; $i <= $maxRow; $i++){
				$child_no = $_sheet->getCell('A'.$i)->getCalculatedValue();
				$kd_id = trim($_sheet->getCell('B'.$i)->getCalculatedValue());
				$tpbarang = trim($_sheet->getCell('C'.$i)->getCalculatedValue());
				$matgroup = trim($_sheet->getCell('D'.$i)->getCalculatedValue());
				$partno = $_sheet->getCell('E'.$i)->getCalculatedValue();
				$NmBarang = $_sheet->getCell('F'.$i)->getCalculatedValue();
				$Sat = $_sheet->getCell('G'.$i)->getCalculatedValue();
				$cust = $_sheet->getCell('H'.$i)->getCalculatedValue();
				$UNIX_DATE = ($excel_bahanbaku_date - 25569) * 86400;
				$q01="SELECT KdBarang
					FROM mst_barang  
					LIMIT 1 ";
				$row=$this->db->query($q01)->row();
				
				// setelah data dibaca, sisipkan ke dalam tabel
				if ($partno_tmp != $partno) {
					$q= "DELETE FROM mst_barang WHERE PartNo = '$partno'";
					$this->db->query($q);
					$q= "INSERT INTO mst_barang (
						KdBarang,TpBarang,MatGroup,PartNo,NmBarang,Sat,cust
					) VALUES (
						'$kd_id','$tpbarang','$matgroup','$partno','$NmBarang','$Sat','$cust'
					)";
					// die($q);
					$this->db->query($q);
					$kd_id=$this->db->insert_id();
					$partno_tmp=$partno;
					$child_no=1;
				}
			}
			// tampilan status sukses dan gagal
			echo "<h3>Proses upload data selesai.</h3>";
			//echo "<p>Jumlah data yang sukses di upload : ".$sukses."<br>";
			//echo "Jumlah data yang gagal di upload : ".$gagal."</p>";
		}else{
			echo 'do not allowed to upload';//pesan error tipe file tidak tepat
		}
	}
	
}
