<?php
	defined('BASEPATH') OR exit('No direct script access allowed');
	
	class Masterdata extends CI_Controller 
	{ 
		public function __construct()
		{
			parent::__construct();
			cek_session_login();
			$this->iduser = $this->session->idu;
			$this->level = $this->session->level;
			$this->load->model('Masterdata_model','masterdata');
		}
		
		public function index()
		{
			// cek_menu_akses();
			$data['title'] = 'Data Akun';
			// $data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
			// $data['profile'] = $this->db->get_where('profile', ['id_profile' => 1])->row_array();
			
			
			$data['masterdata'] = $this->masterdata->getAccountData();
			$this->template->load('main/themes','masterdata/index',$data);
			// $this->load->view('masterdata/index', $data);
			
		}
		
		public function akun()
		{
			cek_menu_akses();
			$data['title'] = 'Data Akun';
			$this->template->load('main/themes','masterdata/view_index',$data);
			
		}
		
		
		public function ajax_akun()
		{
			
			cek_nput_post('GET');
			$page = $this->input->post('page');
			if (!$page) {
				$offset = 0;
				} else {
				$offset = $page;
			}
			
			$limits = $this->input->post('limits');
			
			if (!empty($limits)) {
				$limit = $limits;
				} else {
				$limit = $this->perPage;
			}
			$sortBy = $this->input->post('sortBy');
			if (!empty($sortBy)) {
				$conditions['search']['sortBy'] = $sortBy;
			}
			
			$keywords = $this->input->post('keywords');
			if (!empty($keywords)) {
				$conditions['search']['keywords'] = $keywords;
			}
			
			// $conditions['where'] = array(
			// 'jurnal_detail.id_perkiraan' => 1
			// );
			// Get record count 
			$conditions['returnType'] = 'count';
			$totalRec = $this->masterdata->get_Akun($conditions);
			
			// Pagination configuration 
			$config['target']      = '#data_akun';
			$config['base_url']    = base_url('masterdata/ajax_akun');
			$config['total_rows']  = $totalRec;
			$config['per_page']    = $limit;
			$config['link_func']   = 'search_akun';
			
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config);
			
			// Get records 
			$conditions['start'] = $offset;
			$conditions['limit'] = $limit;
			
			if (!empty($sortBy)) {
				$conditions['search']['sortBy'] = $sortBy;
			}
			
			if (!empty($keywords)) {
				$conditions['search']['keywords'] = $keywords;
			}
			// $conditions['where'] = array(
			// 'jurnal_detail.id_perkiraan' => 1
			// );
			unset($conditions['returnType']);
			$data['masterdata'] = $this->masterdata->get_Akun($conditions);
			// Load the data list view 
			$this->load->view('masterdata/ajax-data', $data, false);
		}
		
		function getData($tglAwal, $tglAkhir, $inArray)
		{
			$this->load->model('Report_model','report');
			
			$array = array('jurnal.tgl >=' => $tglAwal, 'jurnal.tgl <=' => $tglAkhir);
			$this->db->where($array);
			$this->report->set_account_group_id($inArray);
			$journal_data =  $this->report->getData();
			
			$this->masterdata->set_account_group_id($inArray);
			$account_data = $this->masterdata->getAccountData();
			
			// return $result= $account_data;
			$saldo_awal_debit = 0;
			$saldo_awal_kredit = 0;
			if($account_data)
			{
				foreach ($account_data as $row)
				{	
					if($row['id_perkiraan'] == 1){
						$saldo_awal_debit = intval($row['saldo_awal']);
						$result[0][$row['kel_akun']][$row['id_akun']] = array('nama' => $row['nama'], 'saldo_awal' => $saldo_awal_debit, 'saldo' => $saldo_awal_debit, 'kel_akun' => $row['kel_akun'], 'noakun' => $row['noakun']);
						} else {
						$saldo_awal_kredit = (-1)*intval($row['saldo_awal']);
						$result[0][$row['kel_akun']][$row['id_akun']] = array('nama' => $row['nama'], 'saldo_awal' => $saldo_awal_kredit, 'saldo' => $saldo_awal_kredit, 'kel_akun' => $row['kel_akun'], 'noakun' => $row['noakun']);
					}
				}
				
				if($journal_data)
				{
					foreach ($journal_data as $row)
					{
						if(isset($result[0][$row['kel_akun']][$row['id_akun']]))
						{
							if($row['id_perkiraan'] == 1)
							{
								$result[0][$row['kel_akun']][$row['id_akun']]['saldo'] += $row['nilai'];
							}
							else
							{
								$result[0][$row['kel_akun']][$row['id_akun']]['saldo'] -=  $row['nilai'];
							}
						}
					}
				}			
				return $result;
			}
		}
		
		public function add_akun()
		{
			$data['user'] = $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
			
			$data['date'] = date("Y-m-d");
			
			$data['masterdata'] = $this->masterdata->getAccountData();
			$data['accountgroup'] = $this->db->get('kelompok_akun')->result_array();
			$data['perkiraan'] = $this->masterdata->getPerkiraan();
			$this->load->view('masterdata/add_akun',$data);
			
		}
        
		public function simpan_akun()
		{
			// dump($_POST);
			$this->form_validation->set_rules(array(array(
			'field' => 'tipeAkun',
			'label' => 'Kelompok Akun',
			'rules' => 'required|trim',
			'errors' => array(
			'required' => '%s. Harus di pilih',
			)))
			);
			$this->form_validation->set_rules(array(array(
			'field' => 'noAkun',
			'label' => 'Nomor Akun',
			'rules' => 'required|trim|numeric|max_length[10]|regex_match[/^[a-z0-9._]+$/]|is_unique[akun.noakun]',
			'errors' => array(
			'required' => '%s. Harus di isi',
			'numeric' => '%s. Harus angka',
			'max_length' => '%s maksimal 10 digit.',
			'is_unique'     => '%s sudah ada.'
			)
			)));
			$this->form_validation->set_rules(array(array(
			'field' => 'namaAkun',
			'label' => 'Nama Akun',
			'rules' => 'required|trim|max_length[50]|is_unique[akun.nama]',
			'errors' => array(
			'required' => '%s. Harus di isi',
			'max_length' => '%s maksimal 50 digit.',
			'is_unique'     => '%s sudah ada.'
			)
			)));
			
			$this->form_validation->set_rules('perkiraan','Perkiraan', 'required');
			$this->form_validation->set_rules(array(array(
			'field' => 'saldoAwal',
			'label' => 'Saldo Awal',
			'rules' => 'required|trim|max_length[10]',
			'errors' => array(
			'required' => '%s. Harus di isi',
			'max_length' => '%s maksimal 10 digit.',
			)
			)));
			if($this->form_validation->run() == false) {
				$response = [
				'status'=>false,
				'title'=>'Simpan data',
				'msg'   =>validation_errors(),
				];
				}else{
				$saldoAwal1 	= $this->input->post('saldoAwal', true);
				$hide 			= array("Rp", ".", " ");
				$saldoAwal 		= str_replace($hide, "", $saldoAwal1);
				$input = $this->masterdata->insertData($saldoAwal);
				if($input['status']==true)
				{
					$akunBaru = $this->masterdata->getAccountDataById($input['id']);
					$response = [
					'status'=>true,
					'title'=>'Simpan data',
					'msg'   =>'Berhasil',
					'id'    =>$input['id'],
					'kel_akun'=>!empty($akunBaru) ? $akunBaru['kel_akun'] : '',
					'noakun'=>!empty($akunBaru) ? $akunBaru['noakun'] : $this->input->post('noAkun', true),
					'nama'  =>!empty($akunBaru) ? $akunBaru['nama'] : $this->input->post('namaAkun', true),
					'label' =>!empty($akunBaru)
						? $akunBaru['kel_akun'].'-'.$akunBaru['noakun'].' '.$akunBaru['nama']
						: $this->input->post('namaAkun', true),
					];
					}else{
					$response = [
					'status'=>false,
					'title'=>'Simpan data',
					'msg'   =>'Gagal',
					];
				}
				
			}
			$this->output
			->set_status_header(200)
			->set_content_type('application/json', 'utf-8')
			->set_output(json_encode($response, JSON_HEX_APOS | JSON_HEX_QUOT))
			->_display();
			exit();
		}
        
		//tambah data akun
		public function add()
		{
			$data['title'] = 'Tambah Data Akun';
			$data['user'] = $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
			
			$data['date'] = date("Y-m-d");
			
			$data['masterdata'] = $this->masterdata->getAccountData();
			$data['accountgroup'] = $this->db->get('kelompok_akun')->result_array();
			$data['perkiraan'] = $this->masterdata->getPerkiraan();
			
			$this->form_validation->set_rules('tipeAkun','Tipe Akun', 'required');
			$this->form_validation->set_rules(array(array(
			'field' => 'namaAkun',
			'label' => 'Nama Akun',
			'rules' => 'required|trim|max_length[50]|is_unique[akun.nama]',
			'errors' => array(
			'required' => '%s. Harus di isi',
			'max_length' => '%s maksimal 50 digit.',
			'is_unique'     => '%s sudah ada.'
			)
			)));
			$this->form_validation->set_rules(array(array(
			'field' => 'noAkun',
			'label' => 'Nomor Akun',
			'rules' => 'required|trim|numeric|max_length[10]|regex_match[/^[a-z0-9._]+$/]|is_unique[akun.noakun]',
			'errors' => array(
			'required' => '%s. Harus di isi',
			'numeric' => '%s. Harus angka',
			'max_length' => '%s maksimal 10 digit.',
			'is_unique'     => '%s sudah ada.'
			)
			)));
			$this->form_validation->set_rules('perkiraan','Perkiraan', 'required');
			$this->form_validation->set_rules('saldoAwal','Saldo Awal', 'required');
			
			if($this->form_validation->run() == false) {
				$this->template->load('main/themes','masterdata/add_data_akun',$data);
				} else {
				save_demo_redirect('masterdata');
				cek_crud_akses(7);
				// simpan_demo("Simpan");
				$saldoAwal1 	= $this->input->post('saldoAwal', true);
				$hide 			= array("Rp", ".", " ");
				$saldoAwal 		= str_replace($hide, "", $saldoAwal1);
				$this->masterdata->insertData($saldoAwal);
				$this->session->set_flashdata('message_akun','<div class="alert alert-success" role="alert">Akun baru berhasil ditambahkan! 
				<button type="button" class="close" data-dismiss="alert" aria-label="Close">
				<span aria-hidden="true">&times;</span>
				</button></div>');
				redirect('masterdata/akun');
			}
		}
		
		//edit data akun
		public function edit($id)
		{
			
			$data['title'] = 'Edit Data Akun';
			$id = decrypt_url($id);
			
			$cek = $this->masterdata->cek_id($id);
			
			$data['user'] = $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
			$data['masterData'] = $this->masterdata->getAccountDataById($id);
			//kumpulan akun
			$data['kelompok_akun'] = $this->db->get('kelompok_akun')->result_array();
			
			//debit kredit
			$data['perkiraan'] = $this->db->get('perkiraan')->result_array();
			
			$this->form_validation->set_rules('noAkun','Nomor Akun', 'required');
			$this->form_validation->set_rules('namaAkun','Nama Akun', 'required');
			$this->form_validation->set_rules('saldoAwal','Saldo Awal', 'required');
			
			if($this->form_validation->run() == false) {
				if($cek==true)
				{
					$this->template->load('main/themes','masterdata/edit_data_akun',$data);
					}else{
					$data['heading'] = 'Halaman error';				
					$data['message'] = 'Data tidak ditemukan';				
					$this->load->view('errors/html/error_404',$data);
				}
				} else {
				save_demo_redirect('masterdata');
				// simpan_demo("Simpan");
				$saldoAwal1 	= $this->input->post('saldoAwal', true);
				$hide 			= array("Rp", ".", " ");
				$saldoAwal 		= str_replace($hide, "", $saldoAwal1);
				$data['masterData'] = $this->masterdata->getAccountDataById($id);
				$name = $data['masterData']['nama'];
				$this->masterdata->editAccountData($saldoAwal);
				$this->session->set_flashdata('message_akun', '<div class="alert alert-success" role="alert">Akun '. $name .' berhasil di update!
				<button type="button" class="close" data-dismiss="alert" aria-label="Close">
				<span aria-hidden="true">&times;</span>
				</button></div>');
				redirect('masterdata/akun');
			}
		}
		
		//menghapus data akun
		public function delete($id)
		{
			// cek_nput_post('GET');
			save_demo_redirect('masterdata');
			simpan_demo("Hapus");
			
			$this->load->model('Admin_model','admin');
			$data['masterData'] = $this->masterdata->getAccountDataById($id);
			$name = $data['masterData']['nama'];
			// cek apakah akun masih digunakan di db lain
			$pesan = '';
			$akun_sumber = $this->admin->getAllDataById('akun_sumber', 'id_akun', $id); // cash flow
			$jurnal_detail = $this->admin->getAllDataById('jurnal_detail', 'id_akun', $id); // transaksi
			$set_account = $this->admin->getAllDataById('set_account', 'id_akun', $id); // set modal usaha
			$set_account_kas = $this->admin->getAllDataById('set_account_kas', 'id_akun', $id); // set modal usaha
			if(!empty($akun_sumber)){
				$pesan = 'GAGAL! Akun ini masih digunakan pada setting laporan arus kas';
				} else if(!empty($jurnal_detail)){
				$pesan = 'GAGAL! Akun ini masih digunakan pada transaksi';
				} else if(!empty($set_account)){
				$pesan = 'GAGAL! Akun ini masih digunakan pada setting akun';
				}  else if(!empty($set_account_kas)){
				$pesan = 'GAGAL! Akun ini masih digunakan pada setting akun kas';
				} else {
				$this->masterdata->deleteAccountData($id);
				$pesan = 'BERHASIL! Akun berhasil dihapus';
			}
			$this->session->set_flashdata('message_akun', '<div class="alert alert-danger" role="alert">'. $pesan .'
			<button type="button" class="close" data-dismiss="alert" aria-label="Close">
			<span aria-hidden="true">&times;</span>
			</button></div>');
			redirect('masterdata/akun');
		}
		
		//menghapus data akun
		public function hapus_akun()
		{
			// cek_nput_post('GET');
			save_demo_redirect('masterdata/akun');
			simpan_demo("Hapus");
			
			$id 	= $this->input->post('id', true);
			$id = decrypt_url($id);
			
			$this->load->model('Admin_model','admin');
			$data['masterData'] = $this->masterdata->getAccountDataById($id);
			$name = $data['masterData']['nama'];
			// cek apakah akun masih digunakan di db lain
			$pesan = '';
			$akun_sumber = $this->admin->getAllDataById('akun_sumber', 'id_akun', $id); // cash flow
			$jurnal_detail = $this->admin->getAllDataById('jurnal_detail', 'id_akun', $id); // transaksi
			$set_account = $this->admin->getAllDataById('set_account', 'id_akun', $id); // set modal usaha
			$set_account_kas = $this->admin->getAllDataById('set_account_kas', 'id_akun', $id); // set modal usaha
			if(!empty($akun_sumber)){
				$response['status'] = false; 
				$response['msg'] = 'GAGAL! Akun ini masih digunakan pada setting laporan arus kas';
				} else if(!empty($jurnal_detail)){
				$response['status'] = false; 
				$response['msg'] = 'GAGAL! Akun ini masih digunakan pada transaksi';
				} else if(!empty($set_account)){
				$response['status'] = false; 
				$response['msg'] = 'GAGAL! Akun ini masih digunakan pada setting akun';
				}  else if(!empty($set_account_kas)){
				$response['status'] = false; 
				$response['msg'] = 'GAGAL! Akun ini masih digunakan pada setting akun kas';
				} else {
				$this->masterdata->deleteAccountData($id);
				$response['status'] = true; 
				$response['msg'] = 'BERHASIL! Akun berhasil dihapus';
			}
			$this->output
			->set_status_header(200)
			->set_content_type('application/json', 'utf-8')
			->set_output(json_encode($response, JSON_HEX_APOS | JSON_HEX_QUOT))
			->_display();
			exit();
		}
		
		public function account_group()
		{
			$idkelAkun = $this->input->post('idkelAkun',TRUE);
			
			$this->db->select('MAX(akun.noakun) AS no_akun');
			$this->db->where_in('akun.id_kelompok_akun', $idkelAkun);
			$query = $this->masterdata->getAccountData();
			echo json_encode($query);
		}
		public function cetak_akun()
		{
			$this->load->model('Journal_model','journal');
			$data['profile'] = $this->db->get_where('info', ['id' => 1])->row_array();
			
			$data['akun'] =  $this->masterdata->get_Akun();
			 // dump($data['akun']);
			$this->load->library('fpdf');
			$this->load->view('report/pdf/cetak_akun', $data);
		}
		public function sync_journal()
		{
			$this->load->model('Journal_model','journal');
			$where = [
			// 'month(invoice.tgl_trx)'=>month(),
			// 'year(invoice.tgl_trx)'=>year(),
			'lunas'=>1
			];
			
			$data = $this->model_app->view_where('invoice',$where)->result();
			// 
			// dump($data);
			if(!empty($data)){
				$no=0;
				foreach($data AS $row)
				{
					$no++;
					$_data = $this->model_jurnal->cek_bayar_belum_lunas($row->id_invoice)->row();
					
					$no_trans = date("ymd",strtotime($row->tgl_trx)).sprintf("%04s",$no);
					$get_id_transaksi = get_id_transaksi($row->id_invoice)['nomor_order'];
					$nama = cekKonsumen($row->id_konsumen)['nama'];
					
					$catatan =  "ORDER NO#".$get_id_transaksi.' - '.$nama;
					
					$respon = [
					"no_trans" 		=> $no_trans,
					"tgl"	 		=> $row->tgl_trx,
					"keterangan" 	=> $catatan,
					"bukti" 	    => $_data->lampiran,
					"id_user" 		=> $row->id_user
					];
					
					$this->db->insert('jurnal', $respon);
					$jurnal_id 	    = $this->db->insert_id();
					// $jurnal_id 	    = 0;
					if($_data->id_bayar==1){
						// $getIdAkun = getIdAkun($_data->id_bayar);
						$input_jurnal = array(
						'id_jurnal' 		=> $jurnal_id,
						'id_akun'			=> 1,
						'tipe_kas'			=> 1,
						'id_perkiraan'		=> 1, 
						'nilai'				=> $_data->total, 
						'catatan_jurnal'	=> "", 
						);
						$this->db->insert('jurnal_detail', $input_jurnal);
						}else{
						$getIdAkun = getIdAkunBank($_data->id_sub_bayar);
						$input_jurnal = array(
						'id_jurnal' 		=> $jurnal_id,
						'id_akun'			=> $getIdAkun,
						'tipe_kas'			=> 1,
						'id_perkiraan'		=> 1, 
						'nilai'				=> $_data->total, 
						'catatan_jurnal'	=> "", 
						);
						$this->db->insert('jurnal_detail', $input_jurnal);
					}
					
					
					// $this->db->insert_batch('jurnal_detail', $input_jurnal);
					
					$akun_detail =  $this->model_jurnal->akun_detail($row->id_invoice)->result();
					foreach($akun_detail AS $rows)
					{
						$jumlah = $rows->jumlah * $rows->harga;
						$input_jurnal_kredit  = array(
						'id_jurnal' 		=> $jurnal_id,
						'id_akun'			=> $rows->id_akun,
						'tipe_kas'			=> $this->model_jurnal->getIdAkunKasById($rows->id_akun),
						'id_perkiraan'		=> 2, 
						'nilai'				=> $jumlah,
						'catatan_jurnal'	=> $rows->id_invoice, 
						);
						$this->db->insert('jurnal_detail', $input_jurnal_kredit);
					}
					
				}
				
				
				// dump($input_jurnal_kredit);
			}
			
			// $this->db->insert_batch('jurnal', $respon);
			
			
		}
		
		public function sync_journal_belumlunas()
		{
			$this->load->model('Journal_model','journal');
			$where = [
			// 'month(invoice.tgl_trx)'=>month(),
			// 'year(invoice.tgl_trx)'=>year(),
			'pos'=>'Y',
			'lunas'=>0
			];
			$data = $this->model_app->view_where('invoice',$where)->result();
			// dump($data);
			if(!empty($data)){
				$no=0;
				$input_jurnal = [];
				foreach($data AS $row)
				{
					$no++;
					$total =$this->model_jurnal->sum_detail($row->id_invoice);
					$no_trans = date("ymd",strtotime($row->tgl_trx)).sprintf("%04s",$no);
					$get_id_transaksi = get_id_transaksi($row->id_invoice)['nomor_order'];
					$nama = cekKonsumen($row->id_konsumen)['nama'];
					$catatan =  "PIUTANG ORDER NO#".$get_id_transaksi.' - '.$nama;
					$respon = [
					"no_trans" 		=> $no_trans,
					"tgl"	 		=> $row->tgl_trx,
					"keterangan" 	=> $catatan,
					"bukti" 	    => '',
					"id_user" 		=> $row->id_user
					];
					
					$this->db->insert('jurnal', $respon);
					// $jurnal_id 	    = 1;
					$jurnal_id 	    = $this->db->insert_id();
					
					$input_jurnal = array(
					'id_jurnal' 		=> $jurnal_id,
					'id_akun'			=> $this->model_jurnal->get_akun(3),
					'tipe_kas'			=> $this->model_jurnal->getIdAkunKasById(3),
					'id_perkiraan'		=> 1, 
					'nilai'				=> $row->total_bayar, 
					'catatan_jurnal'	=> ""
					);
					$this->db->insert('jurnal_detail', $input_jurnal);
					
					$akun_detail =  $this->model_jurnal->akun_detail($row->id_invoice)->result();
					foreach($akun_detail AS $rows)
					{
						$jumlah = $rows->jumlah * $rows->harga;
						$input_jurnal_kredit  = array(
						'id_jurnal' 		=> $jurnal_id,
						'id_akun'			=> $rows->id_akun,
						'tipe_kas'			=> $this->model_jurnal->getIdAkunKasById($rows->id_akun),
						'id_perkiraan'		=> 2, 
						'nilai'				=> $jumlah,
						'catatan_jurnal'	=> $rows->id_invoice, 
						);
						$this->db->insert('jurnal_detail', $input_jurnal_kredit);
					}
				}
				// dump($input_jurnal);
			}
			
			// $this->db->insert_batch('jurnal', $respon);
			
			
		}
		
		public function sync_kas_keluar()
		{
			$this->load->model('Journal_model','journal');
			
			$data = $this->model_app->views('kas_keluar')->result();
			// dump($data);
			if(!empty($data)){
				$no=0;
				$input_jurnal = [];
				foreach($data AS $row)
				{
					$no++;
					
					$respon = [
					"no_trans" 		=> $row->no_transaksi,
					"tgl"	 		=> $row->tanggal,
					"keterangan" 	=> $row->keterangan,
					"bukti" 	    => '',
					"id_user" 		=> $row->id_user
					];
					
					$this->db->insert('jurnal', $respon);
					// $jurnal_id 	    = 1;
					$jurnal_id 	    = $this->db->insert_id();
					
					$input_jurnal = array(
					'id_jurnal' 		=> $jurnal_id,
					'id_akun'			=> $row->id_akun,
					'tipe_kas'			=> $this->model_jurnal->getIdAkunKasById($row->id_akun),
					'id_perkiraan'		=> 2, 
					'nilai'				=> $row->jumlah, 
					'catatan_jurnal'	=> $row->keterangan
					);
					
					$this->db->insert('jurnal_detail', $input_jurnal);
					
					$akun_detail =  $this->model_jurnal->kas_detail($row->id)->result();
					foreach($akun_detail AS $rows)
					{
						
						$input_jurnal_kredit  = array(
						'id_jurnal' 		=> $jurnal_id,
						'id_akun'			=> $rows->id_akun,
						'tipe_kas'			=> $this->model_jurnal->getIdAkunKasById($rows->id_akun),
						'id_perkiraan'		=> 1, 
						'nilai'				=> $rows->jumlah,
						'catatan_jurnal'	=> $rows->keterangan, 
						);
						$this->db->insert('jurnal_detail', $input_jurnal_kredit);
					}
				}
				// dump($input_jurnal);
			}
			
			// $this->db->insert_batch('jurnal', $respon);
			
			
		}
		
		public function sync_pembelian()
		{
			$this->load->model('Journal_model','journal');
			$this->load->model('Model_kas','kas');
			$this->load->model("model_pembelian",'beli');
			$data = $this->model_app->views('pembelian')->result();
			// dump($data);
			if(!empty($data)){
				$no=0;
				// $input_jurnal = [];
				foreach($data AS $row)
				{
					$no++;
					
					$catatan =  "PEMBELIAN NO#".$row->no_transaksi;
					$respon = [
					"no_trans" 		=> $row->no_transaksi,
					"tgl"	 		=> $row->tgl_pembelian,
					"keterangan" 	=> $catatan,
					"bukti" 	    => '',
					"id_user" 		=> $this->iduser
					];
					
					$this->db->insert('jurnal', $respon);
					$jurnal_id 	    = $this->db->insert_id();
					// $jurnal_id 	    = 1;
					
					$input_jurnal = array(
					'id_jurnal' 		=> $jurnal_id,
					'id_akun'			=> $row->id_akun,
					'tipe_kas'			=> $this->model_jurnal->getIdAkunKasById($row->id_akun),
					'id_perkiraan'		=> 2, 
					'nilai'				=> $row->total_bayar, 
					'catatan_jurnal'	=> $row->keterangan
					);
					
					$this->db->insert('jurnal_detail', $input_jurnal);
					
					$akun_detail =  $this->model_jurnal->pembelian_detail($row->id_pembelian)->result();
					foreach($akun_detail AS $rows)
					{
						$jumlah = $rows->jumlah * $rows->harga;
						$input_jurnal_kredit  = array(
						'id_jurnal' 		=> $jurnal_id,
						'id_akun'			=> $rows->id_akun,
						'tipe_kas'			=> $this->model_jurnal->getIdAkunKasById($rows->id_akun),
						'id_perkiraan'		=> 1, 
						'nilai'				=> $jumlah,
						'catatan_jurnal'	=> $rows->keterangan, 
						);
						$this->db->insert('jurnal_detail', $input_jurnal_kredit);
					}
				}
				// dump($respon);
			}
			
			// $this->db->insert_batch('jurnal', $respon);
			
			
		}
		
		
		// eksport data akun
		public function export_data_akun()
		{
			$this->load->library('phpexcel');
			
			// Panggil class PHPExcel nya
			$excel = new PHPExcel();
			// Settingan awal fil excel
			$excel->getProperties()->setCreator('My Notes Code')
			->setLastModifiedBy('My Notes Code')
			->setTitle("Data Akun Keuangan")
			->setSubject("Data Akun")
			->setDescription("Laporan Data Akun Keuangan Perusahaan")
			->setKeywords("Data Akun");
			
			
			// Buat sebuah variabel untuk menampung pengaturan style dari header tabel
			$style_col = array(
			'font' => array('bold' => true), // Set font nya jadi bold
			'alignment' => array(
			'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, // Set text jadi ditengah secara horizontal (center)
			'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER // Set text jadi di tengah secara vertical (middle)
			),
			'borders' => array(
			'top' => array('style'  => PHPExcel_Style_Border::BORDER_THIN), // Set border top dengan garis tipis
			'right' => array('style'  => PHPExcel_Style_Border::BORDER_THIN),  // Set border right dengan garis tipis
			'bottom' => array('style'  => PHPExcel_Style_Border::BORDER_THIN), // Set border bottom dengan garis tipis
			'left' => array('style'  => PHPExcel_Style_Border::BORDER_THIN) // Set border left dengan garis tipis
			)
			);
			// Buat sebuah variabel untuk menampung pengaturan style dari isi tabel
			$style_row = array(
			'alignment' => array(
			'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER // Set text jadi di tengah secara vertical (middle)
			),
			'borders' => array(
			'top' => array('style'  => PHPExcel_Style_Border::BORDER_THIN), // Set border top dengan garis tipis
			'right' => array('style'  => PHPExcel_Style_Border::BORDER_THIN),  // Set border right dengan garis tipis
			'bottom' => array('style'  => PHPExcel_Style_Border::BORDER_THIN), // Set border bottom dengan garis tipis
			'left' => array('style'  => PHPExcel_Style_Border::BORDER_THIN) // Set border left dengan garis tipis
			)
			);
			
			$excel->setActiveSheetIndex(0)->setCellValue('A1', "Data Akun Keuangan Perusahaan"); // Set kolom A1 dengan tulisan "DATA SISWA"
			$excel->getActiveSheet()->mergeCells('A1:G1'); // Set Merge Cell pada kolom A1 sampai E1
			$excel->getActiveSheet()->getStyle('A1')->getFont()->setBold(TRUE); // Set bold kolom A1
			$excel->getActiveSheet()->getStyle('A1')->getFont()->setSize(15); // Set font size 15 untuk kolom A1
			$excel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); // Set text center untuk kolom A1
			
			// Buat header tabel nya pada baris ke 3
			$excel->setActiveSheetIndex(0)->setCellValue('A3', "#"); 
			$excel->setActiveSheetIndex(0)->setCellValue('B3', "ID Akun"); 
			$excel->setActiveSheetIndex(0)->setCellValue('C3', "Nomor Akun"); 
			$excel->setActiveSheetIndex(0)->setCellValue('D3', "Nama Akun");
			$excel->setActiveSheetIndex(0)->setCellValue('E3', "Saldo Normal Akun"); 
			$excel->setActiveSheetIndex(0)->setCellValue('F3', "Debit"); 
			$excel->setActiveSheetIndex(0)->setCellValue('G3', "Kredit"); 
			
			// Apply style header yang telah kita buat tadi ke masing-masing kolom header
			$excel->getActiveSheet()->getStyle('A3')->applyFromArray($style_col);
			$excel->getActiveSheet()->getStyle('B3')->applyFromArray($style_col);
			$excel->getActiveSheet()->getStyle('C3')->applyFromArray($style_col);
			$excel->getActiveSheet()->getStyle('D3')->applyFromArray($style_col);
			$excel->getActiveSheet()->getStyle('E3')->applyFromArray($style_col);
			$excel->getActiveSheet()->getStyle('F3')->applyFromArray($style_col);
			$excel->getActiveSheet()->getStyle('G3')->applyFromArray($style_col);
			
			// Panggil function view yang ada di SiswaModel untuk menampilkan semua data siswanya
			
			$masterdata = $this->masterdata->getAccountData();
			$no = 1; // Untuk penomoran tabel, di awal set dengan 1
			$numrow = 4; // Set baris pertama untuk isi tabel adalah baris ke 4
			$debit = 0;
			$kredit = 0;
			$tot_debit = 0;
			$tot_kredit = 0;
			foreach($masterdata as $data){ // Lakukan looping pada variabel siswa
				
				$excel->setActiveSheetIndex(0)->setCellValue('A'.$numrow, $no);
				$excel->setActiveSheetIndex(0)->setCellValue('B'.$numrow, $data['id_akun']);
				$excel->setActiveSheetIndex(0)->setCellValue('C'.$numrow, $data['noakun']);
				$excel->setActiveSheetIndex(0)->setCellValue('D'.$numrow, $data['nama']);
				
				// saldo normal akun
				if($data['id_perkiraan'] == 1) {
					$sna = 'DEBIT';
					$debit = $data['saldo_awal'];
					$tot_debit += $debit;
					
					$excel->setActiveSheetIndex(0)->setCellValue('E'.$numrow, $sna);
					$excel->setActiveSheetIndex(0)->setCellValue('F'.$numrow, $debit);
					$excel->setActiveSheetIndex(0)->setCellValue('G'.$numrow, '');
					} else {
					$sna = 'KREDIT';
					$kredit = $data['saldo_awal'];
					$tot_kredit += $kredit;
					
					$excel->setActiveSheetIndex(0)->setCellValue('E'.$numrow, $sna);
					$excel->setActiveSheetIndex(0)->setCellValue('F'.$numrow, '');
					$excel->setActiveSheetIndex(0)->setCellValue('G'.$numrow, $kredit);
				}
				
				
				// Apply style row yang telah kita buat tadi ke masing-masing baris (isi tabel)
				$excel->getActiveSheet()->getStyle('A'.$numrow)->applyFromArray($style_row);
				$excel->getActiveSheet()->getStyle('B'.$numrow)->applyFromArray($style_row);
				$excel->getActiveSheet()->getStyle('C'.$numrow)->applyFromArray($style_row);
				$excel->getActiveSheet()->getStyle('D'.$numrow)->applyFromArray($style_row);
				$excel->getActiveSheet()->getStyle('E'.$numrow)->applyFromArray($style_row);
				$excel->getActiveSheet()->getStyle('F'.$numrow)->applyFromArray($style_row);
				$excel->getActiveSheet()->getStyle('G'.$numrow)->applyFromArray($style_row);
				
				$no++; // Tambah 1 setiap kali looping
				$numrow++; // Tambah 1 setiap kali looping
			}
			
			$excel->setActiveSheetIndex(0)->setCellValue('A'.$numrow, "Jumlah"); // Set kolom A1 dengan tulisan "DATA SISWA"
			$excel->getActiveSheet(0)->mergeCells('A'.$numrow.':E'.$numrow); // Set Merge Cell pada kolom A1 sampai E1
			
			$excel->setActiveSheetIndex(0)->setCellValue('F'.$numrow, $tot_debit);
			$excel->setActiveSheetIndex(0)->setCellValue('G'.$numrow, $tot_kredit);
			
			// Apply style row yang telah kita buat tadi ke masing-masing baris (isi tabel)
			$excel->getActiveSheet()->getStyle('A'.$numrow.':E'.$numrow)->applyFromArray($style_row);
			$excel->getActiveSheet()->getStyle('F'.$numrow)->applyFromArray($style_row);
			$excel->getActiveSheet()->getStyle('G'.$numrow)->applyFromArray($style_row);
			
			
			// Set width kolom
			$excel->getActiveSheet()->getColumnDimension('A')->setWidth(5); // Set width kolom A
			$excel->getActiveSheet()->getColumnDimension('B')->setWidth(15); // Set width kolom B
			$excel->getActiveSheet()->getColumnDimension('C')->setWidth(25); // Set width kolom C
			$excel->getActiveSheet()->getColumnDimension('D')->setWidth(20); // Set width kolom D
			$excel->getActiveSheet()->getColumnDimension('E')->setWidth(20); // Set width kolom E
			$excel->getActiveSheet()->getColumnDimension('F')->setWidth(25); // Set width kolom E
			$excel->getActiveSheet()->getColumnDimension('G')->setWidth(25); // Set width kolom E
			
			// Set height semua kolom menjadi auto (mengikuti height isi dari kolommnya, jadi otomatis)
			$excel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(-1);
			// Set orientasi kertas jadi LANDSCAPE
			$excel->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
			// Set judul file excel nya
			$excel->getActiveSheet(0)->setTitle("Laporan Data ");
			$excel->setActiveSheetIndex(0);
			// Proses file excel
			header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
			header('Content-Disposition: attachment; filename="Data Akun Keuangan Perusahaan.xlsx"'); // Set nama file excel nya
			header('Cache-Control: max-age=0');
			$write = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
			$write->save('php://output');
		}
		
		
		
		// Piutang karyawan
		// public function
	}																																															
