<?php
	defined('BASEPATH') OR exit('No direct script access allowed');
	
	class Report extends CI_Controller 
	{
		public function __construct()
		{
			parent::__construct();
			cek_session_login();
			$this->load->model('Report_model','report');
			$this->load->model('Kas_model','kas');
			$this->load->model('Masterdata_model','masterdata');
			$this->load->model('Setting_model','setting');
			$this->load->model('Admin_model', 'admin');
			$this->iduser = $this->session->idu;
			$this->level = $this->session->level;
		}
		
		public function index()
		{
			cek_menu_akses();
			$data['title'] = 'Buku Besar';
			$data['user'] = $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
			
			
			$now = date("Y-m-d");
			$data['tglAwal'] = date('Y-m-').'01';
			$data['tglAkhir'] = $now;
			
			//data akun
			$this->db->order_by('kelompok_akun.kel_akun', 'ASC');
			$data['akun'] =  $this->masterdata->getAccountData();
			
			$this->form_validation->set_rules('namaAkun','Nama Akun', 'required');
			$this->form_validation->set_rules('tglAwal','Tgl Awal', 'required');
			$this->form_validation->set_rules('tglAkhir','Tgl Akhir', 'required');
			
			if($this->form_validation->run() == false) {
				$data['status'] = 0;
				
				$this->template->load('main/themes','report/index',$data);
				} else {
				$idAkun = $this->input->post('namaAkun', true);
				$tglAwal = $this->input->post('tglAwal', true);
				$tglAkhir = $this->input->post('tglAkhir', true);
				$data['tglAwal'] = $tglAwal;
				$data['tglAkhir'] = $tglAkhir;
				
				
				
				$account_data = $this->masterdata->getAccountDataById($idAkun);
				$data['account_data'] = $this->buildLedgerAccountData($account_data, $idAkun, $tglAwal);
				
				$data['tglAwal'] = $tglAwal;
				$data['tglAkhir'] = $tglAkhir;
				
				
				$array = array('jurnal_detail.id_akun' => $idAkun, 'jurnal.tgl >=' => $tglAwal, 'jurnal.tgl <=' => $tglAkhir);
				$this->db->where($array);
				$data['journal_data'] =  $this->report->getData($idAkun, $tglAwal, $tglAkhir);
				
				$data['status'] = 1;
				$data['title'] = 'Buku Besar';
				$data['user'] = $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
				
				$this->db->order_by('kelompok_akun.kel_akun', 'ASC');
				$data['akun'] =  $this->masterdata->getAccountData();
				$this->template->load('main/themes','report/index',$data);
				
			}
		}
		
		public function trialbalance()
		{
			$data['title'] = 'Neraca Saldo';
			$data['user'] = $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
			
			$now = date("Y-m-d");
			$data['pilih_range'] = 1;
			// menampilkan daftar nama bulan
			$data['bulan_sekarang'] = date('m');
			$data['bulan'] = bulan();
			// menampilkan tahun
			$thn = date('Y');
			$data['tahun_sekarang'] = $thn;
			$data['tahun'] = array();
			$j = 0;
			for($i=0; $i < 10; $i++) {
				$data['tahun'][] = $thn-$i;
				$j++;
			}
			
			// $this->form_validation->set_rules('bln','', 'required');
			$this->form_validation->set_rules('tahun','', 'required');
			
			if($this->form_validation->run() == false) {
				$data['status'] = 0;
				
				$this->template->load('main/themes','report/trialbalance',$data);
				} else {
				$pilih_range 	= $this->input->post('pilih_range', true);
				$bln 	= $this->input->post('bln', true);
				$tahun 	= $this->input->post('tahun', true);
				$tgl_set = date($tahun.'-'.$bln.'-d');
				$tglAwal = '1971-01-01';
				$tglAkhir = ((int) $pilih_range === 2)
					? $tahun . '-12-31'
					: date('Y-m-t', strtotime($tgl_set));
				$data['pilih_range'] = $pilih_range;
				$data['bulan_sekarang'] = $bln;
				$data['tahun_sekarang'] = $tahun;
				// dump($_POST);
				$kelAkun = $this->db->get('kelompok_akun')->result_array();
				$inArray = array(110,120,210,220,310,410,420,510,520);
				// Neraca saldo adalah posisi kumulatif sampai akhir periode.
				$data['neraca_saldo_data'] = $this->getData($tglAwal, $tglAkhir, $inArray);
				
				$data['status'] = 1;
				
				$this->template->load('main/themes','report/trialbalance',$data);
			}
		}
		
		public function incomestatement()
		{
			$data['title'] = 'Laporan Laba Rugi';
			$data['user'] = $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
			$now = date("Y-m-d");
			$data['pilih_range'] = 1;
			// menampilkan daftar nama bulan
			$data['bulan_sekarang'] = date('m');
			$data['bulan'] = bulan();
			// menampilkan tahun
			$thn = date('Y');
			$data['tahun_sekarang'] = $thn;
			$data['tahun'] = array();
			$j = 0;
			for($i=0; $i < 10; $i++) {
				$data['tahun'][] = $thn-$i;
				$j++;
			}
			
			// $this->form_validation->set_rules('bln','', 'required');
			$this->form_validation->set_rules('tahun','', 'required');
			
			if($this->form_validation->run() == false) {
				$data['status'] = 0;
				
				$this->template->load('main/themes','report/incomestatement',$data);
				} else {
				$pilih_range 	= $this->input->post('pilih_range', true);
				$bln 	= $this->input->post('bln', true);
				$tahun 	= $this->input->post('tahun', true);
				$tgl_set = date($tahun.'-'.$bln.'-d');
				$data['pilih_range'] = $pilih_range;
				if ((int) $pilih_range === 2) {
					$tglAwal = $tahun . '-01-01';
					$tglAkhir = $tahun . '-12-31';
				} else {
					$tglAwal = date('Y-m-01', strtotime($tgl_set));
					$tglAkhir = date('Y-m-t', strtotime($tgl_set));
				}
				$data['bulan_sekarang'] = $bln;
				$data['tahun_sekarang'] = $tahun;
				
				// Laba rugi hanya memuat mutasi periode, tanpa saldo awal akun nominal.
				$data['laba_rugi_data'] = $this->getData($tglAwal, $tglAkhir, array(410,420,510,520), '', false);
				
				$data['status'] = 1;
				$this->template->load('main/themes','report/incomestatement',$data);
				
			}
		}
		
		public function capitalstatement()
		{
			$data['title'] = 'Laporan Perubahan Ekuitas';
			$data['user'] = $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
			
			$now = date("Y-m-d");
			// menampilkan daftar nama bulan
			$data['bulan_sekarang'] = date('m');
			$data['bulan'] = bulan();
			// menampilkan tahun
			$thn = date('Y');
			$data['tahun_sekarang'] = $thn;
			$data['tahun'] = array();
			$j = 0;
			for($i=0; $i < 10; $i++) {
				$data['tahun'][] = $thn-$i;
				$j++;
			}
			
			$this->form_validation->set_rules('bln','', 'required');
			$this->form_validation->set_rules('tahun','', 'required');
			
			if($this->form_validation->run() == false) {
				$data['status'] = 0;
				
				$this->template->load('main/themes','report/capitalstatement',$data);
				} else {
				$bln 	= $this->input->post('bln', true);
				$tahun 	= $this->input->post('tahun', true);
				$tgl_set = date($tahun.'-'.$bln.'-d');
				
				
				$tglAwal = $tahun . '-01-01';
				$tglAkhir = date('Y-m-t', strtotime($tgl_set));
				$tglSebelum = date('Y-m-d', strtotime('-1 day', strtotime($tglAwal)));
				$data['tglAkhir'] = $tglAkhir;
				$data['bulan_sekarang'] = $bln;
				$data['tahun_sekarang'] = $tahun;
				$data['data_akun'] = $this->report->getAccountData();
				$data['labarugi'] = $this->getTotalLabaRugi($tglAwal, $tglAkhir, array(410,420,510,520));
				$data['perubahan_ekuitas_data'] = $this->getData_capital_statement($tglAwal, $tglAkhir, array(310));
				$data['saldo_awal'] = $this->getEquityAtDate($tglSebelum);
				
				
				$data['status'] = 1;
				
				$this->template->load('main/themes','report/capitalstatement',$data);
			}
		}
		
		public function balancesheet()
		{
			$data['title'] = 'Laporan Neraca';
			$data['user'] = $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
			$now = date("Y-m-d");
			// menampilkan daftar nama bulan
			$data['bulan_sekarang'] = date('m');
			$data['bulan'] = bulan();
			// menampilkan tahun
			$thn = date('Y');
			$data['tahun_sekarang'] = $thn;
			$data['tahun'] = array();
			$j = 0;
			for($i=0; $i < 10; $i++) {
				$data['tahun'][] = $thn-$i;
				$j++;
			}
			
			$this->form_validation->set_rules('bln','', 'required');
			$this->form_validation->set_rules('tahun','', 'required');
			
			if($this->form_validation->run() == false) {
				$data['status'] = 0;
				
				$this->template->load('main/themes','report/balancesheet',$data);
				} else {
				$bln 	= $this->input->post('bln', true);
				$tahun 	= $this->input->post('tahun', true);
				$tgl_set = date($tahun.'-'.$bln.'-d');
				$inArray = array(110,120,210,220,310,410,420,510,520);
				
				
				$tglAwal = '1971-01-01';
				$tglAkhir = date('Y-m-t', strtotime($tgl_set));
				$data['bulan_sekarang'] = $bln;
				$data['tahun_sekarang'] = $tahun;
				$data['data_akun'] = $this->report->getAccountData();
				$data['labarugi'] = $this->getTotalLabaRugi($tglAwal, $tglAkhir, array(410,420,510,520));
				$data['modal_akhir'] = $this->getModalAkhir(0, $tglAwal, $tglAkhir, array(310), $data['labarugi'], $data['data_akun']);
				$data['neraca_saldo_data'] = $this->getData($tglAwal, $tglAkhir, $inArray);
				
				$data['status'] = 1;
				
				$this->template->load('main/themes','report/balancesheet',$data);
			}
		}
		
		public function cashflowstatement()
		{
			$data['title'] = 'Laporan Arus Kas';
			$data['user'] = $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
			
			
			$now = date("Y-m-d");
			// menampilkan daftar nama bulan
			$data['bulan_sekarang'] = date('m');
			$data['bulan'] = bulan();
			// menampilkan tahun
			$thn = date('Y');
			$data['tahun_sekarang'] = $thn;
			$data['tahun'] = array();
			$j = 0;
			for($i=0; $i < 10; $i++) {
				$data['tahun'][] = $thn-$i;
				$j++;
			}
			
			$this->form_validation->set_rules('bln','', 'required');
			$this->form_validation->set_rules('tahun','', 'required');
			
			if($this->form_validation->run() == false) {
				$data['status'] = 0;
				
				$this->template->load('main/themes','report/cashflowstatement',$data);
				} else {
				$bln 	= $this->input->post('bln', true);
				$tahun 	= $this->input->post('tahun', true);
				$tgl_set = date($tahun.'-'.$bln.'-d');
				
				$tglAwal = date('Y-m-01', strtotime($tgl_set));
				$tglAkhir = date('Y-m-t', strtotime($tgl_set));
				$data['bulan_sekarang'] = $bln;
				$data['tahun_sekarang'] = $tahun;
				$data['data_akun'] = $this->report->getAccountData();
				
				$cashFlow = $this->report->getCashFlowSummary($tglAwal, $tglAkhir);
				$data['activitas_operasi'] = $cashFlow[1];
				$data['activitas_investasi'] = $cashFlow[2];
				$data['activitas_pendanaan'] = $cashFlow[3];
				$data['total_saldo_kas'] = $this->report->getCashBalanceAt(
					date('Y-m-d', strtotime('-1 day', strtotime($tglAwal)))
				);
				
				$data['status'] = 1;
				
				$this->template->load('main/themes','report/cashflowstatement',$data);
			}
		}
		
		public function setting()
		{
			$data['title'] = 'Setting Laporan Arus Kas';
			$data['user'] = $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
			// Menampilkan aktivitas
			$data['activitas'] = $this->report->kel_aktivitas();
			
			// Menampilkan aktivitas operasi
			$this->report->set_kategori_by_tipe_aktivitas(1);
			$data['activitas_operasi'] = $this->report->kategori_arus_kas();
			
			// Menampilkan aktivitas operasi
			$this->report->set_kategori_by_tipe_aktivitas(2);
			$data['activitas_investasi'] = $this->report->kategori_arus_kas();
			
			// Menampilkan aktivitas operasi
			$this->report->set_kategori_by_tipe_aktivitas(3);
			$data['activitas_pendanaan'] = $this->report->kategori_arus_kas();
			
			// Menampilkan data akun
			$data['masterdata'] = $this->masterdata->getAccountData();
			
			$this->form_validation->set_rules('nama-kategori','Nama Kategori', 'required');
			$this->form_validation->set_rules('tipe-aktivitas','Tipe Aktivitas', 'required');
			$this->form_validation->set_rules('akun-sumber[]','Akun Sumber', 'required');
			
			if($this->form_validation->run() == false ){
				
				$this->template->load('main/themes','report/setting',$data);
				} else {
				$namaKategori = $this->input->post('nama-kategori', true);
				$tipeAktivitas = $this->input->post('tipe-aktivitas', true);
				$akunSumber = $this->input->post('akun-sumber[]', true);
				
				// echo json_encode($akunSumber);
				$this->report->insert_kategori();
				$this->session->set_flashdata('message','<div class="alert alert-success" role="alert">New kategori Added! 
				<button type="button" class="close" data-dismiss="alert" aria-label="Close">
				<span aria-hidden="true">&times;</span>
				</button></div>');
				redirect('report/setting');
			}
		}
		
		public function delete($id)
		{
			$this->report->delete_kategori($id);
			$this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">Kategori has been deleted!
			<button type="button" class="close" data-dismiss="alert" aria-label="Close">
			<span aria-hidden="true">&times;</span>
		  	</button></div>');
			redirect('report/setting');
		}
		
		public function data_aktivitas()
		{
			$id = $this->input->post('id');
			$this->db->where('kategori.id_kategori', $id);
			$aktivitas = $this->report->aktivitas_arus_kas();
			foreach ($aktivitas as $result) {
				$value[] = array( 
    			'id_akun' => (float) $result['id_akun'], 
    			'id_kelompok_aktivitas' => (float) $result['id_kelompok_aktivitas'],
    			'keterangan' => (float) $result['keterangan']
				);
			}
			echo json_encode($value);
		}
		
		public function update_katagori()
		{
			$this->report->updateKategori();
			$this->session->set_flashdata('message','<div class="alert alert-success" role="alert">Kategori has been Updated! 
			<button type="button" class="close" data-dismiss="alert" aria-label="Close">
			<span aria-hidden="true">&times;</span>
			</button></div>');
			redirect('report/setting');
		}
		
		public function printledger()
		{
			
			$idAkun = $this->input->post('namaAkun', true);
			$tglAwal = $this->input->post('tglAwal', true);
			$tglAkhir = $this->input->post('tglAkhir', true);
			
			
			
			
			$account_data = $this->masterdata->getAccountDataById($idAkun);
			$data['account_data'] = $this->buildLedgerAccountData($account_data, $idAkun, $tglAwal);
			
			$array = array('jurnal_detail.id_akun' => $idAkun, 'jurnal.tgl >=' => $tglAwal, 'jurnal.tgl <=' => $tglAkhir);
			$this->db->where($array);
			$data['journal_data'] =  $this->report->getData($idAkun, $tglAwal, $tglAkhir);
			
			$data['tglAwal'] = $tglAwal;
			$data['tglAkhir'] = $tglAkhir;
			$data['profile'] = $this->db->get_where('info', ['id' => 1])->row_array();
			$this->load->library('PDF_MC_Table');
			$this->load->view('report/pdf/ledger', $data);
		}
		
		public function printtrialbalance()
		{
			
			$pilih_range 	= $this->input->post('pilih_range_print', true);
			$bln 	= $this->input->post('bln', true);
			$tahun 	= $this->input->post('tahun', true);
			$tgl_set = date($tahun.'-'.$bln.'-d');
			
			$tglAwal = '1971-01-01';
			$tglAkhir = ((int) $pilih_range === 2)
				? $tahun . '-12-31'
				: date('Y-m-t', strtotime($tgl_set));
			
			$kelAkun = $this->db->get('kelompok_akun')->result_array();
			$inArray = array(110,120,210,220,310,410,420,510,520);
			$data['bln'] = $bln;
			$data['tahun'] = $tahun;
			$data['profile'] = $this->db->get_where('info', ['id' => 1])->row_array();
			$data['neraca_saldo_data'] = $this->getData($tglAwal, $tglAkhir, $inArray);
			
			$this->load->library('fpdf');
			$this->load->view('report/pdf/trialbalance', $data);
		}
		
		function printincomestatement()
		{
		    // Ambil nilai filter dari form cetak (modal)
		    $pilih_range = $this->input->post('pilih_range_print', true);
		    $bln         = $this->input->post('bln', true);
		    $tahun       = $this->input->post('tahun', true);
		    $tgl_set     = date($tahun . '-' . $bln . '-d');

		    if ((int) $pilih_range === 2) {
		        $tglAwal = $tahun . '-01-01';
		        $tglAkhir = $tahun . '-12-31';
		    } else {
		        $tglAwal = date('Y-m-01', strtotime($tgl_set));
		        $tglAkhir = date('Y-m-t', strtotime($tgl_set));
		    }

		    // Data periode & profil perusahaan untuk header PDF
		    $data['bln']     = $bln;
		    $data['tahun']   = $tahun;
		    $data['profile'] = $this->db
		        ->get_where('info', ['id' => 1])
		        ->row_array();

		    // Ambil mutasi akun laba rugi pada periode yang dipilih.
		    $laba_rugi_data = $this->getData($tglAwal, $tglAkhir, array(410, 420, 510, 520), '', false);

		    // === FILTER AGAR SAMA DENGAN TAMPILAN BROWSER ===
		    // Di view HTML incomestatement, hanya akun yang saldo-nya != 0 yang ditampilkan:
		    //   if ($row['saldo'] > 0) ... else if ($row['saldo'] < 0) ...
		    // Supaya PDF tidak menampilkan akun dengan saldo 0,
		    // di sini kita bersihkan dulu $laba_rugi_data sebelum dikirim ke view PDF.
		    if (isset($laba_rugi_data[0]) && is_array($laba_rugi_data[0])) {
		        foreach ($laba_rugi_data[0] as $kelompok_akun => $daftar_akun) {
		            if (!is_array($daftar_akun)) {
		                continue;
		            }

		            foreach ($daftar_akun as $id_akun => $akun) {
		                $saldo = isset($akun['saldo']) ? (float) $akun['saldo'] : 0;

		                // Buang akun yang saldo-nya 0 supaya tidak ikut tercetak
		                if ($saldo == 0.0) {
		                    unset($laba_rugi_data[0][$kelompok_akun][$id_akun]);
		                }
		            }

		            // Kalau seluruh akun dalam kelompok ini sudah terhapus (semua 0),
		            // hapus juga kelompoknya supaya tidak muncul blok kosong.
		            if (empty($laba_rugi_data[0][$kelompok_akun])) {
		                unset($laba_rugi_data[0][$kelompok_akun]);
		            }
		        }
		    }

		    // Kirim data yang sudah difilter ke view PDF
		    $data['laba_rugi_data'] = $laba_rugi_data;

		    // Generate PDF
		    $this->load->library('fpdf');
		    $this->load->view('report/pdf/incomestatement', $data);
		}

		
		public function printcapitalstatement()
		{
			$bln 	= $this->input->post('bln', true);
			$tahun 	= $this->input->post('tahun', true);
			$tgl_set = date($tahun.'-'.$bln.'-d');
			
			$tglAwal = $tahun . '-01-01';
			$tglAkhir = date('Y-m-t', strtotime($tgl_set));
			$tglSebelum = date('Y-m-d', strtotime('-1 day', strtotime($tglAwal)));
			
			$data['bln'] = $bln;
			$data['tahun'] = $tahun;
			$data['tglAkhir'] = $tglAkhir;
			$data['profile'] = $this->db->get_where('info', ['id' => 1])->row_array();
			$data['data_akun'] = $this->report->getAccountData();
			$data['labarugi'] = $this->getTotalLabaRugi($tglAwal, $tglAkhir, array(410,420,510,520));
			$data['perubahan_ekuitas_data'] = $this->getData_capital_statement($tglAwal, $tglAkhir, array(310));
			$data['saldo_awal'] = $this->getEquityAtDate($tglSebelum);
			
			$this->load->library('fpdf');
			$this->load->view('report/pdf/capitalstatement',$data);
		}
		
		public function printbalancesheet()
		{
			$bln 	= $this->input->post('bln', true);
			$tahun 	= $this->input->post('tahun', true);
			$tgl_set = date($tahun.'-'.$bln.'-d');
			
			$tglAwal = date('Y-m-d', strtotime('1/1/1971'));
			$tglAkhir = date('Y-m-t', strtotime($tgl_set));
			
			$inArray = array(110,120,210,220,310,410,420,510,520);
			$data['bln'] = $bln;
			$data['tahun'] = $tahun;
			$data['profile'] = $this->db->get_where('info', ['id' => 1])->row_array();
			$data['data_akun'] = $this->report->getAccountData();
			$data['labarugi'] = $this->getTotalLabaRugi($tglAwal, $tglAkhir, array(410,420,510,520));
			$data['modal_akhir'] = $this->getModalAkhir(0, $tglAwal, $tglAkhir, array(310), $data['labarugi'], $data['data_akun']);
			$data['neraca_saldo_data'] = $this->getData($tglAwal, $tglAkhir, $inArray);
			
			$this->load->library('fpdf');
			$this->load->view('report/pdf/balancesheet', $data);
		}
		
		public function printcashflowstatement()
		{
			$bln 	= $this->input->post('bln', true);
			$tahun 	= $this->input->post('tahun', true);
			$tgl_set = date($tahun.'-'.$bln.'-d');
			
			$tglAwal = date('Y-m-01', strtotime($tgl_set));
			$tglAkhir = date('Y-m-t', strtotime($tgl_set));
			
			
			$data['bln'] = $bln;
			$data['tahun'] = $tahun;
			$data['profile'] = $this->db->get_where('info', ['id' => 1])->row_array();
			$data['data_akun'] = $this->report->getAccountData();
			
			$cashFlow = $this->report->getCashFlowSummary($tglAwal, $tglAkhir);
			$data['activitas_operasi'] = $cashFlow[1];
			$data['activitas_investasi'] = $cashFlow[2];
			$data['activitas_pendanaan'] = $cashFlow[3];
			$data['total_saldo_kas'] = $this->report->getCashBalanceAt(
				date('Y-m-d', strtotime('-1 day', strtotime($tglAwal)))
			);
			
			$this->load->library('fpdf');
			$this->load->view('report/pdf/cashflowstatement', $data);
		}
		
		
		function getArusKas($tglAwal, $tglAkhir, $activityId = 1)
		{
			$summary = $this->report->getCashFlowSummary($tglAwal, $tglAkhir);
			return $summary[(int) $activityId] ?? array();
		}
		
		
		
		
		function getModalAkhir($modal_awal, $tglAwal, $tglAkhir, $inArray, $totalLabarugi, $data_akun)
		{
			$equityData = $this->getData($tglAwal, $tglAkhir, $inArray);
			$signedEquity = 0;
			if (isset($equityData[0][310])) {
				foreach ($equityData[0][310] as $row) {
					$signedEquity += (int) $row['saldo'];
				}
			}

			// Data laporan memakai debit positif dan kredit negatif. Untuk
			// penyajian ekuitas, tanda tersebut dibalik lalu ditambah laba/rugi.
			return (int) $modal_awal - $signedEquity + (int) $totalLabarugi;
		}

		private function getEquityAtDate($date)
		{
			if (empty($date) || $date < '1971-01-01') {
				$equityData = $this->getData('1971-01-01', '1971-01-01', array(310));
				$signedEquity = 0;
				if (isset($equityData[0][310])) {
					foreach ($equityData[0][310] as $row) {
						$signedEquity += (int) $row['saldo'];
					}
				}
				return -$signedEquity;
			}

			$profit = $this->getTotalLabaRugi('1971-01-01', $date, array(410,420,510,520));
			return $this->getModalAkhir(0, '1971-01-01', $date, array(310), $profit, array());
		}
		
		
		public function getData_capital_statement($tglAwal, $tglAkhir, $inArray){
			$this->report->set_account_group_id($inArray);
			$journal_data = $this->report->getData(null, $tglAwal, $tglAkhir);
			
			$this->masterdata->set_account_group_id($inArray);
			$account_data = $this->masterdata->getAccountData();
			
			// return $result= $account_data;
			if($account_data)
			{
				foreach ($account_data as $row)
				{	
					$result[0][$row['kel_akun']][$row['id_akun']] = array('nama' => $row['nama'], 'saldo' => 0, 'kel_akun' => $row['kel_akun'], 'noakun' => $row['noakun']);
				}
				
				if($journal_data)
				{
					foreach ($journal_data as $row)
					{
						if(isset($result[0][$row['kel_akun']][$row['id_akun']]))
						{
							if($row['id_perkiraan'] == 1)
							{
								$result[0][$row['kel_akun']][$row['id_akun']]['saldo'] += $row['nilai'];
							}
							else
							{
								$result[0][$row['kel_akun']][$row['id_akun']]['saldo'] -=  $row['nilai'];
							}
						}
					}
				}			
				return $result;
			}
		}
		
		
		public function getTotalLabaRugi($tglAwal, $tglAkhir, $inArray)
		{
			$labaRugi = $this->getData($tglAwal, $tglAkhir, $inArray, '', false);
			$revenueSigned = 0;
			$expenseSigned = 0;

			foreach (array(410, 420) as $group) {
				foreach (($labaRugi[0][$group] ?? array()) as $row) {
					$revenueSigned += (int) $row['saldo'];
				}
			}
			foreach (array(510, 520) as $group) {
				foreach (($labaRugi[0][$group] ?? array()) as $row) {
					$expenseSigned += (int) $row['saldo'];
				}
			}

			return (-$revenueSigned) - $expenseSigned;
		}

		private function buildLedgerAccountData($accountData, $accountId, $startDate)
		{
			if (empty($accountData)) {
				return array();
			}

			$opening = ((int) $accountData['id_perkiraan'] === 1)
				? (int) $accountData['saldo_awal']
				: -(int) $accountData['saldo_awal'];
			$previousDate = date('Y-m-d', strtotime('-1 day', strtotime($startDate)));
			if ($previousDate >= '1971-01-01') {
				$previousEntries = $this->report->getData($accountId, '1971-01-01', $previousDate);
				foreach ($previousEntries as $entry) {
					$opening += ((int) $entry['id_perkiraan'] === 1)
						? (int) $entry['nilai']
						: -(int) $entry['nilai'];
				}
			}

			return array(
				'id_perkiraan' => (int) $accountData['id_perkiraan'],
				'nama' => $accountData['nama'],
				'kel_akun' => $accountData['kel_akun'],
				'noakun' => $accountData['noakun'],
				'saldo_awal' => $opening,
			);
		}
		// ->where('month(jurnal.tgl)',$bulan)
		// ->where('year(jurnal.tgl)',$tahun)
		
		function getData($tglAwal, $tglAkhir, $inArray, $pilih_range = '', $includeOpeningBalance = true)
		{
			$this->report->set_account_group_id($inArray);
			$journal_data = $this->report->getData(null, $tglAwal, $tglAkhir);
			
			$this->masterdata->set_account_group_id($inArray);
			$account_data = $this->masterdata->getAccountData();
			
			// return $result= $account_data;
			$result = array(0 => array());
			$result = array(0 => array());
			if($account_data)
			{
				foreach ($account_data as $row)
				{	
					$opening = 0;
					if ($includeOpeningBalance) {
						$opening = ((int) $row['id_perkiraan'] === 1)
							? (int) $row['saldo_awal']
							: -(int) $row['saldo_awal'];
					}
					$result[0][$row['kel_akun']][$row['id_akun']] = array(
						'nama' => $row['nama'],
						'saldo' => $opening,
						'kel_akun' => $row['kel_akun'],
						'noakun' => $row['noakun']
					);
				}
				
				if($journal_data)
				{
					foreach ($journal_data as $row)
					{
						if(isset($result[0][$row['kel_akun']][$row['id_akun']]))
						{
							if($row['id_perkiraan'] == 1)
							{
								$result[0][$row['kel_akun']][$row['id_akun']]['saldo'] += $row['nilai'];
							}
							else
							{
								$result[0][$row['kel_akun']][$row['id_akun']]['saldo'] -=  $row['nilai'];
							}
						}
					}
				}			
				return $result;
			}
		}
	}
	
	
	
