<?php
	defined('BASEPATH') or exit('No direct script access allowed');
	
	class Pembayaran extends CI_Controller
	{
		public function __construct()
		{
			parent::__construct();
			// cek_tabel();
			cek_session_login();
			$this->load->model('Masterdata_model','masterdata');
			$this->iduser = $this->session->idu;
			$this->title = info()['title']; 
		}
		
		public function jenis()
		{
			cek_menu_akses();
			$data['title'] = 'Jenis Pembayaran | '.$this->title;
			// $this->db->where_in('kelompok_akun.id_kelompok_akun',1);
			$data['dt_akun'] = $this->masterdata->getAccountData();
			$this->template->load('main/themes','pembayaran/pembayaran',$data);
		}
		public function rekening()
		{
			cek_menu_akses();
			$data['title'] = 'Rekening Bank | '.$this->title;
			$this->db->where_in('kelompok_akun.id_kelompok_akun', 1);
			$data['dt_akun'] = $this->masterdata->getAccountData();
			$this->template->load('main/themes','pembayaran/rekening',$data);
		}
		public function jenis_pembayaran(){
			$result = $this->model_app->view_where('jenis_bayar',array('kunci'=>1));
			$data = array();
			foreach ($result->result() as $row)
			{
				$data[] = array("id"=>$row->id,"name"=>$row->nama_bayar);
			}
			
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
			
		}
		public function jenis_pembayaran_pengeluaran(){
			$result = $this->model_app->view_where('jenis_bayar',array('publish'=>'Y'));
			$data = array();
			foreach ($result->result() as $row)
			{
				$data[] = array("id"=>$row->id,"name"=>$row->nama_bayar);
			}
			
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
			
		}
		
		public function jenis_pembayaran_pembelian($id=''){
			$arr['a'] = ['id_bayar'=>'','id_akun'=>'','title'=>'','tgl'=>'']; 
			if(!empty($id)){
				$cek = $this->model_app->view_where('pembelian',array('id_pembelian'=>$id))->row();
				$arr['a'] = ['id_bayar'=>$cek->id_bayar,'id_akun'=>getIdAkun($cek->id_bayar),'title'=>getNameKas($cek->id_kas),'tgl'=>tgl_ambil($cek->tgl_jatuhtempo)]; 				
			}
			$result = $this->model_app->view_where('jenis_bayar',array('publish'=>'Y'));
			$data = array();
			foreach ($result->result() as $row)
			{
				$data['b'][] = array("id"=>$row->id,"name"=>$row->nama_bayar);
			}
			$data = array_merge($arr,$data);
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
			
		}
		public function jenis_pembayaran_piutang(){
			$result = $this->model_app->view_where('jenis_bayar',array('publish'=>'Y','kunci'=>0));
			$data = array();
			foreach ($result->result() as $row)
			{
				$data[] = array("id"=>$row->id,"name"=>$row->nama_bayar);
			}
			
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
			
		}
		public function jenis_kas(){
			$result = $this->model_app->view_where('jenis_kas',array('kunci'=>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 tujuan_kas(){
			$id= $this->db->escape_str($this->input->post('id'));
			if(!empty($id)){
				$result = $this->model_app->view_where('jenis_kas',array('id!='=>$id,'kunci'=>0));
				$data = array();
				foreach ($result->result() as $row)
				{
					$data[] = array("id"=>$row->id,"name"=>$row->title);
				}
				}else{
				$data[] = array("id"=>0,"name"=>'Pilih','msg'=>'disabled');
			}
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		public function data_pembayaran()
		{
			// $data['record'] = $this->model_app->view_ordering('jenis_bayar','id','DESC');
			$data['record'] = $this->model_app->view_join_where('akun','jenis_bayar','id_akun',['publish'=>'Y'],'id','ASC');
			$this->load->view('pembayaran/data_jenis',$data);
		}
		public function data_rekening()
		{
			$data['record'] = $this->model_app->view_where_ordering('rekening_bank',array(),'id','DESC')->result();
			$this->load->view('pembayaran/data_rekening',$data);
		}

		// =========================
		// HAPUS REKENING BANK / MERCHANT (CEK DIPAKAI + CEK SALDO)
		// =========================
		public function delete_rekening()
		{
			simpan_demo('Hapus');

			$id = (int) $this->input->post('id');
			if ($id <= 0) {
				return $this->output
					->set_content_type('application/json')
					->set_output(json_encode(['status' => 422, 'msg' => 'ID tidak valid']));
			}

			// Ambil rekening (untuk dapat id_akun)
			$rek = $this->db->get_where('rekening_bank', ['id' => $id])->row_array();
			if (empty($rek)) {
				return $this->output
					->set_content_type('application/json')
					->set_output(json_encode(['status' => 404, 'msg' => 'Data rekening tidak ditemukan']));
			}

			$id_akun = (int) ($rek['id_akun'] ?? 0);

			$reasons = [];

			// =====================================================
			// 1) CEK SALDO (kalau masih ada saldo -> BLOK HAPUS)
			// =====================================================
			if ($id_akun > 0) {
				$saldo = (float)$this->_saldoAkun($id_akun);
				if (abs($saldo) > 0.00001) {
					$reasons[] = 'Di dalam rekening ini masih terdapat saldo ' . $this->_fmtRp($saldo);
				}
			}

			// =====================================================
			// 2) CEK DIPAKAI DI INVOICE
			//    bayar_invoice_detail.id_sub_bayar = rekening_bank.id_akun
			// =====================================================
			if ($id_akun > 0 && $this->db->table_exists('bayar_invoice_detail')) {
				$q = $this->db->select('1', false)
					->from('bayar_invoice_detail')
					->where('id_sub_bayar', $id_akun);

				if ($this->db->field_exists('hapus', 'bayar_invoice_detail')) {
					$q->where('hapus', 0);
				}

				if ($q->limit(1)->get()->num_rows() > 0) {
					$reasons[] = 'Rekening sedang digunakan di Invoice';
				}
			}

			// =====================================================
			// 3) CEK DIPAKAI DI KAS KELUAR
			//    kas_keluar.id_akun = rekening_bank.id_akun
			// =====================================================
			if ($id_akun > 0 && $this->db->table_exists('kas_keluar') && $this->db->field_exists('id_akun', 'kas_keluar')) {
				$q = $this->db->select('1', false)
					->from('kas_keluar')
					->where('id_akun', $id_akun);

				if ($this->db->field_exists('hapus', 'kas_keluar')) {
					$q->where('hapus', 0);
				}

				if ($q->limit(1)->get()->num_rows() > 0) {
					$reasons[] = 'Rekening sedang digunakan di Kas Keluar';
				}
			}

			// =====================================================
			// 4) CEK DIPAKAI DI KAS MASUK / MUTASI
			//    kas_masuk.id_sub_bayar = rekening_bank.id  (khusus bank)
			//    mutasi biasanya id_bayar = 0
			// =====================================================
			if ($this->db->table_exists('kas_masuk') && $this->db->field_exists('id_sub_bayar', 'kas_masuk')) {

				// Mutasi (id_bayar=0)
				if ($this->db->field_exists('id_bayar', 'kas_masuk')) {
					$qm = $this->db->select('1', false)
						->from('kas_masuk')
						->where('id_sub_bayar', $id)
						->where('id_bayar', 0);

					if ($this->db->field_exists('hapus', 'kas_masuk')) {
						$qm->where('hapus', 0);
					}

					if ($qm->limit(1)->get()->num_rows() > 0) {
						$reasons[] = 'Rekening sedang digunakan di Mutasi';
					}

					// Kas Masuk (selain mutasi)
					$qk = $this->db->select('1', false)
						->from('kas_masuk')
						->where('id_sub_bayar', $id)
						->where('id_bayar !=', 0);

					if ($this->db->field_exists('hapus', 'kas_masuk')) {
						$qk->where('hapus', 0);
					}

					if ($qk->limit(1)->get()->num_rows() > 0) {
						$reasons[] = 'Rekening sedang digunakan di Kas Masuk';
					}
				} else {
					// fallback kalau id_bayar tidak ada: tetap blok kalau pernah muncul
					$qf = $this->db->select('1', false)
						->from('kas_masuk')
						->where('id_sub_bayar', $id);

					if ($this->db->field_exists('hapus', 'kas_masuk')) {
						$qf->where('hapus', 0);
					}

					if ($qf->limit(1)->get()->num_rows() > 0) {
						$reasons[] = 'Rekening sedang digunakan di Kas Masuk/Mutasi';
					}
				}
			}

			// Kalau ada alasan apapun -> BLOK HAPUS
			if (!empty($reasons)) {
				return $this->output
					->set_content_type('application/json')
					->set_output(json_encode([
						'status' => 409,
						'msg'    => implode('. ', $reasons) . '.'
					]));
			}

			// Aman untuk dihapus
			$res = $this->model_app->delete('rekening_bank', ['id' => $id]);
			$out = $res
				? ['status' => 200, 'msg' => 'Data berhasil dihapus']
				: ['status' => 400, 'msg' => 'Data gagal dihapus'];

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




		
		
		public function get_data_bayar(){
			$id= $this->db->escape_str($this->input->post('id'));
			if($id>0){
				$where = array('id' => $id);
				$row = $this->model_app->edit('jenis_bayar',$where)->row_array();
				$data = $row;
				}else{
				$data = [];
			}
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		function get_data(){
			$id= $this->db->escape_str($this->input->post('id'));
			if($id>0){
				$where = array('id' => $id);
				$row = $this->model_app->edit('rekening_bank',$where)->row_array();
				$data = $row;
				}else{
				$data = [];
			}
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		
		function get_rekening(){
			$type= $this->db->escape_str($this->input->post('type'));
			if($type=='cari'){
				$where = array('publish' => 'Y');
				$result = $this->model_app->view_where('rekening_bank',$where)->result();
				foreach($result AS $row){
					$data[] = ['id'=>$row->id,'name'=>$row->nama_bank];
				}
				}else{
				$data = [];
			}
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		
		
		public function save_data_bayar()
		{
			simpan_demo('Simpan');
			$id      = $this->db->escape_str($this->input->post('id'));
			$type    = $this->db->escape_str($this->input->post('type'));
			$id_akun    = $this->db->escape_str($this->input->post('id_akun'));
			$judul   = $this->db->escape_str($this->input->post('cara_bayar'));
			$publish = $this->db->escape_str($this->input->post('publish'));
			
			
			$_data   = array('id_akun'=>$id_akun,'nama_bayar'=>$judul,'publish'=>$publish);
			
			$data = [];
			if($type=='edit'){
				///data update
				$res=  $this->model_app->update('jenis_bayar',$_data,array('id'=>$id));
				if($res==true){
					$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_data()
		{
			simpan_demo('Simpan');
			$id      = $this->db->escape_str($this->input->post('id'));
			$type    = $this->db->escape_str($this->input->post('type'));
			$id_akun    = $this->db->escape_str($this->input->post('id_akun'));
			$judul   = $this->db->escape_str($this->input->post('cara_bayar'));
			$no_rek  = $this->db->escape_str($this->input->post('nomor'));
			$pemilik = $this->db->escape_str($this->input->post('pemilik'));
			$inisial = $this->db->escape_str($this->input->post('inisial'));
			$footerin = $this->db->escape_str($this->input->post('footerin'));
			$publish = $this->db->escape_str($this->input->post('publish'));
			
			$_data   = array('id_akun'=>$id_akun,'nama_bank'=>$judul,'nomor_rekening'=>$no_rek,'pemilik'=>$pemilik,'publish'=>$publish,'inisial'=>$inisial,'footer_invoice'=>$footerin);
			if(!empty($id)){
				$data = [];
				if($type=='edit'){
					///data update
					$res=  $this->model_app->update('rekening_bank',$_data,array('id'=>$id));
					if($res['status']=='ok'){
						$data = array('status'=>200,'msg'=>'Data berhasil update');
						}else{
						$data = array('status'=>400);
					}
				}
				}else{
				if($type=='add'){
					$input=  $this->model_app->input('rekening_bank',$_data);
					if($input['status']=='ok'){
						$data = array('status'=>200,'msg'=>'Data berhasil update');
						}else{
						$data = array('status'=>400);
					}
					}else{
					$data = array('status'=>400);
				}
			}
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}

		// =========================
		// HELPERS (SALDO AKUN + FORMAT RP)
		// =========================
		private function _saldoAkun($idAkun){
			$idAkun = (int)$idAkun;
			if($idAkun <= 0) return 0;
			if(!$this->db->table_exists('jurnal_detail')) return 0;

			$debit = (float)$this->db->select_sum('nilai','t')
				->get_where('jurnal_detail',['id_akun'=>$idAkun,'id_perkiraan'=>1])
				->row()->t;

			$kredit = (float)$this->db->select_sum('nilai','t')
				->get_where('jurnal_detail',['id_akun'=>$idAkun,'id_perkiraan'=>2])
				->row()->t;

			return $debit - $kredit;
		}

		private function _fmtRp($n){
			$n = (float)$n;
			$neg = ($n < 0);
			$n = abs($n);
			return ($neg ? '-' : '') . 'Rp ' . number_format($n, 0, ',', '.');
		}

	}																							