<?php
    defined("BASEPATH") or exit("No direct script access allowed");
    
    class Pembelian extends CI_Controller
    {
        public function __construct()
        {
            parent::__construct();
            
            cek_session_login();
            $this->load->model("model_pembelian",'beli');
            $this->load->model('Model_kas','kas');
			$this->load->model('Masterdata_model','masterdata');
			$this->load->model('Journal_model','journal');
            $this->load->model('Report_model','report');
            $this->load->model('Pembelian_stok_model','pembelian_stok');
            $this->title = info()["title"];
            $this->iduser = $this->session->idu;
            $this->level = strtolower((string) $this->session->level);
            $this->perPage = 10;
		}
        
        public function data()
        {
            cek_menu_akses();
            $format = "%Y-%m-%d";
            $harian = mdate($format);
            $data["title"] = "Faktur Pembelian | " . $this->title;
            $tgl_awal = date("01/m/Y", strtotime($harian));
            $data["tgl_awal"] = $tgl_awal;
            $data["tgl"] = date("d/m/Y");
            $data['dari'] = date('01/m/Y', strtotime(today()));
			$data['sampai'] = date('t/m/Y', strtotime(today()));
			
            $data["pilihan"] = $this->model_app->view("tb_users");
            $data['sinkron_stok_aktif'] = $this->pembelian_stok->is_enabled();
            $data['boleh_acc_stok'] = $this->boleh_acc_stok();
            $this->template->load("main/themes", "pembelian/pembelian", $data);
		}
        /**
            * ajaxPembelian
            *
            * @return void
		*/
        function ajaxPembelian(){
            // cek_session_login(); 
            $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; 
			} 
            // $conditions['where'] = array('pos' => 'Y');
            $sortBy = $this->input->post('sortBy'); 
            $user = $this->input->post('user'); 
            $keywords = $this->input->post("keywords");
            // if(!empty($_POST['dari'])){
			// $dari = date_slash($_POST['dari']);
			// $conditions['search']['dari'] = $dari; 
			// }
            // if(!empty($_POST['sampai'])){ 
			// $sampai = date_slash($_POST['sampai']);
			// $conditions['search']['sampai'] = $sampai; 
			// }
            
			$tgl = $this->input->post('tgl');
			if (!empty($tgl)) {
				$date = date_ranges($tgl);
				$dari = date_replace_slash($date['dari']);
				$sampai = date_replace_slash($date['sampai']);
				$conditions["search"]["dari"] = $dari;
				$conditions["search"]["sampai"] = $sampai;
				
			}
			
            if(!empty($sortBy)){ 
                $conditions['search']['sortBy'] = $sortBy; 
			} 
            
            if(!empty($user)){ 
                $conditions['where'] = array(
                'pembelian.id_user' =>$user
                );	
			} 
				$data["search"] = '';
            if (!empty($keywords)) {
				$conditions["search"]["keywords"] = $keywords;
				$data["search"] = $keywords;
			}
            // Get record count 
            $conditions['returnType'] = 'count'; 
			if (!empty($keywords)) {
				$totalRec = $this->beli->getPembelianCari($conditions); 
				}else{
				$totalRec = $this->beli->getPembelian($conditions); 
			}
            
            // Pagination configuration 
            $config['target']      = '#dataListpembelian'; 
            $config['base_url']    = base_url('pembelian/ajaxPembelian'); 
            $config['total_rows']  = $totalRec; 
            $config['per_page']    = $limit; 
            $config['link_func']   = 'FilterPembelian'; 
            
            // Initialize pagination library 
            $this->ajax_pagination->initialize($config); 
            
            // Get records 
            $conditions['start'] = $offset; 
            $conditions['limit'] = $limit;
            
            
            unset($conditions['returnType']); 
			if (!empty($keywords)) {
				$data['result'] = $this->beli->getPembelianCari($conditions); 
				}else{
				$data['result'] = $this->beli->getPembelian($conditions); 
			}
            $purchaseIds = array();
            if (!empty($data['result'])) {
                foreach ($data['result'] as $purchase) $purchaseIds[] = (int) $purchase['id_pembelian'];
            }
            $data['stok_sync_summaries'] = $this->pembelian_stok->summaries($purchaseIds);
            $data['sinkron_stok_aktif'] = $this->pembelian_stok->is_enabled();
            $data['boleh_acc_stok'] = $this->boleh_acc_stok();
            
            // Load the data list view 
            $this->load->view('pembelian/ajax-pembelian', $data); 
		}     
		
		public function simpan_pembelian()
{
	$jenis_bayar          = xss_filter($this->input->post("jenis_bayar"), 'xss');
	$no_trans             = xss_filter($this->input->post("no_trans"), 'xss');
	$dari_kas             = xss_filter($this->input->post("dari_kas"), 'xss');
	$saldo_kas            = xss_filter($this->input->post("saldo_kas"), 'xss');
	$tanggal_beli         = xss_filter($this->input->post("tanggal_beli"), 'xss');
	$tanggal_beli         = date_replace_slash($tanggal_beli);
	$keterangan_kas       = xss_filter($this->input->post("keterangan_kas"), 'xss');
	$jumlah_kas           = xss_filter($this->input->post("jumlah_kas"), 'xss');
	$getIdAkunKasById     = $this->kas->getIdAkunKasById($dari_kas);
	$idAkun 	          = $this->input->post('idAkun', true);
	$supplier             = $this->input->post('supplier', true);
	$keterangan           = $this->input->post('keterangan', true);
	$jumlah 	          = $this->input->post('jumlah', true);
	$harga 		          = $this->input->post('harga', true);

	$idAkun     = is_array($idAkun) ? $idAkun : [];
	$supplier   = is_array($supplier) ? $supplier : [];
	$keterangan = is_array($keterangan) ? $keterangan : [];
	$jumlah     = is_array($jumlah) ? $jumlah : [];
	$harga      = is_array($harga) ? $harga : [];

	$nominal_jumlah = [];
	$nominal_harga = [];
	$total_pembelian = 0;
	foreach ($harga as $key => $value) {
		$nominal_jumlah[$key] = isset($jumlah[$key]) ? convert_to_number($jumlah[$key]) : 0;
		$nominal_harga[$key] = convert_to_number($value);
		$total_pembelian += $nominal_jumlah[$key] * $nominal_harga[$key];
	}

	if ($total_pembelian <= 0) {
		$total_pembelian = convert_to_number($jumlah_kas);
	}

	// =========================
	// Upload bukti nota (opsional)
	// name="bukti_nota" (JPG/PNG/PDF)
	// =========================
	$bukti_nota_file = null;
	$bukti_jurnal_file = '';
	if (!empty($_FILES['bukti_nota']['name'])) {
		$upload_dir = FCPATH . 'uploads/bukti_pembelian/';
		if (!is_dir($upload_dir)) {
			@mkdir($upload_dir, 0755, true);
		}

		$this->load->library('upload');

		$no_trans_safe = preg_replace('/[^A-Za-z0-9_\-]/', '_', (string) $no_trans);
		$config = [
			'upload_path'   => $upload_dir,
			'allowed_types' => 'jpg|jpeg|png|webp|pdf',
			'max_size'      => 6120, // 6MB
			'file_name'     => 'nota_' . $no_trans_safe . '_' . time(),
			'overwrite'     => false,
		];

		$this->upload->initialize($config);

		if (!$this->upload->do_upload('bukti_nota')) {
			$response = [
				'status' => false,
				'msg'    => trim($this->upload->display_errors('', '')),
			];
			$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();
		}

		$up = $this->upload->data();
		$finalUpload = bm_finalize_ci_upload_as_webp($up, 80);
		if (!$finalUpload['status']) {
			$response = [
				'status' => false,
				'msg'    => $finalUpload['message'],
			];
			$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();
		}

		$bukti_nota_file = $finalUpload['file_name'];

		// Sinkronkan juga ke folder lampiran jurnal umum.
		$jurnal_upload_dir = FCPATH . 'uploads/lampiran/';
		if (!is_dir($jurnal_upload_dir)) {
			@mkdir($jurnal_upload_dir, 0755, true);
		}

		$source_file = rtrim($upload_dir, '/\\') . DIRECTORY_SEPARATOR . $bukti_nota_file;
		$target_file = $jurnal_upload_dir . $bukti_nota_file;

		if (is_file($source_file)) {
			if (!is_file($target_file)) {
				@copy($source_file, $target_file);
			}
			if (is_file($target_file)) {
				$bukti_jurnal_file = $bukti_nota_file;
			}
		}
	}

	if($jenis_bayar==1){
		$dari_kas = $dari_kas;
	} else {
		$dari_kas = $this->beli->getIdJenis(10);
	}

	$catatan =  "PEMBELIAN NO#".$no_trans;

	$data = [
		"no_trans" 		=> $no_trans,
		"tgl"	 		=> $tanggal_beli,
		"keterangan" 	=> $catatan,
		"bukti" 	    => $bukti_jurnal_file,
		"id_user" 		=> $this->iduser
	];

	$this->db->insert('jurnal', $data);
	$jurnal_id 	    = $this->db->insert_id();

	$data_beli = [
		"id_jenis"         => $jenis_bayar,
		"id_jurnal"        => $jurnal_id,
		"no_transaksi"     => $no_trans,
		"id_akun"	      => $dari_kas,
		"tgl_pembelian"    => $tanggal_beli,
		"id_user"	      => $this->iduser,
		"total_bayar"	  => $total_pembelian,
		"pos"              => 'Y',
		"keterangan"       => $keterangan_kas,
		// Kolom baru (opsional) di tabel pembelian: bukti_nota
		"bukti_nota"       => $bukti_nota_file
	];

	$input_beli = $this->model_app->input('pembelian', $data_beli);

	if($jenis_bayar==1){
		$input_data = [
			'id_pembelian'=>$input_beli['id'],
			'tgl_bayar'=>$tanggal_beli,
			'jml_bayar'=>$total_pembelian,
			'id_bayar'=>$dari_kas,
			'id_user'=>$this->iduser,
		];
		$this->simpan_bayar_pembelian($input_data);
	}

	$input_jurnal = array();
	$input_kas = array();
	foreach($idAkun AS $key => $val){

		$input_kas[] = array(
			'id_pembelian'	=> $input_beli['id'],
			'id_bahan'	    => $val,
			'id_biaya'	    => getIdAkun($val),
			'id_supplier'	=> isset($supplier[$key]) ? $supplier[$key] : 0,
			'jumlah'	    => isset($nominal_jumlah[$key]) ? $nominal_jumlah[$key] : 0,
			'harga'	        => isset($nominal_harga[$key]) ? $nominal_harga[$key] : 0,
			'keterangan'    => isset($keterangan[$key]) ? $keterangan[$key] : '',
		);

		$_jumlah = isset($nominal_jumlah[$key]) ? $nominal_jumlah[$key] : 0;
		$_harga = isset($nominal_harga[$key]) ? $nominal_harga[$key] : 0;
		$total_harga = $_jumlah * $_harga;

		$input_jurnal[] = array(
			'id_jurnal' 		=> $jurnal_id,
			'id_akun'			=> $this->beli->getIdAkun($val),
			'tipe_kas'			=> $this->kas->getIdAkunKasById($val),
			'id_perkiraan'		=> 1,
			'nilai'				=> $total_harga,
			'catatan_jurnal'	=> isset($keterangan[$key]) ? $keterangan[$key] : '',
		);
	};

	$this->db->insert_batch('pembelian_detail', $input_kas);
	$this->db->insert_batch('jurnal_detail', $input_jurnal);
	$queued_stock = $this->pembelian_stok->queue_purchase($input_beli['id'], $this->iduser);

	$input_jurnal_kredit = array(
		'id_jurnal' 		=> $jurnal_id,
		'id_akun'			=> $dari_kas,
		'tipe_kas'			=> $getIdAkunKasById,
		'id_perkiraan'		=> 2,
		'nilai'				=> $total_pembelian,
		'catatan_jurnal'	=> $keterangan_kas,
	);

	$input = $this->model_app->input('jurnal_detail', $input_jurnal_kredit);

	if($input['status']=='ok') {
		$msg = 'Berhasil disimpan';
		if ($queued_stock > 0) $msg .= '. '.$queued_stock.' item stok menunggu ACC Owner/Superadmin';
		$response = ['status'=>true,'msg'=>$msg];
	} else {
		$response = ['status'=>false,'msg'=>'Gagal disimpan'];
	}

	$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 simpan_bayar_pembelian($input_data)
		{
			$input = $this->model_app->input('bayar_pembelian', $input_data);
			if ($input["status"] == "ok") {
				$data = ["ok" => "ok", "msg" => "Data berhasil dihapus"];
				} else {
				$data = ["ok" => "err", "msg" => "Data gagal dihapus"];
			}
		}
		
		public function hapus_detail()
		{
			$idx = $this->input->post("id");
			$id = ["no" => $idx];
			$res = $this->model_app->hapus("pembelian_detail", $id);
			if ($res["status"] == "ok") {
				$data = ["ok" => "ok", "msg" => "Data berhasil dihapus"];
				} else {
				$data = ["ok" => "err", "msg" => "Data gagal dihapus"];
			}
			$this->output
			->set_content_type("application/json")
			->set_output(json_encode($data));
		}
		
		public function load_modal()
		{
			$id = decrypt_url($this->input->post("id"));
			$cek_item_id =  $this->beli->cek_id($id);
			
			$data['supplier'] =  $this->model_app->pilih_where('id_supplier,nama_perusahaan','supplier',['publish'=>'Y']);
			if($cek_item_id == true)
			{
				$row =  $this->beli->view_pembelian(['id_pembelian'=>$id])->row();
				$data['row'] = $row;
				$data['no_trans'] = $row->no_transaksi;
				$data['tanggal'] = tgl_ambil($row->tgl_pembelian);
				$data['dari_kas'] = $row->id_akun;
				$data['keterangan'] = $row->keterangan;
				$data['total_bayar'] = $row->total_bayar;
				$data['item'] =  $this->beli->view_item(['kunci'=>0,'pub'=>'Y']);
				
				$data['data'] =  $this->beli->get_detailby_id($id);
				
				$this->load->view('pembelian/load_detail',$data);
				}else{
				$no_transaction =  $this->journal->check_number_tramsaction();
				$no_order = substr($no_transaction, 6, 4);
				$no_transaction_now = intval($no_order) + 1;
				if($no_transaction == null){
					$data['no_trans'] = date("ymd").'0001';
					} else {
					$data['no_trans'] = date("ymd").sprintf("%04s",$no_transaction_now);
				}
				$data['tanggal'] = tgl_sampai_slash();
				$data['item'] =  $this->beli->view_item(['kunci'=>0,'pub'=>'Y']);
				$this->load->view('pembelian/load_modal',$data);
			}
		}
		
		public function load_total_bayar()
		{
			$id = $this->db->escape_str($this->input->post("id"));
			$total = $this->model_cek->sum_pembelian(["id_pembelian" => $id]);
			echo $total;
		}
		
		public function load_bayar()
		{
			$info = $this->db->escape_str($this->input->post("info"));
			$id = decrypt_url($this->db->escape_str($this->input->post("id")));
			$iduser = $this->db->escape_str($this->input->post("user"));
			$format = "%Y-%m-%d";
			$mdate = mdate($format);
			
			$search = $this->model_app->edit("bayar_pembelian", [
			"id_pembelian" => $id,
			]);
			$data["bayar"] = $search;
			if($info=='bayarh'){
				$this->load->view("pembelian/list_piutang", $data, false);
				}else{
				$this->load->view("pembelian/list_bayar", $data, false);
			}
			
		}
        
        public function list_bayar()
        {
            $noin = $this->db->escape_str($this->input->post("id"));
            $data["total_bayar"] = $this->model_app
            ->pilih("total_bayar", "pembelian", ["id_pembelian" => $noin])
            ->row();
            $data["bayar"] = $this->model_app->view_where("bayar_pembelian", [
            "id_pembelian" => $noin,
			]);
			$this->load->view("pembelian/list_bayar", $data);
		}
        
        public function cetak_pembelian($noid)
        {
			$noid = decrypt_url($noid);
            $id = ["id_pembelian" => $noid];
            
            $search = $this->model_app->view_where("pembelian", $id);
            $data["logo"] = FCPATH . "uploads/" . info()["logo"];
            
            if ($search->num_rows() > 0) {
                // $this->session->unset_userdata("cartbeli");
                $row = $search->row_array();
				// dump($row);
                $data["cetak"] = $row;
                $data["info"] = info();
                $data["detail"] = $this->model_app
                ->view_where("pembelian_detail", ["id_pembelian" => $noid])
                ->result_array();
                $data["user"] = $this->model_app
                ->view_where("tb_users", ["id_user" => $row["id_user"]])
                ->row_array();
                $this->load->library("pdf");
                $this->pdf->setPaper("A5", "landscape");
                $this->pdf->filename =
                "pembelian_" . $noid . "_" . $row["tgl_pembelian"];
                $this->pdf->load_view("pembelian/cetak_pembelian", $data);
                // $this->load->view('pembelian/cetak_pembelian',$data);
                } else {
                $data["heading"] = "Halaman error";
                $data["message"] = "Data tidak ditemukan";
                $this->load->view("errors/html/error_404", $data);
			}
		}
        
        public function cetak_periode()
        {
            $periode = $this->input->post('periode');
            list($bulan,$tahun) = explode(' ',$periode);
            $bulan = getBlnPiutang($bulan);
            $data = $this->model_data->getMonthPembelian($bulan,$tahun);
            print_r($data);exit;
            $id = ["id_pembelian" => $noid];
            
            $search = $this->model_app->view_where("pembelian", $id);
            $data["logo"] = FCPATH . "uploads/" . info()["logo"];
            
            if ($search->num_rows() > 0) {
                $this->session->unset_userdata("cartbeli");
                $row = $search->row_array();
                $data["cetak"] = $row;
                $data["info"] = info();
                $data["detail"] = $this->model_app
                ->view_where("pembelian_detail", ["id_pembelian" => $noid])
                ->result_array();
                $data["user"] = $this->model_app
                ->view_where("tb_users", ["id_user" => $row["id_user"]])
                ->row_array();
                $this->load->library("pdf");
                $this->pdf->setPaper("A5", "landscape");
                $this->pdf->filename =
                "pembelian_" . $noid . "_" . $row["tgl_pembelian"];
                $this->pdf->load_view("pembelian/cetak_pembelian", $data);
                // $this->load->view('pembukuan/cetak_pengeluaran',$data);
                } else {
                $data["heading"] = "Halaman error";
                $data["message"] = "Data tidak ditemukan";
                $this->load->view("errors/html/error_404", $data);
			}
		}
        
        public function print_pembelian(){		
			
			$tanggal = $this->input->post('tanggal', true);	
			$jenis   = $this->db->escape_str($this->input->post('jenis'));			
			$id_user = $this->db->escape_str($this->input->post('id_user'));
			
			if(empty($_POST)){
				$data['heading'] = 'Halaman error';				
				$data['message'] = 'Data tidak ditemukan';				
				$this->load->view('errors/404',$data);
				}else{
				if(!empty($tanggal)){
					$date = date_ranges($tanggal);
					$dari = date_replace_slash($date['dari']);
					$sampai = date_replace_slash($date['sampai']);
					
					$condition['search']['dari'] = $dari; 
					$condition['search']['sampai'] = $sampai;
					
					
					if(empty($id_user) AND empty($jenis))
					{
						$search = $this->model_data->printPembelian($condition);
					}
					
					if(!empty($id_user) AND empty($jenis))
					{
						$condition['where'] = array(
						'id_user' => $id_user
						);
						$search = $this->model_data->printPembelian($condition);
					}
					
					$data['user'] = $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();	
					
					
					$data['logo'] = FCPATH.'uploads/'.info()['logo'];			
					
					if(!empty($search)){
						$data['dari'] = $dari;		
						$data['sampai'] = $sampai;		
						$data['info'] = info();		
						$data['pembelian'] = $search;
						
						$this->load->library('pdf');				
						$this->pdf->setPaper('A4', 'potrait');				
						$this->pdf->filename = "pembelian_".$dari."_".$sampai;
						$this->pdf->load_view('pembelian/print_pembelian', $data);				
						// $this->load->view('pembelian/print_pembelian',$data);				
						}else{				
						$data['heading'] = 'Halaman Laporan';				
						$data['message'] = 'Belum ada data';				
						$this->load->view('errors/html/error_404',$data);				
					}	
					}else{
					$data['cetak']       = 'error';
					$this->load->view('errors/404',$data);
				}
			}
		}
		
		public function hapus_pembelian()
		{
			$id = decrypt_url($this->db->escape_str($this->input->post('id'))); 
			$idtrans = decrypt_url($this->db->escape_str($this->input->post('idtrans'))); 
			if ($this->pembelian_stok->has_approved($id)) {
				$this->output->set_content_type('application/json')->set_output(json_encode(array(
					'status'=>false, 'msg'=>'Pembelian tidak dapat dihapus karena stoknya sudah disetujui.'
				)));
				return;
			}
			$this->model_app->hapus('pembelian_stok_pending', ['id_pembelian'=>$id]);
			$hapus = $this->model_app->hapus("pembelian", ['id_pembelian'=>$id]);
			if($hapus['status']=='ok'){
				$this->model_app->hapus("pembelian_detail", ['id_pembelian'=>$id]);
				$this->hapus_jurnal($idtrans);
				
				$data = ["status" => true, "msg" => "Data berhasil dihapus"];
				}else{
				$data = ["status" => false, "msg" => "Data gagal dihapus"];
			}
			
			$this->output
			->set_content_type("application/json")
			->set_output(json_encode($data));
		}

		private function boleh_acc_stok()
		{
			return in_array($this->level, array('admin', 'owner', 'superadmin', 'super_admin'), true);
		}

		public function toggle_sinkron_stok()
		{
			if (!$this->boleh_acc_stok()) {
				$this->output->set_status_header(403)->set_content_type('application/json')->set_output(json_encode(array('status'=>false,'msg'=>'Hanya Owner/Superadmin yang dapat mengubah sinkronisasi.')));
				return;
			}
			$enabled = (int)$this->input->post('aktif') === 1;
			$this->pembelian_stok->set_enabled($enabled);
			$this->output->set_content_type('application/json')->set_output(json_encode(array(
				'status'=>true,
				'msg'=>$enabled ? 'Sinkronisasi pembelian dengan data stok diaktifkan.' : 'Sinkronisasi pembelian dengan data stok dinonaktifkan.'
			)));
		}

		public function acc_stok_pembelian()
		{
			if (!$this->boleh_acc_stok()) {
				$this->output->set_status_header(403)->set_content_type('application/json')->set_output(json_encode(array('status'=>false,'msg'=>'ACC stok hanya dapat dilakukan Owner/Superadmin.')));
				return;
			}
			$id = decrypt_url($this->input->post('id'));
			$result = $this->pembelian_stok->approve_purchase((int)$id, $this->iduser);
			$this->output->set_content_type('application/json')->set_output(json_encode($result));
		}
		
		private function hapus_jurnal($jurnal)
		{
			$cek = $this->model_app->view_where('jurnal',['no_trans'=>$jurnal]);
			if($cek->num_rows() >0)
			{
				$result = $cek->result();
				
				foreach($result AS $row)
				{
					$this->model_app->delete('jurnal', ['id_jurnal'=>$row->id_jurnal]);
				}
				
			}
		}
		/**
			* jenis
			*
			* @return void
		*/
		public function item()
		{
			cek_menu_akses();
			$data['title'] = 'Item Pembelian | ' . info()['title'];
			$data['judul'] = 'Item Pembelian';
			
			$this->template->load('main/themes', 'pembelian/item', $data);
		}
		
		/**
			* ajaxPembelian
			*
			* @return void
		*/
		function cariItem(){
			// cek_session_login(); 
			$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; 
			} 
			// $conditions['where'] = array('pos' => 'Y');
			$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(
			'kunci' =>0
			);	
			
			// Get record count 
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->beli->getItem($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#data_item'; 
			$config['base_url']    = base_url('pembelian/cariItem'); 
			$config['total_rows']  = $totalRec; 
			$config['per_page']    = $limit; 
			$config['link_func']   = 'search_item'; 
			
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records 
			$conditions['start'] = $offset; 
			$conditions['limit'] = $limit;
			
			unset($conditions['returnType']); 
			$data['result'] = $this->beli->getItem($conditions); 
			
			// Load the data list view 
			$this->load->view('pembelian/cari-item', $data); 
		}     
		
		/**
			* edit_jenis
			*
			* @return void
		*/
		public function edit_item()
		{
			cek_nput_post('GET');
			$id = xss_filter($this->input->post('id'),'xss');
			$id = decrypt_url($id);
			$cek_item_id = $this->beli->cek_item_id($id);
			if ($cek_item_id == true) {
				$where = array('id' => $id);
				
				$row = $this->beli->edit_item($where);
				
				$response = [
				'status' => true, 
				'id' => encrypt_url($id), 
				'title' => $row->title, 
				"kelompok" => $row->kelompok_akun, 
				'id_akun' => $row->id_akun,
				'aktif' => $row->pub
				];
				
				} else {
				$response = [
				'status' => false, 
				'id' => 0, 
				'judul' => "", 
				"kelompok" => "", 
				"id_akun" => "", 
				"aktif" => ""];
			}
			
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($response));
		}
		
		/**
			* save_item
			*
			* @return void
		*/
		public function save_item()
		{
			cek_nput_post('GET');
			simpan_demo('Simpan');
			
			$id = xss_filter($this->input->post('id'),'xss');
			$id = decrypt_url($id);
			$id_akun = xss_filter($this->input->post('id_akun'),'xss');
			$type = xss_filter($this->input->post('type'),'xss');
			$judul = xss_filter($this->input->post('judul'),'xss');
			$kelompok_akun = xss_filter($this->input->post('kelompok'),'xss');
			$aktif = xss_filter($this->input->post('aktif'),'xss');
			if(!empty($id_akun))
			{
				$_data = [
				'title'=>$judul,
				'id_akun'=>$id_akun,
				'kelompok_akun'=>$kelompok_akun,'pub'=>$aktif];
				}else{
				$_data = [
				'title'=>$judul,
				'kelompok_akun'=>$kelompok_akun,
				'pub'=>$aktif];
			}
			
			
			///data baru
			if($id ==0 AND $type=='add'){
				$result= $this->beli->save_item($_data);
				if($result['status']==true){
					$this->cek_akun($judul,$result['id']);
					$data = [
						'status'=>true,
						'msg'=>'Data berhasil disimpan',
						'id'=>$result['id'],
						'title'=>$judul
					];
					}else{
					$data = ['status'=>false];
				}
			}
			
			// dump($get_akun_item);
			
			if($id > 0 AND $type=='edit'){
				$cek_item_id = $this->beli->cek_item_id($id);
				if ($cek_item_id == true) {
					$this->cek_akun($judul,$id);
					$result=  $this->beli->update_item($_data,['id'=>$id]);
					if($result===true){
						$data = array(
							'status'=>true,
							'msg'=>'Data berhasil update',
							'id'=>$id,
							'title'=>$judul
						);
						}else{
						$data = array('status'=>false,'msg'=>'Tidak ada perubahan data');
						// $this->cek_akun($judul,$id);
					}
					}else{
					$data = array('status'=>false,'msg'=>'Data tidak ditemukan');
				}
			}
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		
		private function cek_akun($nama,$val)
		{
			$kelompok = xss_filter($this->input->post('kelompok'),'xss');
			$get_akun_item = $this->beli->get_nama($val);
			// dump($_POST);
			$arr = [];
			if($nama!=$get_akun_item)
			{
				$this->model_app->update('akun',['nama'=>$nama],['id_kelompok_akun'=>$kelompok,'nama'=>$get_akun_item]);
				$arr = ['a'];
				}else{
				
				$cek = $this->model_app->view_where('akun',['nama'=>$nama]);
				if($cek->num_rows() > 0)
				{
					
					$arr = ['b'];
					}else{
					$this->db->select_max('noakun');
					$this->db->from('akun');
					$this->db->where('id_kelompok_akun',$kelompok);
					$query = $this->db->get()->row()->noakun; 
					$max = $query + 1;
					
					$_data = [
					'noakun'=>$max,
					'nama'=>$nama,
					'id_kelompok_akun'=>$kelompok,
					'id_perkiraan'=>1,
					'saldo_awal'=>0,
					'keterangan'=>'',
					'id_user'=>$this->iduser,
					];
					
					$input = $this->model_app->input('akun',$_data);
					$this->beli->update_item(['id_akun'=>$input['id']],array('id'=>$val));
					$arr = ['c'];
				}
			}
			// print_r($arr);
			// print_r($get_akun_item);
		}
		
		/**
			* hapus_item
			*
			* @return true
		*/
		public function hapus_item()
		{
			cek_nput_post('GET');
			simpan_demo('Hapus');
			$id   = xss_filter($this->input->post('id'),'xss');
			$id   = decrypt_url($id);
			$type = xss_filter($this->input->post('type'),'xss');
			
			$cek_item_id = $this->beli->cek_item_id($id);
			if ($cek_item_id == true and $type == 'hapus') {
				$cek_item = $this->model_app->view_where('pembelian_detail', ['id_biaya' => $id]);
				if ($cek_item->num_rows() == 0) {                    
					$result = $this->beli->delete_item(['id' => $id]);
					if ($result == true) {
						$data = ['status' => true, 'msg' => 'Item berhasil dihapus'];
						} else {
						$data = ['status' => false, 'msg' => 'Item gagal dihapus'];
					}
					
					} else {
					$data = ['status' => false, 'msg' => 'Item tidak bisa dihapus'];
				}
				} else {
				$data = ['status' => false, 'msg' => 'Item tidak ditemukan'];
			}
			
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		
		
		public function akun_kas(){
			$id   = xss_filter($this->input->post('id'),'xss');
			
			if(empty($id))
			{
				$result = $this->model_app->views('set_account_kas');
				
				$data = array();
				foreach ($result->result() as $row)
				{
					$data[] = array("id"=>$row->id_akun,"name"=>$row->nm);
				}
				}else{
				$row = $this->model_app->view_where('set_account_kas',['id_akun'=>$id])->row();
				$data[] = array("id"=>$row->id_akun,"name"=>$row->nm);
			}
			
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		
		public function simpan_bayar_piutang()
        {
			
			
            $id_pembelian = decrypt_url($this->db->escape_str($this->input->post("id")));
            $no_transaksi = $this->db->escape_str($this->input->post("no_transaksi"));
            $total_beli = $this->db->escape_str($this->input->post("total"));
            $jml_bayar = $this->db->escape_str($this->input->post("jml_bayar"));
            $id_bayar = $this->db->escape_str($this->input->post("cara_bayar"));
			$keterangan_kas = $this->db->escape_str($this->input->post("keterangan_kas"));
			$tanggal_input = trim($this->db->escape_str($this->input->post("tanggal_bayar")));
			$tanggal_object = DateTime::createFromFormat('d/m/Y', $tanggal_input);

			if (!$tanggal_object || $tanggal_object->format('d/m/Y') !== $tanggal_input) {
				$this->output
				->set_content_type('application/json')
				->set_output(json_encode([
					'status' => 400,
					'msg' => 'Format tanggal bayar tidak valid'
				]));
				return;
			}

			$tanggal_bayar = $tanggal_object->format('Y-m-d');
			
			$tgl_pembelian = $this->model_app->pilih_where('tgl_pembelian','pembelian',['id_pembelian'=>$id_pembelian])->row()->tgl_pembelian;
			$input_data = [
			'id_pembelian'=>$id_pembelian,
			'tgl_bayar'=>$tanggal_bayar,
			'jml_bayar'=>convert_to_number($jml_bayar),
			'id_bayar'=>$id_bayar,
			'id_user'=>$this->iduser,
			];
			// dump($input_data);
			$input = $this->model_app->input("bayar_pembelian", $input_data);
			if ($input["status"] == "ok") {
				$this->input_jurnal_bayar($no_transaksi,$tgl_pembelian,$id_bayar,$jml_bayar,$keterangan_kas);
				$data = ["status" => 200, "msg" => "sukses"];
				}else{
				$data = ["status" => 400, "msg" => "Gagal"];
			}
			
            $this->output
            ->set_content_type("application/json")
            ->set_output(json_encode($data));
		}
		
		private function input_jurnal_bayar($no_transaksi,$tgl_pembelian,$id_bayar,$jml_bayar,$keterangan_kas){
			
			$catatan =  "BAYAR PEMBELIAN NO#".$no_transaksi;
			$no_transaction =  $this->journal->check_number_tramsaction();
			$no_order = substr($no_transaction, 6, 4);
			$no_transaction_now = intval($no_order) + 1;
			if($no_transaction == null){
				$no_trans = date("ymd").'0001';
				} else {
				$no_trans = date("ymd").sprintf("%04s",$no_transaction_now);
			}
			$data = [
			"no_trans" 		=> $no_trans,
			"tgl"	 		=> $tgl_pembelian,
			"keterangan" 	=> $catatan,
			"bukti" 	    => '',
			"id_user" 		=> $this->iduser
			];
			$getIdAkunKasById = $this->kas->getIdAkunKasById($id_bayar);
			$this->db->insert('jurnal', $data);
			$jurnal_id 	    = $this->db->insert_id();
			$dari_kas = $this->beli->getIdJenis(10);
			$input_jurnal_debit = array(
			'id_jurnal' 		=> $jurnal_id,
			'id_akun'			=> $dari_kas,
			'tipe_kas'			=> $getIdAkunKasById,
			'id_perkiraan'		=> 1, 
			'nilai'				=> convert_to_number($jml_bayar), 
			'catatan_jurnal'	=> $keterangan_kas, 
			);
			$input = $this->model_app->input('jurnal_detail', $input_jurnal_debit);
			
			$input_jurnal_kredit = array(
			'id_jurnal' 		=> $jurnal_id,
			'id_akun'			=> $id_bayar,
			'tipe_kas'			=> $getIdAkunKasById,
			'id_perkiraan'		=> 2, 
			'nilai'				=> convert_to_number($jml_bayar), 
			'catatan_jurnal'	=> $keterangan_kas, 
			);
			$input = $this->model_app->input('jurnal_detail', $input_jurnal_kredit);
		}
	}
