<?php
	defined('BASEPATH') or exit('No direct script access allowed');
	use Brick\PhoneNumber\PhoneNumber;
	use Brick\PhoneNumber\PhoneNumberParseException;
	use Brick\PhoneNumber\PhoneNumberFormat;
	
	class Konsumen extends CI_Controller
	{
		public function __construct()
		{
			parent::__construct();
			cek_session_login();
			$this->load->model('model_konsumen','konsumen');
			$this->perPage = 10; 
			$this->title = info()['title'];
			$this->iduser = $this->session->idu;
		}
		
		public function index($id=null)
		{
			cek_menu_akses();
			cek_crud_akses(8);
			if(empty($id))
			{
				$data['title'] ="Data Konsumen | ".$this->title;
				// $conditions['where'] = array(
				// 'i.pos' => 'Y',
				// 'i.status' => 'simpan',
				// );
				$conditions['returnType'] = 'count'; 
				$totalRec = $this->model_data->getKonsumenOrder($conditions); 
				
				// Pagination configuration 
				$config['target']      = '#dataListKonsumen'; 
				$config['base_url']    = base_url('konsumen/ajaxKonsumen'); 
				$config['total_rows']  = $totalRec; 
				$config['per_page']    = $this->perPage; 
				$config['link_func']   = 'searchFilterKonsumen'; 
				// Initialize pagination library 
				$this->ajax_pagination->initialize($config); 
				
				// Get records 
				$conditions = array( 
				'limit' => $this->perPage 
				); 
				
				$conditions['search']['sortBy'] = 'ASC'; 
				$data['posts'] = $this->model_data->getKonsumenOrder($conditions); 
				// dump($data['posts']);
				$this->template->load('main/themes','konsumen/konsumen_data',$data);
			}
			else{
				$data['title'] = 'Detail konsumen | '.$this->title;
				$data['id'] = $id;
				
				// Get record count 
				$conditions['id'] = $id;
				$conditions['returnType'] = 'count'; 
				$totalRec = $this->model_data->getDetail($conditions); 
				
				// Pagination configuration 
				$config['target']      = '#detailKonsumen'; 
				$config['base_url']    = base_url('konsumen/ajaxDKonsumen'); 
				$config['total_rows']  = $totalRec; 
				$config['per_page']    = $this->perPage; 
				
				// Initialize pagination library 
				$this->ajax_pagination->initialize($config); 
				
				// Get records 
				$conditions = array( 
				'limit' => $this->perPage 
				); 
				$conditions['where'] = array(
				'invoice.id_konsumen' => $id
				);
				$data['result'] = $this->model_data->getDetail($conditions); 
				$this->template->load('main/themes','konsumen/detail_konsumen',$data);
			}
		}
		function ajaxKonsumen(){
			
			$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; 
			} 
			// dump($_POST);
			// Set conditions for search and filter 
			$keywords = $this->input->post('keywords'); 
			$sortBy = $this->input->post('sortBy'); 
			
			if(!empty($keywords)){ 
				$conditions['search']['keywords'] = $keywords; 
			} 
			if(!empty($sortBy)){ 
				$conditions['search']['sortBy'] = $sortBy; 
			} 
			// $conditions['where'] = array(
			// 'i.pos' => 'Y',
			// 'i.status' => 'simpan',
			// );
			// Get record count 
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->getKonsumenOrder($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#dataListKonsumen'; 
			$config['base_url']    = base_url('konsumen/ajaxKonsumen'); 
			$config['total_rows']  = $totalRec; 
			$config['per_page']    = $limit; 
			$config['link_func']   = 'searchFilterKonsumen'; 
			
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records 
			$conditions['start'] = $offset; 
			$conditions['limit'] = $limit;
			// $conditions['where'] = array(
			// 'konsumen.kunci' => 0
			// );
			unset($conditions['returnType']);
			
			$data['sortBy'] = $sortBy; 
			$data['posts'] = $this->model_data->getKonsumenOrder($conditions); 
			// dump($data['posts']);
			// Load the data list view 
			$this->load->view('konsumen/ajax-konsumen', $data, false); 
		}
		public function detail($id=null)
		{
			
			cek_crud_akses(8);
			$id = decrypt_url($id);
			if(empty($id))
			{
				
				$data['title'] ='Data Konsumen | '.$this->title;
				
				//$data['id'] =$id;
				$conditions['returnType'] = 'count'; 
				$totalRec = $this->model_data->getKonsumen($conditions); 
				
				// Pagination configuration 
				$config['target']      = '#dataListKonsumen'; 
				$config['base_url']    = base_url('konsumen/ajaxKonsumen'); 
				$config['total_rows']  = $totalRec; 
				$config['per_page']    = $this->perPage; 
				
				// Initialize pagination library 
				$this->ajax_pagination->initialize($config); 
				
				// Get records 
				$conditions = array( 
				'limit' => $this->perPage 
				); 
				$data['posts'] = $this->model_data->getKonsumen($conditions); 
				
				$this->template->load('main/themes','konsumen/konsumen',$data);
				}else{
				
				$data['title'] = 'Detail konsumen | '.$this->title;
				$data['id'] = $id;
				
				// Get record count 
				$conditions['id'] = $id;
				$conditions['returnType'] = 'count'; 
				$totalRec = $this->model_data->getDetail($conditions); 
				
				// Pagination configuration 
				$config['target']      = '#detailKonsumen'; 
				$config['base_url']    = base_url('konsumen/ajaxDKonsumen'); 
				$config['uri_segment']  = 4; 
				$config['total_rows']  = $totalRec; 
				$config['per_page']    = $this->perPage; 
				$config['link_func']   = 'FilterKonsumen'; 
				// Initialize pagination library 
				$this->ajax_pagination->initialize($config); 
				
				// Get records 
				$conditions = array( 
				'limit' => $this->perPage 
				); 
				$conditions['where'] = array(
				'invoice.id_konsumen' => $id,
				'invoice.pos' => 'Y'
				);
				$data['jenis'] = jenis_konsumen($id);
				$data['member'] = jenis_member($id);
				$data['result'] = $this->model_data->getDetail($conditions); 
				$this->template->load('main/themes','konsumen/detail_konsumen',$data);
			}
		}
		function ajaxDKonsumen(){
			
			cek_crud_akses(8);
			$idkon = $this->input->post('idkon'); 
			$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; 
			} 
			// Set conditions for search and filter 
			$keywords = $this->input->post('keywords'); 
			$periode= $this->db->escape_str($this->input->post('periode'));		
			$sortBy = $this->input->post('sortBy'); 
			
			$data['keterangan'] = '';
			
			if(!empty($keywords)){ 
				$conditions['search']['keywords'] = trim($keywords);
			} 
			
			if(!empty($sortBy)){ 
				$conditions['search']['sortBy'] = $sortBy; 
			} 
			if(!empty($limits)){ 
				$conditions['search']['limits'] = $limits; 
			}
			if(!empty($periode)){
				$date = date_ranges($periode);
				$dari = date_replace_slash($date['dari']);
				$sampai = date_replace_slash($date['sampai']);
				$conditions['search']['dari'] = $dari; 
				$conditions['search']['sampai'] = $sampai;
			}
			
			// Get record count 
			$conditions['id'] = $idkon;
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->getDetail($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#detailKonsumen'; 
			$config['base_url']    = base_url('konsumen/ajaxDKonsumen'); 
			$config['total_rows']  = $totalRec; 
			$config['per_page']    = $limit; 
			$config['link_func']   = 'FilterKonsumen'; 
			
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records 
			$conditions['start'] = $offset; 
			$conditions['limit'] = $limit;
			$conditions['where'] = array(
            'invoice.id_konsumen' => $idkon,
            'invoice.pos' => 'Y'
			);
			unset($conditions['returnType']); 
			
			$data['posts'] = $this->model_data->getDetail($conditions); 
			
			// Load the data list view 
			$this->load->view('konsumen/ajax-detail-konsumen', $data, false); 
		}
		
		public function detail_konsumen($id='')
		{
			
			cek_crud_akses(8);
			if(empty($id)){
				redirect('konsumen/konsumen_data/');
			}
			$data['title'] = 'Detail konsumen |' .$this->title;
			$data['id'] = $id;
			
			// Get record count 
			$conditions['id'] = $id;
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->getDetail($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#detailKonsumen'; 
			$config['base_url']    = base_url('konsumen/ajaxDKonsumen'); 
			$config['total_rows']  = $totalRec; 
			$config['per_page']    = $this->perPage; 
			
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records 
			$conditions = array( 
            'limit' => $this->perPage 
			); 
			$conditions['where'] = array(
            'invoice.id_konsumen' => $id,
			'invoice.pos' => 'Y'
			);
			$data['result'] = $this->model_data->getDetail($conditions); 
			$this->template->load('main/themes','konsumen/detail_konsumen',$data);
		}
		public function cari_konsumen(){
			
			cek_crud_akses(8);
			$data['title'] ='';
			$data['id'] = $this->input->post('id');
			$this->load->view('konsumen/cari_konsumen',$data);
		}
		public function cek_konsumen()
		{
			
			cek_crud_akses(8);
			$id = $this->db->escape_str($this->input->post('id'));
			$id = decrypt_url($id);
			$search=$this->model_app->view_where('konsumen',array('id'=>$id));
			if($search->num_rows()>0){
				$row =$search->row();
				$data = array(
				'id'=>encrypt_url($row->id),
				'nama'=>$row->nama,
				'panggilan'=>$row->panggilan,
				'jenis'=>(isset($row->jenis) ? $row->jenis : ''),
				'nohp'=>$row->no_hp,
				'alamat1'=>$row->alamat,
				'perusahaan'=>$row->perusahaan,
				'jenis_member'=>$row->jenis_member,
				'alamat2'=>$row->alamat_lembaga,
				'no_telp'=>$row->no_telp,
				'email'=>$row->email,
				'tampil'=>$row->tampil,
				'via'=>$row->referal,
				'boleh'=>$row->status,
				'max'=>$row->max_utang,
				'status'=>200
				);
				$this->output
				->set_content_type('application/json')
				->set_output(json_encode($data));
			}
		}
		
		public function _cek_telp($telp,$id) 
		{
			$full_phone = $this->input->post('full_phone');
			$full_phone_country = $this->input->post('full_phone_country');
			$number = PhoneNumber::parse($full_phone);
			$nomor_personal = $number->format(PhoneNumberFormat::NATIONAL);
			$nomor_personal = clean($nomor_personal);
			$cek = $this->model_data->cek_telp($id, $nomor_personal);
			// dump($cek);
			if ($cek == FALSE) 
			{
				$this->form_validation->set_message('_cek_telp', 'No. Hp sudah ada');
				return FALSE;
			}
			else 
			{
				return TRUE;
			}
		}
		
		
		public function update_konsumen()
		{
			
			simpan_demo("Simpan");
			cek_crud_akses(9,'json');
			$id = $this->db->escape_str($this->input->post('id_edit'));
			$id = decrypt_url($id);
			
			$config = array(
			array(
			'field' => 'nama_edit',
			'label' => 'Nama',
			'rules' => 'required',
			'errors' => array(
			'required' => '%s. Harus diisi',
			),
			),
			array(
			'field' => 'telepon_edit',
			'label' => 'No. HP',
			'rules' => 'required|trim|min_length[8]|max_length[20]|callback__cek_telp['.$id.']',
			'errors' => array(
			'required' => '%s. Harus di isi',
			'min_length' => '%s minimal 8 digit.',
			'max_length' => '%s maksimal 20 digit.'
			)
			),
			array(
			'field' => 'alamat_edit',
			'label' => 'Alamat',
			'rules' => 'required',
			'errors' => array(
			'required' => '%s. Harus diisi',
			),
			),
			
			array(
			'field' => 'via_edit',
			'label' => 'Referal',
			'rules' => 'required',
			'errors' => array(
			'required' => '%s. Harus diisi',
			),
			)
			);
			$json = array('hasil'=>'error');
			$this->form_validation->set_rules($config);
			if ($this->form_validation->run()){
				// dump($_POST);
				
				$nama_edit = $this->db->escape_str($this->input->post('nama_edit'));
				$panggilan_edit = $this->db->escape_str($this->input->post('panggilan_edit'));
				$telepon_edit = $this->db->escape_str($this->input->post('telepon_edit'));
				$alamat_edit = $this->db->escape_str($this->input->post('alamat_edit'));
				$via_edit = $this->db->escape_str($this->input->post('via_edit'));
				$status = $this->db->escape_str($this->input->post('status_edit'));
				$max_u = $this->db->escape_str($this->input->post('max_u'));
				$jenis = $this->db->escape_str($this->input->post('jenis_lembaga_edit'));
				$member = $this->db->escape_str($this->input->post('jenis_member_edit'));
				$perusahaan_edit = $this->db->escape_str($this->input->post('nama_perusahaan_edit'));
				$alamat_perusahaan = $this->db->escape_str($this->input->post('alamat_perusahaan_edit'));
				$no_telp = $this->db->escape_str($this->input->post('no_telp_edit'));
				$tampil_data = $this->db->escape_str($this->input->post('tampil_edit'));
				$cek_no = cek_no($telepon_edit);
				
				if($cek_no['akses']==0){
					$json = array('status'=>400,'msg'=>$cek_no['msg']);
					}else{
					$json = array();
					$cek =$this->model_app->view_where('konsumen',array('no_hp'=>$telepon_edit,'id !='=>$id));
					if($cek->num_rows() > 0)
					{
						$json = array('status'=>400,'msg'=>'No.hp sudah ada');
						}else{
						$_data = array(
						'nama'=>$nama_edit,
						'panggilan'=>$panggilan_edit,
						'no_hp'=>hp_3($telepon_edit),
						'jenis'=>$jenis,
						'jenis_member'=>$member,
						'alamat'=>$alamat_edit,
						'perusahaan'=>(isset($perusahaan_edit) ? $perusahaan_edit : ''),
						'alamat_lembaga'=>(isset($alamat_perusahaan) ? $alamat_perusahaan : ''),
						'no_telp'=>(isset($no_telp) ? $no_telp : ''),
						'referal'=>$via_edit,
						'tampil'=>$tampil_data,
						'status'=>$status,
						'max_utang'=>$max_u,
						'tgl_edit'=>date('Y-m-d H:i:s')
						);
						///panggil
						$search=$this->model_app->view_where('konsumen',array('id'=>$id));
						$row =$search->row();
						$catat = json_encode($_data);
						if($row->history==''){
							$catat = $catat;
							}else{
							$catat = $row->history.','.$catat;
						}
						$data = array(
						'nama'=>$nama_edit,
						'panggilan'=>$panggilan_edit,
						'no_hp'=>hp_3($telepon_edit),
						'jenis'=>$jenis,
						'jenis_member'=>$member,
						'alamat'=>$alamat_edit,
						'perusahaan'=>(isset($perusahaan_edit) ? $perusahaan_edit : ''),
						'alamat_lembaga'=>(isset($alamat_perusahaan) ? $alamat_perusahaan : ''),
						'no_telp'=>(isset($no_telp) ? $no_telp : ''),
						'referal'=>$via_edit,
						'tampil'=>$tampil_data,
						'status'=>$status,
						'max_utang'=>$max_u,
						'history'=>$catat
						);
						
						
						$res = $this->model_app->update('konsumen', $data, array("id"=>$id));
						if($res['status']=='ok'){
							$json = array('status'=>200,'msg'=>'Data berhasil diupdate','idmember'=>$member);
							}else{
							$json = array('status'=>400,'msg'=>'Data gagal diupdate','idmember'=>$member);
						}
					}
				}
				}else{
				$json = [
				'status'=>400,
				'title' =>'Update data',
				'msg'   =>validation_errors(),
				];
			}
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($json));
		}
		public function ajax_cari(){
			cek_crud_akses(8);
			if ( $this->input->is_ajax_request() )
			{
				$type = $this->db->escape_str($this->input->post('type'));
				if($_POST['type']=='konsumen_cari'){
					$row_num = $this->db->escape_str($this->input->post('row_num'));
					$name = $this->db->escape_str($this->input->post('name_startsWith'));
					$like = ['nama'=>$name];
					$no_hp = ['no_hp'=>$name];
					$no_telp = ['no_telp'=>$name];
					$result = $this->model_app->view_or_like('konsumen',$like,$no_hp,$no_telp);
					
					if($result->num_rows() > 0){
						$data = array();
						foreach ($result->result_array() as $row)
						{
							if($row['tampil']==1){
								$nama = $row['perusahaan'];
								$telp = $row['no_telp'];
								$alamat = $row['alamat_lembaga'];
								}else{
								$nama = $row['nama'];
								$telp = $row['no_hp'];
								$alamat = $row['alamat'];
							}
							$name = $nama.' - '.$telp.'|'.$row['id'].'|'.$nama.'|'.$alamat.'|'.$row['perusahaan'].'|'.$row['id_member'].'|'.$row_num;
							array_push($data, $name);
						}
						echo json_encode($data);
						}else{
						$data = array();
						
						echo json_encode($data);
					}
					}else{
					$data = array();
					
					echo json_encode($data);
				}	
				}else{
				$data = array();
				array_push($data, 'Request Gagal');
				echo json_encode($data);
			}
		}
		
		public function input_konsumen(){
			// dump($_POST);
			
			$config = array(
			array(
			'field' => 'nama_add',
			'label' => 'Nama',
			'rules' => 'required|trim|alpha_numeric_spaces|min_length[3]|max_length[30]',
			'errors' => array(
			'required' => '%s. Harus diisi',
			'min_length' => '%s. Minimal 3 karakter',
			'max_length' => '%s. Maksimal 3 karakter',
			'alpha_numeric_spaces' => '%s. hanya boleh berisi karakter alfanumerik dan spasi.',
			),
			),
			array(
			'field' => 'telepon_add',
			'label' => 'No. HP',
			'required|trim|min_length[8]|max_length[20]|is_unique[konsumen.no_hp]',
			'errors' => array(
			'required' => '%s. Harus di isi',
			'min_length' => '%s minimal 8 digit.',
			'max_length' => '%s maksimal 20 digit.',
			'is_unique'     => '%s sudah ada.'
			),
			),
			array(
			'field' => 'alamat_add',
			'label' => 'Alamat',
			'rules' => 'required|trim|min_length[5]|max_length[100]',
			'errors' => array(
			'required' => '%s. Harus diisi',
			'min_length' => '%s. Minimal 5 karakter',
			'max_length' => '%s. Maksimal 100 karakter',
			),
			),
			
			array(
			'field' => 'via_add',
			'label' => 'Referal',
			'rules' => 'required',
			'errors' => array(
			'required' => '%s. Harus diisi',
			),
			),
			array(
			'field' => 'jenis_lembaga_add',
			'label' => 'Jenis',
			'rules' => 'required',
			'errors' => array(
			'required' => '%s. Harus dipilih',
			),
			)
			);
			$data = array('hasil'=>'error');
			$this->form_validation->set_rules($config);
			if ($this->form_validation->run() != FALSE){
				$perusahaan_add = $this->db->escape_str($this->input->post('perusahaan_add'));
				$alamat_perusahaan = $this->db->escape_str($this->input->post('alamat_perusahaan_add'));
				$no_telp = $this->db->escape_str($this->input->post('no_telp_add'));
				$no_telp = hp_3($no_telp);
				$jenis_lembaga_add = $this->db->escape_str($this->input->post('jenis_lembaga_add'));
				$jenis_member_add = $this->db->escape_str($this->input->post('jenis_member_add'));
				$tampil = $this->db->escape_str($this->input->post('tampil_data'));
				$cek_no = cek_no($this->input->post('telepon_add'));
				
				$full_phone = $this->input->post('full_phone');
				$full_phone_country = $this->input->post('full_phone_country');
				$number = PhoneNumber::parse($full_phone);
				$nomor_personal = $number->format(PhoneNumberFormat::NATIONAL); // 044 668 18 00
				// echo $number->getRegionCode(); // GB
				
				$no_telp_add = $this->input->post('no_telp_add');
				if(!empty($no_telp_add)){
					$full_phone_add = $this->input->post('full_phone_add');
					$full_phone_add_country = $this->input->post('full_phone_add_country');
					$numbers = PhoneNumber::parse($full_phone_add);
					$nomor_perusahaan = $numbers->format(PhoneNumberFormat::NATIONAL); // 044 668 18 00
					}else{
					$nomor_perusahaan = '';
				}
				// echo $number->getRegionCode(); // GB
				
				$data = array('hasil'=>'');
				
				$search=$this->model_app->view_where('konsumen',array('no_hp'=>$this->input->post('telepon_add')));
				if($search->num_rows()>0){
					$data = array('hasil'=>'ada','telp'=>'No. HP Sudah ada');
					}else{
					$nama = strtolower($this->input->post('nama_add'));
					
					$idmember = autoNumbers(MEMBER,DIGIT_MEMBER);
					$unik = strtoupper(random_string('alnum',7));
					$data_arr = array(
					'id_member' => $idmember,
					'kode_unik' => $unik,
					'panggilan' =>  $this->input->post('panggilan_add'),
					'jenis' =>  $this->input->post('jenis_lembaga_add'),
					'jenis_member' =>  $this->input->post('jenis_member_add'),
					'nama' =>  ucwords($nama),
					'alamat' => $this->input->post('alamat_add'),
					'no_hp' => clean($nomor_personal),
					'perusahaan'=>(isset($perusahaan_add) ? $perusahaan_add : 'Personal'),
					'alamat_lembaga'=>(isset($alamat_perusahaan) ? $alamat_perusahaan : ''),
					'no_telp'=>(isset($nomor_perusahaan) ? $nomor_perusahaan : ''),
					'tampil' => $tampil,
					'referal' => $this->input->post('via_add'),
					'status' => $this->input->post('status_add'),
					'max_utang' => $this->input->post('max_u_add'),
					'tgl_daftar' => date('Y-m-d'),
					);
					$result = $this->model_app->input('konsumen', $data_arr); 
					if($result['status']=='ok'){
						$id_nya = $this->input->post('id_nya');
						if(!empty($id_nya)){
							$where = array('id_invoice' => $id_nya);
							$this->model_app->update('invoice', array("id_konsumen"=>$result['id']), $where);
						}
						if($tampil > 0){
							$nama = (isset($perusahaan_edit) ? $perusahaan_edit : 'Personal');
							$telp = (isset($nomor_perusahaan) ? $nomor_perusahaan : '');
							$alamat = (isset($alamat_perusahaan) ? $alamat_perusahaan : 'Personal');
							}else{
							$nama = ucwords($nama);
							$telp =  $full_phone;
							$alamat = 'Personal';
						}
						$data = array(
						'idk' => $result['id'],
						'id_member' => $jenis_member_add,
						'jenis_member' => member($jenis_member_add),
						'panggilan' =>  $this->input->post('panggilan_add'),
						'nama' =>  $nama,
						'telp' => $telp,
						'referal' => $this->input->post('via_add'),
						'alamat' => $alamat,
						'perusahaan' => '',
						'msg' => 'Data berhasil disimpan',
						'hasil' => 'sukses'
						);
						}else{
						$data = array('hasil'=>'error');
					}
				}
				
				}else{
				$data = array('hasil'=>'error','msg'=>validation_errors());
			}
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
			
		}
		public function cari_update(){
			
			$id = clean($this->input->post('id'));//id invoice
			$telepon = clean($this->input->post('telp'));
			$search = $this->model_app->view_where('konsumen', array('no_hp' => $telepon));
			if($search->num_rows()>0){
				$row =$search->row_array();
				$unik = strtoupper(random_string('alnum',5));
				$where = array('id_invoice' => $id);
				$res= $this->model_app->update('invoice', array("id_konsumen"=>$row['id']), $where);
				if($res==true){
					$this->model_app->update('konsumen', array("kode_unik"=>$unik), array('no_hp' => $telepon));
					if($row['tampil']==1){
						$nama = $row['perusahaan'];
						$telp =  $row['no_telp'];
						$alamat = $row['alamat_lembaga'];
						}else{
						$nama = $row['nama'];
						$telp = $row['no_hp'];
						$alamat = $row['alamat'];
					}
					$data = array('idnya' => $id,
					"idk"=> $row['id'],
					"id_member"=> $row['jenis_member'],
					'jenis_member' => member($row['jenis_member']),
					"nama"=> $nama,
					"telp"=> $telp,
					"alamat"=> $alamat,
					"perusahaan"=> $row['perusahaan'],
					"hasil"=> 'sukses'
					);	
				}
				}else{
				$data = array(0 => 'error');	
			}
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		public function cek_telp(){
			
			$full_phone = $this->input->post('telepon_add');
			$full_phone_country = $this->input->post('full_phone_country');
			$phoneNumber = PhoneNumber::parse($full_phone, $full_phone_country);
			// dump($_POST);
			if (! $phoneNumber->isValidNumber()) {
				$response = array('status'=>400,'msg'=>'Invalid Nomor');
				$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();
			}
			
			$telepon = clean($this->input->post('telepon_add'));
			$telepon = hp_3($telepon);
			
			$search = $this->model_app->view_where('konsumen', array('no_hp' => $telepon));
			if($search->num_rows()>0){
				$rows =$search->row_array();
				if($rows['tampil']==1){
					$nama = $rows['perusahaan'];
					$telp = $rows['no_telp'];
					$alamat = $rows['alamat_lembaga'];
					}else{
					$nama = $rows['nama'];
					$telp = $rows['no_hp'];
					$alamat = $rows['alamat'];
				}
				$data = array(0 => 'ada', 
				'idnya' => $rows['id'],
				'no_hp'=>$rows['no_hp'],
				'panggilan'=>$rows['panggilan'],
				'jenis'=>$rows['jenis'],
				'jenis_member'=>$rows['jenis_member'],
				'tampil_data'=>$rows['tampil'],
				'nama'=>$nama,
				'alamat'=>$alamat,
				'perusahaan'=>$rows['perusahaan'],
				'alamat_perusahaan'=>$rows['alamat_lembaga'],
				'no_telp'=>$telp,
				'reff'=>$rows['referal'],
				'kodeunik'=>$rows['kode_unik']);
				}else{
				$data = array(0 => 'add','msg'=>$this->input->post('telepon_add'));	
			}
			
			echo json_encode($data);
		}
		
		public function update_konsumen_cari(){
			if ( $this->input->is_ajax_request() )
			{
				$id_invoicecari  = $this->input->post('id_invoicecari');
				$id_konsumencari = $this->input->post('id_konsumencari');
				$id_member       = $this->input->post('id_member');
				$nama            = $this->input->post('nama_cari');
				$telp            = $this->input->post('caritlp');
				$alamat          = $this->input->post('alamat_cari');
				$perusahaan      = $this->input->post('perusahaan_cari');
				$exp             = explode('-',$telp);
				
				$cek_bayar  = $this->model_cek->sum_bayar_konsumen(['`invoice`.`id_invoice`'=>$id_invoicecari,'konsumen.id'=>$id_konsumencari]);
				$cek_detail = $this->model_cek->sum_detail_konsumen(['`invoice`.`id_invoice`'=>$id_invoicecari,'konsumen.id'=>$id_konsumencari]); 
				$cek        = $cek_detail->total - $cek_bayar->total;
				$totpiutang = 0;
				$cek_member = cek_member($id_konsumencari);
				if($cek > 0){
					if($cek_detail->oto==1 AND $cek_detail->max_utang >0 OR $cek_detail->max_utang >0 AND $cek_detail->status !='batal' OR $cek_detail->oto == 0 AND $cek_detail->total_bayar ==0 AND $cek_detail->status=='baru' OR $cek_detail->statusutang ==1){
						
						$data = array(
						'id' => $id_invoicecari,
						'jenis_member' => member($cek_member),
						'id_member' => $cek_member,
						'idk' => $id_konsumencari,
						'nama' => $nama,
						'telp' =>  phone_number($exp[1]),
						'alamat' => $alamat,
						'perusahaan' => $perusahaan,
						'hasil' => 'sukses',
						'error' => 'Data berhasil di input'
						);	
						$update = $this->model_app->update('invoice',['id_konsumen'=>$id_konsumencari],['id_invoice'=>$id_invoicecari]);
						if($update['status']=='ok'){
							echo json_encode($data);
							}else{
							$data = array(
							'id' => '',
							'jenis_member' => '',
							'id_member' => '',
							'nama' => '',
							'telp' => '',
							'alamat' => '',
							'perusahaan' => '',
							'hasil' => 'gagal',
							'error' => 'Data gagal di input'
							);	
							
							echo json_encode($data);
						}
						}else{
						
						$tgl        = tgl_indo($cek_detail->tgl_trx,false);
						$namakon    = $cek_detail->nama;
						$piutang    = $cek;
						$id_invoice = $cek_detail->id_invoice;
						$totpiutang = $totpiutang + $piutang;
						
						$data = array(
						'id' => $id_konsumencari,
						'totalp' => rp($totpiutang),
						'nama' => $namakon,
						'tgl' => $tgl,
						'hasil' => 'ada',
						'error' => $namakon.' Masih ada piutang sebesar Rp.'.rp($totpiutang));	
						echo json_encode($data);
					}
					}else{
					
					$data = array(
					'id' => $id_invoicecari,
					'jenis_member' => member($cek_member),
					'id_member' => $cek_member,
					'idk' => $id_konsumencari,
					'nama' => $nama,
					'telp' => phone_number($exp[1]),
					'alamat' => $alamat,
					'perusahaan' => $perusahaan,
					'hasil' => 'sukses',
					'error' => 'Data berhasil di input'
					);	
					$update = $this->model_app->update('invoice',['id_konsumen'=>$id_konsumencari],['id_invoice'=>$id_invoicecari]);
					if($update['status']=='ok'){
						echo json_encode($data);
						}else{
						$data = array(
						'id' => '',
						'jenis_member' => '',
						'id_member' => '',
						'nama' => '',
						'telp' => '',
						'alamat' => '',
						'perusahaan' => '',
						'hasil' => 'gagal',
						'error' => 'Data gagal di input'
						);	
						
						echo json_encode($data);
					}
				}
			}
		}
		public function konsumen(){
			
			$conditions['where'] = array(
			'kunci' => '0'
			); 
			$data = $this->model_app->counter('konsumen',$conditions);
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		
		public function cari(){
			
			$search=  $this->input->post('search');
			$query = $this->model_data->getdata($search);
			echo json_encode ($query);
		}
		
		
		public function data_konsumen($id)
		{
			cek_session_login();
			$data['id'] =$id;
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->getKonsumen($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#dataListKonsumen'; 
			$config['base_url']    = base_url('konsumen/ajaxKonsumen'); 
			$config['total_rows']  = $totalRec; 
			$config['per_page']    = $this->perPage; 
			
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records 
			$conditions = array( 
			'limit' => $this->perPage 
			); 
			$data['posts'] = $this->model_data->getKonsumen($conditions); 
			// dump($data['posts']);
			$this->load->view('konsumen/konsumen',$data);
		}
		
		public function jenis_lembaga(){
			$status = $this->input->post('status');
			if($status=='add'){
				}else{
			}
			$result = $this->model_app->view_where('jenis_lembaga',array('pub'=>'0'));
			$data = array();
			foreach ($result->result() as $row)
			{
				$data[] = array("id"=>$row->id,"name"=>$row->title);
			}
			
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		
		public function member()
		{
			cek_menu_akses();
			$data['title'] = 'Jenis member |' .$this->title;
			$data['judul'] ='Jenis member';
			$data['diskon_member_aktif'] = $this->is_diskon_member_aktif();
			
			$this->template->load('main/themes','konsumen/member',$data);
		}
		
		public function data_member()
		{
			$data['record'] = $this->model_app->view_ordering('member','id','DESC');
			$this->load->view('konsumen/data_member',$data);
		}
		
		public function edit_member(){
			$id= $this->db->escape_str($this->input->post('id'));
			if($id>0){
				$where = array('id' => $id);
				$row = $this->model_app->edit('member',$where)->row_array();
				$data = array('id'=>$id,'title'=>$row['title'],'diskon'=>$row['potongan_diskon'],'aktif'=>$row['status']);
				}else{
				$data = array('id'=>0,'title'=>"",'diskon'=>'',"aktif"=>"");
			}
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		public function load_member(){
			$id= $this->db->escape_str($this->input->post('id'));
			
			$where = array('`konsumen`.`id`' => $id,'`member`.`status`'=>1);
			$sql = $this->model_app->join_where('title,potongan_diskon','member','konsumen','id','jenis_member',$where);
			if($sql->num_rows() >0 ){
				$data = array('id'=>$id,'title'=>$sql->row()->title,'diskon'=>$sql->row()->potongan_diskon);
				}else{
				$data = array('id'=>0,'title'=>"Member Biasa",'diskon'=>0);
			}
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		
		public function save_member()
		{
			cek_nput_post('GET');
			simpan_demo('Simpan');
			$id    = $this->db->escape_str($this->input->post('id'));
			$type  = $this->db->escape_str($this->input->post('type'));
			$title = $this->db->escape_str($this->input->post('title'));
			$diskon = (float) $this->input->post('diskon');
			$diskon = max(0, min(100, $diskon));
			$aktif = $this->db->escape_str($this->input->post('aktif'));
			
			if($type=='add'){
				$_data = array('title'=>$title,'potongan_diskon'=>$diskon,'status'=>$aktif);
				$insert = $this->model_app->input('member',$_data);
				if($insert['status']=='ok'){
					$data = array('status'=>200,'msg'=>'Data berhasil diinput');
					}else{
					$data = array('status'=>400);
				}
			}
			if($id > 0 AND $type=='edit'){
				$_data = array('title'=>$title,'potongan_diskon'=>$diskon,'status'=>$aktif);
				$res=  $this->model_app->update('member',$_data,array('id'=>$id));
				///data update
				if($res['status']=='ok'){
					$data = array('status'=>200,'msg'=>'Data berhasil update');
					}else{
					$data = array('status'=>400);
				}
			}
			$this->output
			->set_content_type('application/json')
				->set_output(json_encode($data));
		}

		public function save_diskon_member_status()
		{
			cek_nput_post('GET');
			simpan_demo('Simpan');
			$aktif = $this->input->post('aktif') == '1' ? '1' : '0';
			$ok = $this->save_diskon_member_setting($aktif);
			$this->output
				->set_content_type('application/json')
				->set_output(json_encode(array(
					'status' => $ok ? 200 : 400,
					'aktif' => (int) $aktif,
					'msg' => $ok ? 'Pengaturan diskon level member berhasil disimpan' : 'Pengaturan gagal disimpan',
				)));
		}

		private function is_diskon_member_aktif()
		{
			if (!$this->db->table_exists('shared_folder')) return false;
			$row = $this->db->select('isi')->from('shared_folder')
				->where('nama', 'diskon_level_member_aktif')->limit(1)->get()->row_array();
			return $row && isset($row['isi']) && (string) $row['isi'] === '1';
		}

		private function save_diskon_member_setting($value)
		{
			if (!$this->db->table_exists('shared_folder')) return false;
			$exists = $this->db->select('id')->from('shared_folder')
				->where('nama', 'diskon_level_member_aktif')->limit(1)->get()->row_array();
			if ($exists) {
				return (bool) $this->db->where('nama', 'diskon_level_member_aktif')
					->update('shared_folder', array('isi' => (string) $value));
			}
			$next = $this->db->select('COALESCE(MAX(id),0)+1 AS id', false)->from('shared_folder')->get()->row_array();
			return (bool) $this->db->insert('shared_folder', array(
				'id' => (int) $next['id'], 'nama' => 'diskon_level_member_aktif', 'isi' => (string) $value,
			));
		}
		
		public function jenis_member(){
			$status = $this->input->post('status');
			if($status=='add'){
				}else{
			}
			$result = $this->model_app->view_where('member',['status'=>1]);
			$data = array();
			foreach ($result->result() as $row)
			{
				$data[] = array("id"=>$row->id,"name"=>$row->title);
			}
			
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		public function delete_konsumen()
		{
			cek_nput_post('GET');
			simpan_demo("Hapus");
			$id = decrypt_url($this->input->post('id',TRUE));
			$cek_order = $this->cek_order($id);
			if($cek_order===false){
				$cek = $this->model_app->view_where('konsumen', ['id'=>$id]);
				if($cek->num_rows() > 0)
				{
					$row = $cek->row();
					if($row->id >1){
						$delete = $this->model_app->hapus('konsumen', ['id'=>$id]);
						if($delete['status']=='ok')
						{
							$arr = ['status'=>true,'msg'=>'Sukses'];
							}else{
							$arr = ['status'=>false,'msg'=>'Gagal'];
						}
						
						}else{
						$arr = ['status'=>false,'msg'=>'Data tidak dapat dihapus'];
					}
					}else{
					$arr = ['status'=>false,'msg'=>'Data tidak ditemukan'];
				}
				
				}else{
				$arr = ['status'=>false,'msg'=>'Gagal'];
			}
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($arr));
		}
		
		private function cek_order($id)
		{
			$cek = $this->model_app->view_where('invoice', ['id_konsumen'=>$id]);
			if($cek->num_rows() ==0){
				return false;
			}
		}
		
		public function print_detail(){			
			
			
			$periode  = $this->db->escape_str($this->input->post('periode'));			
			$id_user = $this->db->escape_str($this->input->post('id_user'));
			$limits = $this->db->escape_str($this->input->post('limits'));
			// dump($_POST);
			if(empty($_POST)){
				$data['heading'] = 'Halaman error';				
				$data['message'] = 'Data tidak ditemukan';				
				$this->load->view('errors/404',$data);
				}else{
				if(!empty($periode)){
					$date = date_ranges($periode);
					$dari = date_replace_slash($date['dari']);
					$sampai = date_replace_slash($date['sampai']);
					$condition['search']['dari'] = $dari; 
					$condition['search']['sampai'] = $sampai;
					}else{
					$dari = day_ymd();
					$sampai = day_ymd();
				}
				
				$condition['where'] = ['invoice.id_konsumen' => $id_user];
				$condition['search']['dari'] = $dari;
				$condition['search']['sampai'] = $sampai;
				$condition['search']['sortBy'] = 'ASC';
				$condition['limit'] = max(1, (int) $limits);
				$search = $this->model_data->get_harian($condition);

				if(!empty($search)){
					$data['dari'] = $dari;		
					$data['sampai'] = $sampai;		
					$data['title'] = 'Rincian Penjualan Pelanggan | '.$this->title;
					$data['posts'] = $search;

					$nama_dari = (!empty($dari) && strtotime($dari)) ? date('Ymd', strtotime($dari)) : date('Ymd');
					$nama_sampai = (!empty($sampai) && strtotime($sampai)) ? date('Ymd', strtotime($sampai)) : date('Ymd');

					$this->load->library('pdf');				
					$this->pdf->setPaper('A4', 'landscape');				
					$this->pdf->filename = 'Rincian_Penjualan_Pelanggan_'.$nama_dari.'_'.$nama_sampai.'.pdf';
					$this->pdf->load_view('pembukuan/export_omset_pdf', $data);
					}else{				
					$data['heading'] = 'Halaman error';				
					$data['message'] = 'Data tidak ditemukan';				
					$this->load->view('errors/html/error_404',$data);				
				}	
			}
		}
		public function grafik() {
			
			$data['sales_growth'] = $this->konsumen->get_buyers_comparisonz();
			// dump($data);
			$this->load->view('konsumen/buyers_comparison_view', $data);
		}
		
		public function grafiks() {
			
			$data['arrivals'] = $this->konsumen->get_buyers_comparison_by_months();
			dump($data);
			$this->load->view('konsumen/consumer_arrivals_view', $data);
		}
		
		public function index_baru() {
			$data['comparison'] = $this->konsumen->get_buyers_comparison();
			// $this->output
			// // ->set_content_type('application/json')
			// ->set_output(json_encode($data['comparison']));
			// print json_encode($data['comparison']);
			// dump($data);
			$this->load->view('konsumen/buyers_comparison_view', $data);
		}
		
		public function index_bulan() {
			$month = 10;
			$year = year();
			$data['comparison'] = $this->konsumen->get_buyers_comparison_by_month($year);
			$this->load->view('konsumen/buyers_comparison_view_month', $data);
		}
		public function index_day() {
			$month = 10;
			$year = year();
			$data['comparison'] = $this->konsumen->get_buyers_comparison_by_day($month, $year);
			$this->load->view('konsumen/buyers_comparison_view_day', $data);
		}
		
		public function index_buyer() {
			$month = 10;
			$year = year();
			$data['buyers_data'] = $this->konsumen->get_buyers_data($month,$year);
			$this->load->view('konsumen/dashboard_view', $data);
		}
		
		public function index_filter() {
			$month = $this->input->get('month') ?? date('m'); // Default to current month
			$year = $this->input->get('year') ?? date('Y'); // Default to current year
			
			$data['buyers_data'] = $this->konsumen->get_daily_buyers_data($month, $year);
			
			// Format the date to Indonesian
			foreach ($data['buyers_data'] as &$row) {
				$row['transaction_date'] = date("d F Y", strtotime($row['transaction_date'])); // e.g., "01 Januari 2023"
			}
			
			// Prepare month and year for filter
			$data['months'] = range(1, 12);
			$data['years'] = range(date('Y') - 2, date('Y')); // Show last 5 years
			
			$this->load->view('konsumen/dashboard_view_filter', $data);
		}
	}																																																						
