<?php
	defined('BASEPATH') OR exit('No direct script access allowed');
	
	class Model_kas extends CI_Model
	{
		// menampilkan semua
		public function getAllDataKas()
		{
			$this->db->select('*');
			$this->db->from('kas_keluar');
			$this->db->order_by("id", "asc");
			$query = $this->db->get()->result();
			return $query;
		}
		
		public function getTotalSaldo()
		{
			$dt_kas = $this->getAllData();
			$tot_saldo = 0;
			foreach($dt_kas as $row){
				$tot_saldo += $row['saldo_awal'];
			}
			
			return $tot_saldo;
		}
		
		// menampilkan data berdasarkan id
		public function getIdAkunKasById($id)
		{
			$query = $this->db->get_where('set_account_kas', ['id_akun' => $id]);
			$result = ($query->num_rows() > 0)?$query->row()->id_akun:0; 
			return $result;
		}
		// menampilkan data berdasarkan id
		public function cek_kas_id($id)
		{
			$query = $this->db->get_where('kas_keluar', ['id' => $id]);
			$result = ($query->num_rows() > 0)? TRUE : FALSE; 
			return $result;
		}
		
		public function check_number_kas()
		{
			$query = $this->db->query("SELECT MAX(no_transaksi) as no_trans from kas_keluar");
			$hasil = $query->row();
			return $hasil->no_trans;
		}			
		function getIdAkunKas()
		{
			$this->db->select('set_account_kas.id_akun');
			$this->db->from('set_account_kas');
			$this->db->order_by("id_sak", "asc");
			$query = $this->db->get()->result_array();
			return $query;
		}
		
		public function getArrayIdKas()
		{
			$akun = $this->getIdAkunKas();
			
			$array_result = array();
			foreach($akun as $row){
				$array_result[] = intval($row['id_akun']);
			}
			
			return $array_result;
		}
		
		// menampilkan data berdasarkan id
		public function getDataById($id)
		{
			return $this->db->get_where('set_account_kas', ['id_sak' => $id])->row_array();
		}
		
		// menambah data kas
		public function insert()
		{
			$data = [
			'nm' => $this->input->post('nm_kas', true),
			'desk' => $this->input->post('desk', true),
			'id_akun' => $this->input->post('id_akun', true),
			'date_created' => time(),
			];
			
			$this->db->insert('set_account_kas', $data);
		}
		
		// mengubah data kas
		public function update($id)
		{
			$data = [
			'nm' => $this->input->post('nm', true),
			'desk' => $this->input->post('desk', true),
			'id_akun' => $this->input->post('id_akun', true),
			];
			
			$this->db->where('id_sak', $id);
			$this->db->update('set_account_kas', $data);
		}
		// hapus data kas
		public function delete($id)
		{
			return $this->db->delete('set_account_kas', ['id_sak' => $id]);
		}
		
		public function get_kas_keluar_by_id($id)
		{
			$this->db->select('*');
			$this->db->from('kas_keluar');
			$this->db->where('id', $id);
			$query = $this->db->get();
			return $query;
		}
		// public function get_kas_detail($id)
		// {
			// $this->db->select('
			// jurnal_detail.id_akun, jurnal_detail.nilai, jurnal_detail.id_perkiraan, 
			// jurnal.id_jurnal, jurnal.tgl, jurnal.no_trans, jurnal.keterangan, jurnal.bukti, 
			// akun.noakun, akun.nama, 
			// kelompok_akun.kel_akun, 
			// perkiraan.nama AS perkiraan
			// ');
			// $this->db->from('jurnal_detail');
			// $this->db->join('jurnal', 'jurnal_detail.id_jurnal = jurnal.id_jurnal');
			// $this->db->join('akun', 'jurnal_detail.id_akun = akun.id_akun');
			// $this->db->join('kelompok_akun', 'akun.id_kelompok_akun = kelompok_akun.id_kelompok_akun');
			// $this->db->join('perkiraan', 'jurnal_detail.id_perkiraan = perkiraan.id_perkiraan');
			// $this->db->where('jurnal_detail.id_jurnal', $id); 
			// $query = $this->db->get();
			// $result = $query->num_rows() > 0 ? $query->result_array() : false;
			// return $result;
		// }
		public function get_kas_detail($id)
		{
			$this->db->select('*');
			$this->db->from('kas_keluar_detail');
			$this->db->where('id_kas', $id);
			$query = $this->db->get();
			return $query;
		}
		
		public function hapus_by_id($id){
            if($this->db->delete('kas_keluar', ['id'=>$id]))
            {
				$this->hapus_detail($id);
				return true;
                }else{
				return false;
			}
		}
		
		public function hapus_detail($id){
            if($this->db->delete('kas_keluar_detail', ['id_kas'=>$id]))
            {
				return true;
                }else{
				return false;
			}
		}
		
		public function getKasKeluar($params = [])
		{
		    // Tabel utama
		    $this->db->from('kas_keluar kk'); // kolom minimal: id, no_transaksi, tanggal, keterangan, id_user, id_akun, jumlah

		    // =========================
		    // FILTER: USER / KASIR
		    // =========================
		    // Prioritas 1: jika controller mengirim 'user' (dropdown), pakai itu
		    if (isset($params['search']['user']) && (int)$params['search']['user'] > 0) {
		        $this->db->where('kk.id_user', (int)$params['search']['user']);
		    } else {
		        // Prioritas 2 (defense-in-depth): bila bukan admin/owner, paksa hanya data miliknya
		        $level = $this->session->level ?? null;
		        $idu   = $this->session->idu    ?? 0;
		        if (!in_array($level, ['admin','owner'])) {
		            $this->db->where('kk.id_user', (int)$idu);
		        }
		    }

		    // =========================
		    // FILTER: TANGGAL
		    // =========================
		    if (!empty($params['search']['dari'])) {
		        $this->db->where('kk.tanggal >=', $params['search']['dari']);
		    }
		    if (!empty($params['search']['sampai'])) {
		        $this->db->where('kk.tanggal <=', $params['search']['sampai']);
		    }

		    // =========================
		    // FILTER: KEYWORDS (opsional)
		    // =========================
		    if (!empty($params['search']['keywords'])) {
		        $kw = $params['search']['keywords'];
		        $this->db->group_start()
		                 ->like('kk.no_transaksi', $kw)
		                 ->or_like('kk.keterangan', $kw)
		                 ->group_end();
		    }

		    // =========================
		    // COUNT MODE
		    // =========================
		    if (isset($params['returnType']) && $params['returnType'] == 'count') {
		        return $this->db->count_all_results();
		    }

		    // =========================
		    // ORDER & PAGINATION
		    // =========================
		    $sort = (!empty($params['search']['sortBy']) && strtoupper($params['search']['sortBy']) == 'ASC') ? 'ASC' : 'DESC';
		    // urutkan utama per tanggal, lalu id (biar stabil)
		    $this->db->order_by('kk.tanggal', $sort);
		    $this->db->order_by('kk.id', $sort);

		    if (!empty($params['limit'])) {
		        $start = !empty($params['start']) ? (int)$params['start'] : 0;
		        $this->db->limit((int)$params['limit'], $start);
		    }

		    // Ambil data
		    return $this->db->get()->result_array();
		}

	}										