<?php
defined("BASEPATH") or exit("No direct script access allowed");

/**
 * Kas Keluar
*/
class Kas_keluar extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();

        // cek sesi login
        cek_session_login();

        $this->load->model('Model_kas','kas');
        $this->load->model('Masterdata_model','masterdata');
        $this->load->model('Journal_model','journal');
        $this->load->model('Report_model','report');

        // default global perpage
        $this->perPage = 10;
        // global title
        $this->title   = info()["title"];
        // session id user
        $this->iduser  = $this->session->idu;
    }

    /**
     * Ambil daftar user untuk dropdown "Pengguna"
     * - admin/owner : semua user
     * - user biasa  : hanya dirinya sendiri
     */
    private function get_pilihan_users()
    {
        $level = $this->session->level;
        $idu   = $this->iduser;

        $this->db->select('id_user, nama_lengkap');
        $this->db->from('tb_users');

        if (!in_array($level, ['admin','owner'])) {
            $this->db->where('id_user', $idu);
        }

        $this->db->order_by('nama_lengkap', 'ASC');
        return $this->db->get()->result_array();
    }

    public function index()
    {
        $data['title']    = 'Kas Keluar | '.$this->title;
        // >>>>>>>>>> PENTING: kirim $pilihan ke view (agar dropdown Pengguna terisi)
        $data['pilihan']  = $this->get_pilihan_users();
        $this->template->load('main/themes','kas_keluar/view_index',$data);
    }

    function ajaxKasKeluar()
    {
        // Define offset 
        $page = $this->input->post('page');
        $offset = $page ? $page : 0;

        $limits = $this->input->post("limits");
        $limit  = !empty($limits) ? (int)$limits : $this->perPage;

        $conditions = [];

        $keywords = $this->input->post('keywords');
        if (!empty($keywords)) {
            $conditions['search']['keywords'] = $keywords;
        }

        $sortBy = $this->input->post('sortBy');
        if (!empty($sortBy)) {
            $conditions['search']['sortBy'] = $sortBy;
        }

        // Tambahan: filter User dari dropdown (selaras dengan pembelian.php)
        $user = $this->input->post('user');
        if ($user !== null && $user !== '' && $user !== '0') {
            $conditions['search']['user'] = (int)$user;
        } else {
            // jika bukan admin/owner, kunci ke user yang login
            if (!in_array($this->session->level, ['admin','owner'])) {
                $conditions['search']['user'] = (int)$this->iduser;
            }
        }

        $tgl = $this->input->post('tgl');
        if (!empty($tgl)) {
            $date   = date_ranges($tgl);
            $dari   = date_replace_slash($date['dari']);
            $sampai = date_replace_slash($date['sampai']);
            $conditions["search"]["dari"]   = $dari;
            $conditions["search"]["sampai"] = $sampai;
        }

        // Get record count 
        $conditions['returnType'] = 'count';
        $totalRec = $this->kas->getKasKeluar($conditions);

        // Pagination configuration 
        $config['target']      = '#dataKasKeluar';
        $config['base_url']    = base_url('kas_keluar/ajaxKasKeluar');
        $config['total_rows']  = $totalRec;
        $config['per_page']    = $limit;
        $config['link_func']   = 'searchFilterKas';

        // Initialize pagination library 
        $this->ajax_pagination->initialize($config);

        // Get records 
        $conditions['start'] = $offset;
        $conditions['limit'] = $limit;

        unset($conditions['returnType']);
        $data['record'] = $this->kas->getKasKeluar($conditions);

        // Load the data list view 
        $this->load->view('kas_keluar/ajax-kas',$data);
    }

    public function load_form()
    {
        $no_transaction =  $this->kas->check_number_kas();
        $no_order = substr($no_transaction, 6, 4);
        $no_transaction_now = intval($no_order) + 1;

        if ($no_transaction == null) {
            $data['no_trans'] = date("ymd").'0001';
        } else {
            $data['no_trans'] = date("ymd").$no_transaction_now;
        }

        $data['tanggal'] = tgl_sampai_slash();

        $inArray = array(210,220,310,420,510,520);
        $this->report->set_account_group_id($inArray);
        $this->db->order_by('kelompok_akun.kel_akun', 'ASC');
        $data['akun'] =  $this->masterdata->getAccountData();

        $this->load->view('kas_keluar/load_form',$data);
    }

    public function akun_kas(){
        $result = $this->model_app->views('set_account_kas');

        $data = array();
        foreach ($result->result() as $row)
        {
            $data[] = array("id"=>$row->id_akun,"name"=>$row->nm);
        }

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

    public function detail()
    {
        $id = xss_filter($this->input->post("id"), 'xss');
        $id = decrypt_url($id);

        $detail = $this->kas->get_kas_keluar_by_id($id);
        if(!empty($detail))
        {
            $data['row'] = $detail->row();
            $this->db->order_by('kelompok_akun.kel_akun', 'ASC');
            $data['akun'] =  $this->masterdata->getAccountData();
            $data['data'] = $this->kas->get_kas_detail($id)->result_array();
            $this->load->view('kas_keluar/detail_form',$data);
        } else {
            $this->load->view('errors/404',$data);
        }
    }

    public function simpan_kas_keluar()
    {
        $no_trans       = xss_filter($this->input->post("no_trans"), 'xss');
        $dari_kas       = xss_filter($this->input->post("dari_kas"), 'xss');
        $saldo_kas      = xss_filter($this->input->post("saldo_kas"), 'xss');
        $tanggal_kas    = xss_filter($this->input->post("tanggal_kas"), 'xss');
        $tanggal_kas    = date_replace_slash($tanggal_kas);
        $keterangan_kas = xss_filter($this->input->post("keterangan_kas"), 'xss');
        $jumlah_kas     = xss_filter($this->input->post("jumlah_kas"), 'xss');
        $getIdAkunKasById = $this->kas->getIdAkunKasById($dari_kas);
        $idAkun     = $this->input->post('idAkun', true);
        $keterangan = $this->input->post('keterangan', true);
        $jumlah     = $this->input->post('jumlah', true);

        $idAkun     = is_array($idAkun) ? $idAkun : [];
        $keterangan = is_array($keterangan) ? $keterangan : [];
        $jumlah     = is_array($jumlah) ? $jumlah : [];

        $nominal = [];
        $total_kas_keluar = 0;
        foreach ($jumlah as $key => $value) {
            $nominal[$key] = convert_to_number($value);
            $total_kas_keluar += $nominal[$key];
        }

        if ($total_kas_keluar <= 0) {
            $total_kas_keluar = convert_to_number($jumlah_kas);
        }

        $catatan =  "KAS KELUAR NO#".$no_trans;
        $data = [
            "no_trans"   => $no_trans,
            "tgl"        => $tanggal_kas,
            "keterangan" => $catatan,
            "bukti"      => '',
            "id_user"    => $this->iduser
        ];

        $this->db->insert('jurnal', $data);
        $jurnal_id = $this->db->insert_id();

        
        // [ADD] Upload lampiran bukti nota kas keluar (opsional)
        $bukti_nota_file = null;
        $bukti_jurnal_file = '';
        if (!empty($_FILES['bukti_nota']['name'])) {
            $upload_dir = FCPATH . 'uploads/bukti_kas_keluar/';
            if (!is_dir($upload_dir)) {
                @mkdir($upload_dir, 0755, true);
            }

            $this->load->library('upload');
            $no_trans_safe = preg_replace('/[^A-Za-z0-9_\-]/', '_', (string) $no_trans);

            $config = [
                'upload_path'   => $upload_dir,
                'allowed_types' => 'jpg|jpeg|png|webp|pdf',
                'max_size'      => 6144, // 6MB
                'file_name'     => 'kas_' . $no_trans_safe . '_' . time(),
                'overwrite'     => false,
            ];

            $this->upload->initialize($config);

            if (!$this->upload->do_upload('bukti_nota')) {
                $response = [
                    'status' => false,
                    'msg'    => trim($this->upload->display_errors('', '')),
                ];
                $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();
            }

            $up = $this->upload->data();
            $finalUpload = bm_finalize_ci_upload_as_webp($up, 80);
            if (!$finalUpload['status']) {
                $response = [
                    'status' => false,
                    'msg'    => $finalUpload['message'],
                ];
                $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();
            }

            $bukti_nota_file = $finalUpload['file_name'];

            // Sinkronkan lampiran bukti nota ke folder jurnal umum.
            $jurnal_upload_dir = FCPATH . 'uploads/lampiran/';
            if (!is_dir($jurnal_upload_dir)) {
                @mkdir($jurnal_upload_dir, 0755, true);
            }

            $source_file = rtrim($upload_dir, '/\\') . DIRECTORY_SEPARATOR . $bukti_nota_file;
            $target_file = $jurnal_upload_dir . $bukti_nota_file;

            if (is_file($source_file)) {
                if (!is_file($target_file)) {
                    @copy($source_file, $target_file);
                }
                if (is_file($target_file)) {
                    $bukti_jurnal_file = $bukti_nota_file;
                }
            }
        }
        // [END ADD] Upload lampiran bukti nota kas keluar
        if ($bukti_jurnal_file !== '') {
            $this->db
                ->where('id_jurnal', $jurnal_id)
                ->update('jurnal', ['bukti' => $bukti_jurnal_file]);
        }

        $data_kas = [
            "no_transaksi" => $no_trans,
            "id_user"      => $this->iduser,
            "id_jurnal"    => $jurnal_id,
            "tanggal"      => $tanggal_kas,
            "id_akun"      => $dari_kas,
            "jumlah"       => $total_kas_keluar,
            "keterangan"   => $keterangan_kas,
            // [ADD] Simpan nama file bukti nota (nullable)
            "bukti_nota"  => $bukti_nota_file
        ];
        $kas_keluar = $this->model_app->input('kas_keluar', $data_kas);

        $input_jurnal = array();
        $input_kas    = array();

        foreach($idAkun AS $key => $val){
            $input_kas[] = array(
                'id_kas'    => $kas_keluar['id'],
                'id_akun'   => $val,
                'jumlah'    => isset($nominal[$key]) ? $nominal[$key] : 0,
                'keterangan'=> isset($keterangan[$key]) ? $keterangan[$key] : '',
            );

            $input_jurnal[] = array(
                'id_jurnal'       => $jurnal_id,
                'id_akun'         => $val,
                'tipe_kas'        => $this->kas->getIdAkunKasById($val),
                'id_perkiraan'    => 1,
                'nilai'           => isset($nominal[$key]) ? $nominal[$key] : 0,
                'catatan_jurnal'  => isset($keterangan[$key]) ? $keterangan[$key] : '',
            );
        };

        $this->db->insert_batch('kas_keluar_detail', $input_kas);
        $this->db->insert_batch('jurnal_detail', $input_jurnal);

        $input_jurnal_kredit = array(
            'id_jurnal'      => $jurnal_id,
            'id_akun'        => $dari_kas,
            'tipe_kas'       => $getIdAkunKasById,
            'id_perkiraan'   => 2,
            'nilai'          => $total_kas_keluar,
            'catatan_jurnal' => $keterangan_kas,
        );
        $input = $this->model_app->input('jurnal_detail', $input_jurnal_kredit);

        if($input['status']=='ok'){
            $response = ['status'=>true,'msg'=>'Berhasil disimpan'];
        }else{
            $response = ['status'=>true,'msg'=>'Gagal disimpan'];
        }

        $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();
    }

    public function cek_total_kas(){
        $id = $this->db->escape_str($this->input->post('id'));
        $total = $this->model_app->sum_data('jml_bayar','bayar_invoice_detail',['id_invoice'=>$id]);
        $total_order = $this->model_app->cek_total_detail(['id_invoice'=>$id])->row()->total;
        $get_id_transaksi = get_id_transaksi($id)['nomor_order'];
        $cek = $this->model_app->view_where('invoice',['id_invoice'=>$id]);
        if($cek->num_rows() > 0){
            $row = $cek->row();
            $msg = array('status'=>'ok','id'=>$id,'no_order'=>$get_id_transaksi,'total_order'=>$total_order,'total'=>$total,'ket'=>$row->history);
        }else{
            $msg = array('status'=>'error','id'=>0);
        }
        echo json_encode($msg);
    }

    public function hapus_kas()
    {
        cek_nput_post('GET');
        simpan_demo("Hapus");
        $id = $this->input->post('id', true);
        $id = decrypt_url($id);

        $cek_kas = $this->kas->get_kas_keluar_by_id($id);

        if($cek_kas->num_rows() > 0){

            $hapus = $this->kas->hapus_by_id($id);
            if($hapus==true)
            {
                $this->hapus_journal($cek_kas->row()->id_jurnal);
                $response = [
                    'status'=>true,
                    'title'=>'Peringatan!!!',
                    'msg'   =>'Berhasil',
                ];
            }else{
                $response = [
                    'status'=>false,
                    'title'=>'Peringatan!!!',
                    'msg'   =>'Gagal',
                ];
            }
        }else{
            $response = [
                'status'=>false,
                'title'=>'Peringatan!!!',
                'msg'   =>'Data tidak ditemukan',
            ];
        }

        $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();
    }

    private function hapus_journal($id)
    {
        $data['data'] = $this->journal->get_jurnal_by_id($id);
        if(!empty($data['data'][1]['bukti'])){
            @unlink(FCPATH . 'uploads/lampiran/' . $data['data'][1]['bukti']);
        }
        $this->journal->delete_journal($id);
    }

    public function print_pdf()
    {
        $tanggal = $this->input->post('tanggal', true);
        if(!empty($tanggal)){
            $date   = date_ranges($tanggal);
            $dari   = date_replace_slash($date['dari']);
            $sampai = date_replace_slash($date['sampai']);

            $data['periode'] = 'Tanggal Order';
            $data['tanggal'] = today();

            $data['dari']   = $dari;
            $data['sampai'] = $sampai;

            $data['user'] = $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
            $data['info'] = info();

            $condition['search']['dari']   = $dari;
            $condition['search']['sampai'] = $sampai;

            $data['logo']    = FCPATH.'uploads/'.info()['logo'];
            $data['laporan'] = $this->model_data->printKasKeluar($condition);

            $mod = modul_cetak('cetak_order');
            $this->load->library('pdf');
            $this->pdf->setPaper($mod['ukuran'], $mod['posisi']);
            $this->pdf->filename = "laporan_kas_keluar";
            $this->pdf->load_view('Kas_keluar/cetak_semua_kas', $data);
        }else{
            $data['cetak'] = 'error';
            $this->load->view('errors/404',$data);
        }
    }

    public function cetak($noid)
    {
        $noid = decrypt_url($noid);
        $id = ["id" => $noid];

        $search = $this->model_app->view_where("kas_keluar", $id);
        $data["logo"] = FCPATH . "uploads/" . info()["logo"];

        if ($search->num_rows() > 0) {
            $row = $search->row_array();
            $data["cetak"] = $row;
            $data["info"]  = info();
            $data["detail"]= $this->model_app->view_where("kas_keluar_detail", ["id" => $noid])->result_array();
            $data["user"]  = $this->model_app->view_where("tb_users", ["id_user" => $row["id_user"]])->row_array();

            $this->load->library("pdf");
            $this->pdf->setPaper("A5", "landscape");
            $this->pdf->filename = "kas_" . $noid . "_" . $row["tanggal"];
            $this->pdf->load_view("kas_keluar/cetak_kas", $data);
        } else {
            $data["heading"] = "Halaman error";
            $data["message"] = "Data tidak ditemukan";
            $this->load->view("errors/html/error_404", $data);
        }
    }
}
