<?php
	defined('BASEPATH') or exit('No direct script access allowed');
	
	class Stok extends CI_Controller
	{
		public function __construct()
		{
			parent::__construct();
			cek_session_login();
			$this->info = info();
			$this->back = $this->agent->referrer();
			$this->perPage = 10; 
			$this->iduser = $this->session->idu;
			$this->load->model('Pembelian_stok_model', 'pembelian_stok');
		}
		
		public function data()
		{
			cek_menu_akses();
			cek_crud_akses(8);
			$this->ensure_bahan_varian_schema();
			$data['title'] = 'Data Stok | '.info()['title'];
			$data['judul'] ='Data Stok';
			$this->ensure_batas_minimum_stok_column();
			$data['stok_keluar_trigger_status'] = stok_keluar_trigger_status();
			
			$conditions['where'] = array( 
            'bahan.status_stok' => 'Y',
            'bahan.pub' => 1
			); 
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->getStokBahan($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#dataStok'; 
			$config['base_url']    = base_url('stok/cariStok'); 
			$config['total_rows']  = $totalRec; 
			$config['per_page']    = $this->perPage; 
			$config['link_func']   = 'search_Stok'; 
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records 
			$conditions = array(
			  'limit' => $this->perPage
			);
			$conditions['search']['sortBy'] = 'ASC'; // default: stok  terkecil -> terbesar

			$conditions['where'] = array( 
            'bahan.status_stok' => 'Y',
            'bahan.pub' => 1
			); 
			$data['bahan'] = $this->db
				->select('bahan.id, bahan.title, bahan.batas_minimum_stok, satuan.satuan')
				->from('bahan')
				->join('satuan', 'satuan.id = bahan.id_satuan', 'left')
				->where(['bahan.pub' => 1, 'bahan.status_stok' => 'Y'])
				->where('bahan.varian_aktif !=', 1)
				->order_by('bahan.title', 'ASC')
				->get()
				->result(); 
			$data['result'] = $this->model_data->getStokBahan($conditions); 
			// $data['mutasi'] = $this->model_stok->get_current_mutasi($data['result']);
			$this->template->load('main/themes','stok/stok',$data);
		}
		
		public function cariStok(){
			cek_nput_post('GET');
			$this->ensure_bahan_varian_schema();
			$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; 
				$sortField = $this->input->post('sortField', true);

				// whitelist biar aman
				$allowedFields = ['total_stok','stok_masuk','stok_keluar'];
				if (!in_array($sortField, $allowedFields, true)) {
				  $sortField = 'total_stok';
				}

				$conditions['search']['sortField'] = $sortField;

			} 
			
			$keywords = $this->input->post('keywords'); 
			if(!empty($keywords)){ 
				$conditions['search']['keywords'] = $keywords; 
			} 
			
			$conditions['where'] = array( 
            'bahan.status_stok' => 'Y',
            'bahan.pub' => 1
			); 
			// Get record count 
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->getStokBahan($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#dataStok'; 
			$config['base_url']    = base_url('stok/cariStok'); 
			$config['total_rows']  = $totalRec; 
			$config['per_page']    = $limit; 
			$config['link_func']   = 'search_Stok';
			
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records 
			$conditions['start'] = $offset; 
			$conditions['limit'] = $limit;
			$conditions['where'] = array( 
            'bahan.status_stok' => 'Y',
            'bahan.pub' => 1
			); 
			unset($conditions['returnType']); 
			$data['result'] = $this->model_data->getStokBahan($conditions); 
			$data['stok_keluar_trigger_status'] = stok_keluar_trigger_status();
			
			$conditions['offset'] = $offset; 
			// Load the data list view 
			$this->load->view('stok/cari-stok', $data, false); 
		}
		public function masuk()
		{
			cek_menu_akses();
			cek_crud_akses(8);
			$data['title'] = 'Data Stok Masuk | '.info()['title'];
			$data['judul'] ='Data Stok Masuk';
			
			$conditions['where'] = array( 
            'bahan.status_stok' => 'Y',
            'bahan.pub' => 1,
            'bahan.id >' => 1
			); 
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->getStokBahan($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#dataStokMasuk'; 
			$config['base_url']    = base_url('stok/cariStokMasuk'); 
			$config['total_rows']  = $totalRec; 
			$config['per_page']    = $this->perPage; 
			// $config['link_func']   = 'search_StokMasuk'; 
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records 
			$conditions = array( 
			'limit' => $this->perPage 
			); 
			$conditions['where'] = array( 
            'bahan.status_stok' => 'Y',
            'bahan.pub' => 1,
            'bahan.id >' => 1
			); 
			$data['bahan'] = $this->model_app->view_where('bahan',['pub'=>1,'status_stok'=>'Y'])->result(); 
			$data['result'] = $this->model_data->getStokBahan($conditions); 
			$data['stok_pembelian_pending'] = $this->pembelian_stok->pending_purchases();
			$data['boleh_acc_stok'] = in_array(strtolower((string)$this->session->level), ['admin','owner','superadmin','super_admin'], true);
			
			// $data['mutasi'] = $this->model_stok->get_current_mutasi($data['result']);
			$this->template->load('main/themes','stok/stok-masuk',$data);
		}
		public function cariStokMasuk(){
			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( 
            'bahan.status_stok' => 'Y',
            'bahan.pub' => 1,
            'bahan.id >' => 1
			); 
			// Get record count 
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->getStokBahan($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#dataStokMasuk'; 
			$config['base_url']    = base_url('stok/cariStokMasuk'); 
			$config['total_rows']  = $totalRec; 
			$config['per_page']    = $limit; 
			$config['link_func']   = 'search_Stok_Masuk'; 
			
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records 
			$conditions['start'] = $offset; 
			$conditions['limit'] = $limit;
			$conditions['where'] = array( 
            'bahan.status_stok' => 'Y',
            'bahan.pub' => 1,
			'bahan.id >' => 1
			); 
			unset($conditions['returnType']); 
			$data['result'] = $this->model_data->getStokBahan($conditions); 
			
			$conditions['offset'] = $offset; 
			// Load the data list view 
			$this->load->view('stok/cari-stok-masuk', $data, false); 
		}
		public function detail_stok_masuk(){
			$id = $this->input->post('id');
			$conditions['where'] = array( 
            'id_bahan' => $id
			); 
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->getStokMasuk($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#DetailStok'; 
			$config['base_url']    = base_url('stok/cariDetailStokMasuk'); 
			$config['total_rows']  = $totalRec; 
			$config['per_page']    = $this->perPage; 
			$config['link_func']   = 'search_detail_masuk'; 
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records 
			$conditions = array( 
			'limit' => $this->perPage 
			); 
			$conditions['where'] = array( 
            'id_bahan' => $id
			); 
			
			$data['result'] = $this->model_data->getStokMasuk($conditions); 
			$this->load->view('stok/detail-stok-masuk', $data, false); 
		}
		public function keluar()
		{
			cek_menu_akses();
			cek_crud_akses(8);
			$data['title'] = 'Data Stok Keluar | '.info()['title'];
			$data['judul'] ='Data Stok Keluar';
			
			$conditions['where'] = array( 
            'bahan.status_stok' => 'Y',
            'bahan.pub' => 1
			); 
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->getStokBahan($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#dataStok'; 
			$config['base_url']    = base_url('stok/cariStokKeluar'); 
			$config['total_rows']  = $totalRec; 
			$config['per_page']    = $this->perPage; 
			// $config['link_func']   = 'search_Stok'; 
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records 
			$conditions = array( 
			'limit' => $this->perPage 
			); 
			$conditions['where'] = array( 
            'bahan.status_stok' => 'Y',
            'bahan.pub' => 1
			); 
			$data['bahan'] = $this->model_app->view_where('bahan',['pub'=>1,'status_stok'=>'Y'])->result(); 
			$data['result'] = $this->model_data->getStokBahan($conditions); 
			$this->template->load('main/themes','stok/stok-keluar',$data);
		}
		
		public function cariStokKeluar(){
			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( 
            'bahan.status_stok' => 'Y',
            'bahan.pub' => 1
			); 
			// Get record count 
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->getStokBahan($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#dataStokKeluar'; 
			$config['base_url']    = base_url('stok/cariStokKeluar'); 
			$config['total_rows']  = $totalRec; 
			$config['per_page']    = $limit; 
			$config['link_func']   = 'search_Stok_Keluar'; 
			
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records 
			$conditions['start'] = $offset; 
			$conditions['limit'] = $limit;
			$conditions['where'] = array( 
            'bahan.status_stok' => 'Y',
            'bahan.pub' => 1
			); 
			unset($conditions['returnType']); 
			$data['result'] = $this->model_data->getStokBahan($conditions); 
			
			$conditions['offset'] = $offset; 
			// Load the data list view 
			$this->load->view('stok/cari-stok-keluar', $data, false); 
		}
		
		public function detail_stok_keluar(){
			$id = $this->input->post('id');
			$conditions['where'] = array( 
            'id_bahan' => $id
			); 
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->getStokKeluar($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#DetailStok'; 
			$config['base_url']    = base_url('stok/cariDetailStokKeluar'); 
			$config['total_rows']  = $totalRec; 
			$config['per_page']    = $this->perPage; 
			$config['link_func']   = 'search_detail_stok'; 
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records 
			$conditions = array( 
			'limit' => $this->perPage 
			); 
			$conditions['where'] = array( 
            'id_bahan' => $id
			); 
			
			$data['id'] = $id;
			$data['result'] = $this->model_data->getStokKeluar($conditions); 
			$this->load->view('stok/detail-stok-keluar', $data, false); 
		}
		 
		public function history($detail=''){
			if(empty($detail)){
				cek_menu_akses();
				cek_crud_akses(8);
				$data['title'] = 'Laporan History Stok | '.info()['title'];
				$data['judul'] ='History Stok';
				$data["tgl"] = date('d/m/Y');
				$conditions['returnType'] = 'count'; 
				$totalRec = $this->model_data->getRowsLaporan($conditions); 
				
				// Pagination configuration 
				$config['target']      = '#dataStok'; 
				$config['base_url']    = base_url('stok/cariLaporan'); 
				$config['total_rows']  = $totalRec; 
				$config['per_page']    = $this->perPage; 
				$config['link_func']   = 'search_Stok'; 
				// Initialize pagination library 
				$this->ajax_pagination->initialize($config); 
				
				// Get records 
				$conditions = array( 
				'limit' => $this->perPage 
				); 
				
				$data['result'] = $this->model_data->getRowsLaporan($conditions); 
				$this->template->load('main/themes','stok/laporan',$data);
				}else{
				$id = decrypt_url($this->uri->segment(3));
				$data['title'] = 'History Stok | '.info()['title'];
				$data['judul'] ='History Stok';
				$data['id'] =$id;
				$data['list_cc'] = $this->model_stok->list_cc();
				$data['query'] = $this->model_stok->report_master($id);
				
				$this->template->load('main/themes','stok/history',$data);
			}
		}
		
		public function cetak_history($detail=''){
			$id = decrypt_url($this->uri->segment(3));
			$type = $this->input->get('type'); 
			$data['title'] = 'History Stok | '.info()['title'];
			$data['judul'] ='History Stok';
			$data['info'] = info();
			$data['user'] = $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
			$data['owner'] = $this->model_app->view_where('tb_users', array('level' => 'owner'))->row()->app_secret;
			
			$data['periode_stok'] = periode_stok($id);
			$data['id'] =$id;
			$data['list_cc'] = $this->model_stok->list_cc();
			$data['query'] = $this->model_stok->report_master($id);
			// print_r($data['query']);exit;
			if($type=='pdf'){
				$data['logo'] = FCPATH.'uploads/'.info()['logo'];
				$this->load->library("pdf");
				$this->pdf->setPaper("A4", "portrait");
				$this->pdf->filename = slugify("laporan history stok ".periode_stok($id));
				$this->pdf->load_view("stok/laporan_history_stok", $data);
				}else{
				$data['logo'] = base_url().'uploads/'.info()['logo'];
				$this->load->view("stok/laporan_history_stok", $data);
			}
			
			
		}
		
		public function cariLaporan(){
			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; 
			} 
			
			
			// Get record count 
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->getRowsLaporan($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#dataStok'; 
			$config['base_url']    = base_url('stok/cariLaporan'); 
			$config['total_rows']  = $totalRec; 
			$config['per_page']    = $limit; 
			$config['link_func']   = 'search_Produk'; 
			
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records 
			$conditions['start'] = $offset; 
			$conditions['limit'] = $limit;
			
			unset($conditions['returnType']); 
			$data['result'] = $this->model_data->getRowsLaporan($conditions); 
			
			$conditions['offset'] = $offset; 
			// Load the data list view 
			$this->load->view('stok/laporan-stok', $data, false); 
		}
		public function edit_bahan(){
			cek_nput_post('GET');
			cek_crud_akses(8);
			$id= $this->db->escape_str($this->input->post('id'));
			if($id>0){
				$select = ['`bahan`.`title`',
				'`bahan`.`id`',
				'`bahan`.`harga`',
				'`bahan`.`harga`',
				'`bahan`.`harga_modal`',
				'`bahan`.`harga_jual`',
				'`bahan`.`id_satuan`',
				'`satuan`.`satuan`',
				'`bahan`.`pub`'];
				$where = array('bahan.id' => $id);
				
				$row = $this->model_app->join_where($select,'satuan','bahan','id','id_satuan',$where)->row_array();
				$data = array('id'=>$id,
				'judul'=>$row['title'],
				'modal'=>$row['harga_modal'],
				'terendah'=>$row['harga_jual'],
				'tertinggi'=>$row['harga'],
				'id_satuan'=>$row['id_satuan'],
				'satuan'=>$row['satuan'],
				'aktif'=>$row['pub']);
				}else{
				$data = array('id'=>0,'judul'=>"",'harga'=>'',"aktif"=>"",'msg'=>'error');
			}
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		private function parse_stok_decimal($value)
		{
			$value = trim((string) $value);
			$value = str_replace(['Rp.', ' '], '', $value);

			if (strpos($value, ',') !== false) {
				$value = str_replace('.', '', $value);
				$value = str_replace(',', '.', $value);
			} elseif (preg_match('/^\d{1,3}(\.\d{3})+$/', $value)) {
				$value = str_replace('.', '', $value);
			}

			return is_numeric($value) ? (float) $value : null;
		}

		public function save_stok()
		{
			cek_nput_post('GET');
			simpan_demo('Simpan');
			cek_crud_akses(9);
			// dump($_POST);
			
			$id = ($this->db->escape_str($this->input->post('id')));
			$harga_beli= $this->db->escape_str($this->input->post('harga_beli'));
			$jumlah = $this->parse_stok_decimal($this->input->post('jumlah'));
			$keterangan= $this->db->escape_str($this->input->post('keterangan'));

			if ($jumlah === null || $jumlah <= 0) {
				$data = array('status'=>400,'msg'=>'Jumlah stok harus berupa angka lebih dari 0');
				$this->output
				->set_content_type('application/json')
				->set_output(json_encode($data));
				return;
			}
			
			
			$_data = array(
			'id_bahan'=>$id,
			'jumlah'=>$jumlah,
			'harga_beli'=>$harga_beli,
			'ket'=>$keterangan,
			'create_date'=>date('Y-m-d H:i:s')
			);
			///data baru
			$res= $this->model_app->input('stok_masuk',$_data);
			if($res['status']=='ok'){
				$data = array('status'=>200,'msg'=>'Stok berhasil disimpan');
				}else{
				$data = array('status'=>400);
			}
			
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}

		private function ensure_batas_minimum_stok_column()
		{
			if (!$this->db->field_exists('batas_minimum_stok', 'bahan')) {
				$this->load->dbforge();
				$this->dbforge->add_column('bahan', [
					'batas_minimum_stok' => [
						'type' => 'DECIMAL',
						'constraint' => '15,2',
						'default' => '0.00',
						'null' => false,
						'after' => 'status_stok',
					],
				]);
			}
		}

		private function ensure_bahan_varian_schema()
		{
			if (!$this->db->table_exists('bahan')) {
				return;
			}

			$this->load->dbforge();
			$fields = [];

			if (!$this->db->field_exists('parent_bahan_id', 'bahan')) {
				$fields['parent_bahan_id'] = [
					'type' => 'INT',
					'constraint' => 11,
					'null' => false,
					'default' => 0,
					'after' => 'id',
				];
			}

			if (!$this->db->field_exists('varian_aktif', 'bahan')) {
				$fields['varian_aktif'] = [
					'type' => 'INT',
					'constraint' => 1,
					'null' => false,
					'default' => 0,
					'after' => 'komisi_desain_aktif',
				];
			}

			if (!$this->db->field_exists('varian_warna', 'bahan')) {
				$fields['varian_warna'] = [
					'type' => 'VARCHAR',
					'constraint' => 100,
					'null' => true,
					'default' => '',
					'after' => 'varian_aktif',
				];
			}

			if (!$this->db->field_exists('varian_ukuran', 'bahan')) {
				$fields['varian_ukuran'] = [
					'type' => 'VARCHAR',
					'constraint' => 100,
					'null' => true,
					'default' => '',
					'after' => 'varian_warna',
				];
			}

			if (!empty($fields)) {
				$this->dbforge->add_column('bahan', $fields);
			}
		}

		public function save_minimum_stok()
		{
			cek_nput_post('GET');
			simpan_demo('Simpan');
			cek_crud_akses(9);

			$id = (int) $this->input->post('id');
			$minimumRaw = trim((string) $this->input->post('minimum'));
			$minimumRaw = str_replace(['Rp.', ' '], '', $minimumRaw);
			if (strpos($minimumRaw, ',') !== false) {
				$minimumRaw = str_replace('.', '', $minimumRaw);
				$minimumRaw = str_replace(',', '.', $minimumRaw);
			} elseif (preg_match('/^\d{1,3}(\.\d{3})+$/', $minimumRaw)) {
				$minimumRaw = str_replace('.', '', $minimumRaw);
			}
			$minimum = is_numeric($minimumRaw) ? (float) $minimumRaw : null;

			if ($id <= 0) {
				$data = ['status' => 400, 'msg' => 'Data bahan tidak valid'];
			} elseif ($minimum === null) {
				$data = ['status' => 400, 'msg' => 'Batas minimum stok harus berupa angka'];
			} elseif ($minimum < 0) {
				$data = ['status' => 400, 'msg' => 'Batas minimum stok tidak boleh minus'];
			} else {
				$this->ensure_batas_minimum_stok_column();
				$cek = $this->model_app->view_where('bahan', ['id' => $id, 'status_stok' => 'Y', 'pub' => 1]);

				if ($cek->num_rows() == 0) {
					$data = ['status' => 404, 'msg' => 'Data bahan tidak ditemukan'];
				} else {
					$res = $this->model_app->update('bahan', ['batas_minimum_stok' => $minimum], ['id' => $id]);
					$data = ($res['status'] == 'ok')
						? ['status' => 200, 'msg' => 'Batas minimum stok berhasil disimpan']
						: ['status' => 400, 'msg' => 'Batas minimum stok gagal disimpan'];
				}
			}

			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}

		public function save_stok_trigger_status()
		{
			cek_nput_post('GET');
			simpan_demo('Simpan');
			cek_crud_akses(9);

			$status = (int) $this->input->post('status');
			if (!in_array($status, [2, 3], true)) {
				$data = ['status' => 400, 'msg' => 'Status pengurangan stok tidak valid'];
			} elseif (!$this->db->table_exists('shared_folder')) {
				$data = ['status' => 400, 'msg' => 'Tabel pengaturan tidak tersedia'];
			} else {
				$row = $this->db
					->select('id')
					->from('shared_folder')
					->where('nama', 'stok_keluar_trigger_status')
					->limit(1)
					->get()
					->row();

				if (!empty($row)) {
					$res = $this->model_app->update(
						'shared_folder',
						['isi' => (string) $status],
						['id' => $row->id]
					);
					$ok = $res['status'] == 'ok';
				} else {
					$nextIdRow = $this->db
						->select('MAX(id) AS max_id', false)
						->from('shared_folder')
						->get()
						->row();
					$nextId = !empty($nextIdRow) ? ((int) $nextIdRow->max_id + 1) : 1;
					$res = $this->model_app->input('shared_folder', [
						'id' => $nextId,
						'nama' => 'stok_keluar_trigger_status',
						'isi' => (string) $status,
					]);
					$ok = $res['status'] == 'ok';
				}

				$data = $ok
					? [
						'status' => 200,
						'msg' => 'Pengaturan stok berhasil disimpan',
						'value' => $status,
						'label' => stok_keluar_trigger_status_label($status),
					]
					: ['status' => 400, 'msg' => 'Pengaturan stok gagal disimpan'];
			}

			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		
		private function cek_harga_beli($id)
		{
			$query_stok_masuk = "SELECT
			SUM(`stok_masuk`.`jumlah`) AS `total_masuk`,
			`bahan`.`harga_modal`
			FROM
			`bahan`
			INNER JOIN `stok_masuk` ON (`bahan`.`id` = `stok_masuk`.`id_bahan`)
			WHERE
			`stok_masuk`.`id_bahan` = $id
			GROUP BY
			`bahan`.`id`";
			
			$sql_masuk = $this->db->query($query_stok_masuk);
			$row_masuk = $sql_masuk->row();
			$harga_modal = $row_masuk->harga_modal * $row_masuk->total_masuk;
			$data = ['harga_beli'=>$harga_modal,'jumlah'=>$row_masuk->total_masuk];
			
			return (object)$data;
		}
		public function save_stok_keluar()
		{
			cek_nput_post('GET');
			simpan_demo('Simpan');
			cek_crud_akses(9);
			
			$type= $this->db->escape_str($this->input->post('type'));
			$bahan= ($this->db->escape_str($this->input->post('bahan')));
			$harga_beli= $this->db->escape_str($this->input->post('harga_beli'));
			$jumlah= $this->db->escape_str($this->input->post('jumlah'));
			$keterangan= $this->db->escape_str($this->input->post('keterangan'));
			
			$_data = array('id_bahan'=>$bahan,'jumlah'=>$jumlah,'create_date'=>date('Y-m-d H:i:s'),'ket'=>$keterangan);
			// print_r($_data);exit;
			if($type=='add'){
				///data baru
				$res= $this->model_app->input('stok_keluar',$_data);
				if($res['status']=='ok'){
					$data = array('status'=>200,'msg'=>'Data berhasil disimpan');
					}else{
					$data = array('status'=>400);
				}
			}
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		public function bahan()
		{
			
			$name= $this->db->escape_str($this->input->get('name'));
			$arr = ['title'=>$name];
			$sql = $this->model_app->view_like('bahan',$arr)->result();
			$response = [];
			foreach($sql AS $row){
				$response[] = array("id"=>$row->id, "name"=>$row->title);
			}
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($response));
		}
		public function save_laporan(){
			$title= $this->db->escape_str($this->input->post('title'));
			$tanggal= $this->db->escape_str($this->input->post('tanggal'));
			$tanggal = date_slash($tanggal);
			// print_r($_POST);exit;
			$skrg = date("Y-m-d H:i:s");
			//sebelum ke transaksi perpindahan data, lakukan perhitungan jumlah data awal untuk periode baru.
			$list = $this->model_data->load_cc();
			
			$plus = array();
			$arr_kirim = array();
			$arr_terima = array();
			
			$x = $this->model_stok->get_current_mutasi($list);
			foreach($x as $idm=>$stk){
				$arr_kirim[] = array(
				"id" => null,
				"id_bahan" => $idm,
				"jumlah" => $stk, 
				"create_date" => $tanggal,
				"ket" => "Data sisa periode",
				"stat" => 1
				);
			}
			// dump($arr_kirim);
			$plus = array();
			foreach($arr_kirim as $tes){
				if(!isset($plus[$tes['id_bahan']])){
					$plus[$tes['id_bahan']] = $tes['jumlah'];
				}
				else{
					$plus[$tes['id_bahan']] += $tes['jumlah'];
				}
			}
			
			
			$a = $this->model_stok->get_stok_keluar($list);
			foreach($a as $idmaster=>$stok){
				$pls = 0;
				if(isset($plus[$idmaster])){
					$pls = $plus[$idmaster];
				}
				
				$stok_akhir =  $pls - $stok;
				
				$arr_terima[] = array(
				"id" => null,
				"id_bahan" => $idmaster,
				"jumlah" => $stok_akhir,
				"create_date" => $skrg, 
				"ket" => "Data awal periode",
				"stat" => 1
				);
			}
			// dump($arr_terima);
			// print_r($arr_terima);exit;
			
			$id_project = $this->model_stok->get_last_id($title,$tanggal);
			$stok_masuk = query("INSERT INTO history_stok 
			SELECT NULL, 
			$id_project,
			'stok_masuk', 
			id_bahan, 
			create_date,
			jumlah, 
			ket, 
			stat 
			FROM 
			stok_masuk");
			
			$stok_keluar = query("INSERT INTO history_stok 
			SELECT NULL, 
			$id_project,
			'stok_keluar', 
			id_bahan, 
			create_date,
			jumlah, 
			ket, 
			stat 
			FROM 
			stok_keluar");
			
			
			$this->db->truncate("stok_masuk");
			$this->db->truncate("stok_keluar");
			
			
			$this->db->insert_batch("stok_masuk",$arr_kirim);
			$data = ['status'=>200,'msg'=>'Berhasil pindah ke periode baru'];
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
			// create_alert("Success","Berhasil pindah ke periode baru","history");
		}
		
		
		public function print_cek(){
			$id = $this->db->escape_str($this->input->post('id'));
			$data = array('status'=>200,'id'=>$id,'encrypt_url'=>encrypt_url($id));
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		
		
		public function get_harga(){
			$id = $this->db->escape_str($this->input->post('id'));
			$sql = $this->model_app->view_where('bahan',['id'=>$id])->row();
			$data = ['status'=>200,'harga'=>$sql->harga_modal];
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		public function cetak_stok_masuk($id=null){
			cek_crud_akses(8);
			$data['title'] = 'Data Stok Masuk | '.info()['title'];
			$type = $this->input->get('type');
			$data['info'] = info();
			$data['user'] = $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
			$data['owner'] = $this->model_app->view_where('tb_users', array('level' => 'owner'))->row()->app_secret;
			if($type=='pdf'){
				$data['logo'] = FCPATH.'uploads/'.info()['logo'];
				}else{
				$data['logo'] = base_url().'uploads/'.info()['logo'];
			}
			
			$data['id'] = $id;
			$conditions['where'] = array( 
            'id_bahan' => $id
			); 
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->getStokMasuk($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#DetailStok'; 
			$config['base_url']    = base_url('stok/cariDetailStokKeluar'); 
			$config['total_rows']  = $totalRec; 
			$config['per_page']    = $this->perPage; 
			$config['link_func']   = 'search_detail_stok'; 
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records 
			$conditions = array( 
			'limit' => $this->perPage 
			); 
			$conditions['where'] = array( 
            'id_bahan' => $id
			); 
			
			$data['detail'] = $this->model_data->getStokMasuk($conditions); 
			if($type=='pdf'){
				$this->load->library("pdf");
				$this->pdf->setPaper("A4", "portrait");
				$this->pdf->filename = "laporan_stok_masuk";
				$this->pdf->load_view("stok/cetak_laporan_stok_masuk", $data);
				}else{
				$this->load->view("stok/cetak_laporan_stok_masuk", $data);
			}
		}
		public function cetak_stok_keluar($id=null){
			cek_crud_akses(8);
			$data['title'] = 'Data Stok Keluar | '.info()['title'];
			$type = $this->input->get('type');
			$data['info'] = info();
			$data['user'] = $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
			$data['owner'] = $this->model_app->view_where('tb_users', array('level' => 'owner'))->row()->app_secret;
			if($type=='pdf'){
				$data['logo'] = FCPATH.'uploads/'.info()['logo'];
				}else{
				$data['logo'] = base_url().'uploads/'.info()['logo'];
			}
			
			$data['id'] = $id;
			$conditions['where'] = array( 
            'id_bahan' => $id
			); 
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->getStokKeluar($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#DetailStok'; 
			$config['base_url']    = base_url('stok/cariDetailStokKeluar'); 
			$config['total_rows']  = $totalRec; 
			$config['per_page']    = $this->perPage; 
			$config['link_func']   = 'search_detail_stok'; 
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records 
			$conditions = array( 
			'limit' => $this->perPage 
			); 
			$conditions['where'] = array( 
            'id_bahan' => $id
			); 
			
			$data['detail'] = $this->model_data->getStokKeluar($conditions); 
			if($type=='pdf'){
				$this->load->library("pdf");
				$this->pdf->setPaper("A4", "portrait");
				$this->pdf->filename = "laporan_keuangan_stok_keluar";
				$this->pdf->load_view("stok/cetak_laporan_stok_keluar", $data);
				}else{
				$this->load->view("stok/cetak_laporan_stok_keluar", $data);
			}
		}
		// Menampilkan laporan stok masuk dalam bentuk PDF
		public function print_stok_masuk() {
			$bulan = $this->input->post('bulan');
			$id = $this->input->post('id');
			
			$this->load->library('pdf');  // Memuat library TCPDF atau DOMPDF
			if($bulan){
				$periode = periode_bulan($bulan);
				// icon
				$data['waicon'] = ['color' => FCPATH.'assets/img/wa_icon.png', 'bw' => FCPATH.'assets/img/wa_icon_bw.png'];
				$data['mail'] = ['color' => FCPATH.'assets/img/gmail_icon.png', 'bw' => FCPATH.'assets/img/gmail_icon_bw.png'];
				$data['fbicon'] = ['color' => FCPATH.'assets/img/fb_icon.png', 'bw' => FCPATH.'assets/img/fb_icon_bw.png'];
				$data['igicon'] = ['color' => FCPATH.'assets/img/ig_icon.png', 'bw' => FCPATH.'assets/img/ig_icon_bw.png'];
				$data['logo'] = FCPATH.'uploads/'.info()['logo'];
				
				$data['favicon'] = base_url().'uploads/'.info()['favicon'];
				$data['info'] = info();
				$data['user']			= $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
				// Ambil data untuk laporan PDF
				$data['stok_per_bahan'] = $this->model_stok->get_stok_masuk_per_bahan_by_id($periode['bulan'], $periode['tahun'],$id);
				$data['total_stok'] = $this->model_stok->get_total_stok_masuk_by_id($periode['bulan'], $periode['tahun'],$id)->total_stok;
				
				// Ambil nama bulan
				$data['nama_bulan'] = date('F', mktime(0, 0, 0, $periode['bulan'], 10));
				$data['judul'] = 'MASUK';
				$this->pdf->setPaper('A4', 'potrait');
				$this->pdf->load_view('stok/laporan_stok_pdf', $data);
				
				$this->pdf->render();
				
				}else{
				$html = "<center><h1>BELUM ADA DATA</h1></center>";
				$this->pdf->loadHtml($html);
				$this->pdf->setPaper('A4', 'potrait');
				$this->pdf->render();
				$this->pdf->stream("Laporan_Stok_Masuk.pdf", array("Attachment" => 0));
			}
		}
		// Menampilkan laporan stok masuk dalam bentuk PDF
		public function print_stok_masuk_peritem($id) {
			
			$id = decrypt_url($id);
			
			$this->load->library('pdf');  // Memuat library TCPDF atau DOMPDF
			if($id){
				
				// icon
				$data['waicon'] = ['color' => FCPATH.'assets/img/wa_icon.png', 'bw' => FCPATH.'assets/img/wa_icon_bw.png'];
				$data['mail'] = ['color' => FCPATH.'assets/img/gmail_icon.png', 'bw' => FCPATH.'assets/img/gmail_icon_bw.png'];
				$data['fbicon'] = ['color' => FCPATH.'assets/img/fb_icon.png', 'bw' => FCPATH.'assets/img/fb_icon_bw.png'];
				$data['igicon'] = ['color' => FCPATH.'assets/img/ig_icon.png', 'bw' => FCPATH.'assets/img/ig_icon_bw.png'];
				$data['logo'] = FCPATH.'uploads/'.info()['logo'];
				
				$data['favicon'] = base_url().'uploads/'.info()['favicon'];
				$data['info'] = info();
				$data['user']			= $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
				// Ambil data untuk laporan PDF
				$data['row'] = $this->model_stok->get_stok_masuk_per_item_by_id($id);
				
				// Ambil nama bulan
				
				$data['judul'] = 'STOK MASUK';
				$this->pdf->setPaper('A5', 'landscape');
				$this->pdf->load_view('stok/laporan_stok_masuk_peritem', $data);
				// $this->load->view('stok/laporan_stok_masuk_peritem', $data);
				
				$this->pdf->render();
				
				}else{
				$html = "<center><h1>BELUM ADA DATA</h1></center>";
				$this->pdf->loadHtml($html);
				$this->pdf->setPaper('A5', 'landscape');
				$this->pdf->render();
				$this->pdf->stream("Laporan_Stok_Masuk.pdf", array("Attachment" => 0));
			}
		}
		// Menampilkan laporan stok masuk dalam bentuk PDF
		public function print_stok_keluar_peritem($id) {
			
			$id = decrypt_url($id);
			
			$this->load->library('pdf');  // Memuat library TCPDF atau DOMPDF
			if($id){
				
				// icon
				$data['waicon'] = ['color' => FCPATH.'assets/img/wa_icon.png', 'bw' => FCPATH.'assets/img/wa_icon_bw.png'];
				$data['mail'] = ['color' => FCPATH.'assets/img/gmail_icon.png', 'bw' => FCPATH.'assets/img/gmail_icon_bw.png'];
				$data['fbicon'] = ['color' => FCPATH.'assets/img/fb_icon.png', 'bw' => FCPATH.'assets/img/fb_icon_bw.png'];
				$data['igicon'] = ['color' => FCPATH.'assets/img/ig_icon.png', 'bw' => FCPATH.'assets/img/ig_icon_bw.png'];
				$data['logo'] = FCPATH.'uploads/'.info()['logo'];
				
				$data['favicon'] = base_url().'uploads/'.info()['favicon'];
				$data['info'] = info();
				$data['user']			= $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
				// Ambil data untuk laporan PDF
				$data['row'] = $this->model_stok->get_stok_kelusr_per_item_by_id($id);
				
				// Ambil nama bulan
				
				$data['judul'] = 'STOK KELUAR';
				$this->pdf->setPaper('A4', 'potrait');
				$this->pdf->load_view('stok/laporan_stok_keluar_peritem', $data);
				// $this->load->view('stok/laporan_stok_keluar_peritem', $data);
				
				$this->pdf->render();
				
				}else{
				$html = "<center><h1>BELUM ADA DATA</h1></center>";
				$this->pdf->loadHtml($html);
				$this->pdf->setPaper('A4', 'potrait');
				$this->pdf->render();
				$this->pdf->stream("Laporan_Stok_Keluar.pdf", array("Attachment" => 0));
			}
		}
		// Menampilkan laporan stok masuk dalam bentuk PDF
		public function print_semua_stok_masuk() {
			
			$this->load->library('pdf');  // Memuat library TCPDF atau DOMPDF
			
			$data['waicon'] = ['color' => FCPATH.'assets/img/wa_icon.png', 'bw' => FCPATH.'assets/img/wa_icon_bw.png'];
			$data['mail'] = ['color' => FCPATH.'assets/img/gmail_icon.png', 'bw' => FCPATH.'assets/img/gmail_icon_bw.png'];
			$data['fbicon'] = ['color' => FCPATH.'assets/img/fb_icon.png', 'bw' => FCPATH.'assets/img/fb_icon_bw.png'];
			$data['igicon'] = ['color' => FCPATH.'assets/img/ig_icon.png', 'bw' => FCPATH.'assets/img/ig_icon_bw.png'];
			$data['logo'] = FCPATH.'uploads/'.info()['logo'];
			
			$data['favicon'] = base_url().'uploads/'.info()['favicon'];
			$data['info'] = info();
			$data['user']			= $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
			// Ambil data untuk laporan PDF
			$data['stok_per_bahan'] = $this->model_stok->get_stok_masuk_per_bahan_by_date();
			$data['total_stok'] = $this->model_stok->get_total_stok_masuk_by_date()->total_stok;
			$data['nama_bulan'] = date('F', mktime(0, 0, 0, $periode['bulan'], 10));
			$data['judul'] = 'MASUK';
			$this->pdf->setPaper('A4', 'potrait');
			$this->pdf->load_view('stok/laporan_stok_masuk', $data);
			
			$this->pdf->render();
			$this->pdf->stream("Laporan_Stok_Masuk.pdf", array("Attachment" => 0));
		}
		// Menampilkan laporan stok masuk dalam bentuk PDF
		public function print_stok_keluar() {
			$bulan = $this->input->post('bulan');
			$id = $this->input->post('id');
			
			$this->load->library('pdf');  // Memuat library TCPDF atau DOMPDF
			if($bulan){
				$periode = periode_bulan($bulan);
				// icon
				$data['waicon'] = ['color' => FCPATH.'assets/img/wa_icon.png', 'bw' => FCPATH.'assets/img/wa_icon_bw.png'];
				$data['mail'] = ['color' => FCPATH.'assets/img/gmail_icon.png', 'bw' => FCPATH.'assets/img/gmail_icon_bw.png'];
				$data['fbicon'] = ['color' => FCPATH.'assets/img/fb_icon.png', 'bw' => FCPATH.'assets/img/fb_icon_bw.png'];
				$data['igicon'] = ['color' => FCPATH.'assets/img/ig_icon.png', 'bw' => FCPATH.'assets/img/ig_icon_bw.png'];
				$data['logo'] = FCPATH.'uploads/'.info()['logo'];
				
				$data['favicon'] = base_url().'uploads/'.info()['favicon'];
				$data['info'] = info();
				$data['user']			= $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
				// Ambil data untuk laporan PDF
				$data['stok_per_bahan'] = $this->model_stok->get_stok_keluar_per_bahan_by_id($periode['bulan'], $periode['tahun'],$id);
				$data['total_stok'] = $this->model_stok->get_total_stok_keluar_by_id($periode['bulan'], $periode['tahun'],$id)->total_stok;
				
				// Ambil nama bulan
				$data['nama_bulan'] = date('F', mktime(0, 0, 0, $periode['bulan'], 10));
				$data['judul'] = 'KELUAR';
				$this->pdf->setPaper('A4', 'potrait');
				$this->pdf->load_view('stok/laporan_stok_pdf', $data);
				
				$this->pdf->render();
				
				}else{
				$html = "<center><h1>BELUM ADA DATA</h1></center>";
				$this->pdf->loadHtml($html);
				$this->pdf->setPaper('A4', 'potrait');
				$this->pdf->render();
				$this->pdf->stream("Laporan_Stok_Masuk.pdf", array("Attachment" => 0));
			}
		}
		// Menampilkan laporan stok masuk dalam bentuk PDF
		public function print_semua_stok_keluar() {
			
			$this->load->library('pdf');  // Memuat library TCPDF atau DOMPDF
			
			$data['waicon'] = ['color' => FCPATH.'assets/img/wa_icon.png', 'bw' => FCPATH.'assets/img/wa_icon_bw.png'];
			$data['mail'] = ['color' => FCPATH.'assets/img/gmail_icon.png', 'bw' => FCPATH.'assets/img/gmail_icon_bw.png'];
			$data['fbicon'] = ['color' => FCPATH.'assets/img/fb_icon.png', 'bw' => FCPATH.'assets/img/fb_icon_bw.png'];
			$data['igicon'] = ['color' => FCPATH.'assets/img/ig_icon.png', 'bw' => FCPATH.'assets/img/ig_icon_bw.png'];
			$data['logo'] = FCPATH.'uploads/'.info()['logo'];
			
			$data['favicon'] = base_url().'uploads/'.info()['favicon'];
			$data['info'] = info();
			$data['user']			= $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
			// Ambil data untuk laporan PDF
			$data['stok_per_bahan'] = $this->model_stok->get_stok_keluar_per_bahan_by_date();
			$data['total_stok'] = $this->model_stok->get_total_stok_keluar_by_date()->total_stok;
			$data['nama_bulan'] = date('F', mktime(0, 0, 0, $periode['bulan'], 10));
			$data['judul'] = 'KELUAR';
			$this->pdf->setPaper('A4', 'potrait');
			$this->pdf->load_view('stok/laporan_stok_masuk', $data);
			
			$this->pdf->render();
			$this->pdf->stream("Laporan_Stok_Masuk.pdf", array("Attachment" => 0));
		}
		
	} //end CI_Controller																																																	
