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

class Dashboard extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        cek_login();
        $this->load->model('Menu_model', 'menu');
        $this->menu->aksesUser($this->session->userdata('login_session')['role']);

        $this->load->model('Admin_model', 'admin');
        $this->load->model('Barang_model', 'barang');
    }

    public function index()
    {
        $data['title'] = "Dashboard";
        $dt_user = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);
        $data['id_gudang'] = $dt_user['cabang_id'];

        date_default_timezone_set('Asia/Jakarta');
        
        $data['bulan_now'] = date("m");
        $data['tahun_now'] = date("Y");

        $tgl = date("d");
        $data['now'] = $data['tahun_now'].'-'.$data['bulan_now'].'-'.$tgl;
        $data['tglAkhir'] = date("Y-m-t", strtotime( $data['now'] ));
        $tgl_a = explode("-",$data['tglAkhir']);
        $array_tgl = array();   
        for($i=1;$i<=$tgl_a[2];$i++){
            $array_tgl[] = $tgl_a[0].'-'.sprintf("%02d", $tgl_a[1]).'-'.sprintf("%02d", $i);
        }
        
        $data['dt_tgl'] = $array_tgl;
        

        // mencari data barang
        $dt_barang = $this->admin->getBarang(); 

        $tgl_awal = date('Y-m-d', strtotime('1/1/1971'));
        $tgl_akhir = date('Y-m-d');

        if(is_admin() || is_petugas()) {

            $data['jml_barang'] = 0;
            $data['total_stok_barang'] = 0;
            $dt_idbarang = array(); 
            foreach($dt_barang as $row){
                    $stok_akhir = $this->barang->_saldo_awal_barang($row['id_barang'], $tgl_awal, $tgl_akhir);

                if($stok_akhir > 0) {
                    $data['total_stok_barang'] += $stok_akhir;
                    $data['jml_barang'] += 1;
                    $dt_idbarang[] = array('id_barang' => $row['id_barang']);
                }
            }

        } else {

            $data['jml_barang'] = 0;
            $data['total_stok_barang'] = 0;
            $dt_idbarang = array(); 

            $dtBarangMasuk = $this->barang->getDetailBarangMasukByIdUser($dt_user['id_user'], $dt_user['cabang_id']);

            foreach($dtBarangMasuk as $row){
                $stokakhir = $this->barang->_saldo_awal_barang_by_user_pemilik($dt_user['id_user'], $row['id_barang'], $tgl_awal, $tgl_akhir, $row['id_detail']);

                if($stokakhir > 0) {
                    $data['total_stok_barang'] += $stokakhir;
                    $data['jml_barang'] += 1;
                    $dt_idbarang[] = array(
                        'id_pemilik' => $dt_user['id_user'],
                        'id_barang' => $row['id_barang'],
                        'id_detail' => $row['id_detail']
                    );
                }
            }

        }
        
        
        $data['user'] = $this->admin->count('user');
        
        // menampilkan data semua Gudang
        $data['dt_gudang'] = $this->admin->getDataCabang();
        
        $data['transaksi'] = [
            'barang_masuk' => $this->admin->getBarangMasuk($data['id_gudang'], 5),
            'barang_keluar' => $this->admin->getBarangKeluar($data['id_gudang'], 5)
        ];





        if(is_admin() || is_petugas()) {

            // Line Chart
            $bln = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
            $data['cbm'] = [];
            $data['cbk'] = [];

            $jml_barang_masuk = 0;
            $jml_barang_keluar = 0;
            foreach ($bln as $b) {
                $jml_bm = $this->getCountBarang($data['id_gudang'], $dt_idbarang, $b, 1);
                $jml_bk = $this->getCountBarang($data['id_gudang'], $dt_idbarang, $b, 2);

                $data['cbm'][] = $jml_bm;
                $data['cbk'][] = $jml_bk;

                $jml_barang_masuk += $jml_bm;
                $jml_barang_keluar += $jml_bk;
            }
            $data['barang_masuk'] = $jml_barang_masuk;
            $data['barang_keluar'] = $jml_barang_keluar;

        } else {

            // Line Chart
            $bln = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
            $data['cbm'] = [];
            $data['cbk'] = [];

            $jml_barang_masuk = 0;
            $jml_barang_keluar = 0;
            foreach ($bln as $b) {
                $jml_bm = $this->getCountBarangUser($data['id_gudang'], $dt_idbarang, $b, 1);
                $jml_bk = $this->getCountBarangUser($data['id_gudang'], $dt_idbarang, $b, 2);

                $data['cbm'][] = $jml_bm;
                $data['cbk'][] = $jml_bk;

                $jml_barang_masuk += $jml_bm;
                $jml_barang_keluar += $jml_bk;
            }
            $data['barang_masuk'] = $jml_barang_masuk;
            $data['barang_keluar'] = $jml_barang_keluar;


        }

        $this->template->load('templates/dashboard', 'dashboard', $data);
    }
    
    public function save_gudang()
    {
        $dt_user = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);
        
        $data_input = array(
                'cabang_id' => $this->input->post('id_gudang', true),
            );
            
        
        $update = $this->admin->update('user', 'id_user', $dt_user['id_user'], $data_input);
        set_pesan('Gudang berhasil dibuka');
        redirect('dashboard');
    }

    // mencari barang keluar dan masuk berdasarkan tgl
    function getCountBarangUser($id_gudang, $dt_barang, $bln, $stts)
    {
        $dt_user = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);
        $this->load->model('Admin_model', 'admin');

        // terkait tanggal
        $set_tgl = date('Y').'-'.$bln.'-'. 15;
        $tgl_awal = date('Y-m-01', strtotime($set_tgl));
        $tgl_akhir = date('Y-m-t', strtotime($set_tgl));

        // mencari data barangnya
        $result = 0;

        foreach($dt_barang as $row) {
            $mutasi_barang = $this->barang->getMutasiBarangByDateAndPemilik($row['id_pemilik'], $row['id_barang'], $id_gudang, $tgl_awal, $tgl_akhir, $row['id_detail']);

            foreach ($mutasi_barang as $b) :

                switch ($b['jenis']) {
                    case "in_tr":
                        $jenis = 'Mutasi Barang Masuk ke ' . $b['trs_cbg'];
                        break;
                    case "out_tr":
                        $jenis = 'Mutasi Barang Keluar ke ' . $b['trs_cbg'];
                        break;
                    case "in":
                        $jenis = 'Barang Masuk';
                        break;
                    case "in_retur":
                        $jenis = 'Barang Retur dari ' . $b['nama_cabang'];
                        break;
                    case "stkpn":
                        $jenis = 'Stok Op Name dari ' . $b['nama_cabang'];
                        break;
                    default:
                        $jenis = 'Barang Keluar';
                }

                // if($b['jenis'] == 'in' || $b['jenis'] == 'in_retur') {
                //      $result += $b['jml']; 
                // } else if($b['jenis'] == 'in_tr' ) { 
                //      $result += $b['jml']; 
                // } else if($b['jenis'] == 'stkpn' ) {
                //     $result += $b['jml'];
                // } else { 
                //     $result -= $b['jml']; 
                // } 

                if($stts == 1) {
                    // mencari jumlah barang masuk
                    if($b['jenis'] == 'in' || $b['jenis'] == 'in_tr') {
                        $result += $b['jml'];
                    } 

                    if($b['jenis'] == 'stkpn') {
                        if($b['jml'] > 0) {
                            $result += $b['jml'];
                        }
                    }
                } else if($stts == 2) {
                    // mencari jumlah barang keluar
                    if($b['jenis'] == 'out' || $b['jenis'] == 'out_tr') {
                        $result += $b['jml'];
                    } 

                    if($b['jenis'] == 'stkpn') {
                        if($b['jml'] < 0) {
                            $result += (-1)*$b['jml'];
                        }
                    }
                }
            endforeach;
        }

        return $result;
    }


    // mencari barang keluar dan masuk berdasarkan tgl
    function getCountBarang($id_gudang, $dt_barang, $bln, $stts)
    {
        $dt_user = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);
        $this->load->model('Admin_model', 'admin');

        // terkait tanggal
        $set_tgl = date('Y').'-'.$bln.'-'. 15;
        $tgl_awal = date('Y-m-01', strtotime($set_tgl));
        $tgl_akhir = date('Y-m-t', strtotime($set_tgl));

        // mencari data barangnya
        $result = 0;

        foreach($dt_barang as $row) {
            $mutasi_barang = $this->barang->getMutasiBarangByDate($row['id_barang'], $dt_user['cabang_id'], $tgl_awal, $tgl_akhir);

            foreach ($mutasi_barang as $b) :

                switch ($b['jenis']) {
                    case "in_tr":
                        $jenis = 'Mutasi Barang Masuk ke ' . $b['trs_cbg'];
                        break;
                    case "out_tr":
                        $jenis = 'Mutasi Barang Keluar ke ' . $b['trs_cbg'];
                        break;
                    case "in":
                        $jenis = 'Barang Masuk';
                        break;
                    case "in_retur":
                        $jenis = 'Barang Retur dari ' . $b['nama_cabang'];
                        break;
                    case "stkpn":
                        $jenis = 'Stok Op Name dari ' . $b['nama_cabang'];
                        break;
                    default:
                        $jenis = 'Barang Keluar';
                }

                // if($b['jenis'] == 'in' || $b['jenis'] == 'in_retur') {
                //      $result += $b['jml']; 
                // } else if($b['jenis'] == 'in_tr' ) { 
                //      $result += $b['jml']; 
                // } else if($b['jenis'] == 'stkpn' ) {
                //     $result += $b['jml'];
                // } else { 
                //     $result -= $b['jml']; 
                // } 

                if($stts == 1) {
                    // mencari jumlah barang masuk
                    if($b['jenis'] == 'in' || $b['jenis'] == 'in_tr') {
                        $result += $b['jml'];
                    } 

                    if($b['jenis'] == 'stkpn') {
                        if($b['jml'] > 0) {
                            $result += $b['jml'];
                        }
                    }
                } else if($stts == 2) {
                    // mencari jumlah barang keluar
                    if($b['jenis'] == 'out' || $b['jenis'] == 'out_tr') {
                        $result += $b['jml'];
                    } 

                    if($b['jenis'] == 'stkpn') {
                        if($b['jml'] < 0) {
                            $result += (-1)*$b['jml'];
                        }
                    }
                }
            endforeach;
        }

        return $result;
    }







    
    function persentase_barang_keluar()
    {
        $dt_user = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);
        $dt_cabang = $this->admin->getDataCabangByUser($dt_user['cabang_id']);
        $data['barang'] = $this->admin->getBarang(); 

        date_default_timezone_set('Asia/Jakarta');
        
        $data['bulan_now'] = date("m");
        $data['tahun_now'] = date("Y");

        $data['tahun'] = array(2022,2023,2024,2025,2026);

        // memperoleh tgl pada bulan ini
        $tgl = date("d");
        $data['now'] = $data['tahun_now'].'-'.$data['bulan_now'].'-'.$tgl;
        $data['tglAkhir'] = date("Y-m-t", strtotime( $data['now'] ));
        $tgl_a = explode("-",$data['tglAkhir']);
        $array_tgl = array();   
        for($i=1;$i<=$tgl_a[2];$i++){
            $array_tgl[] = $tgl_a[0].'-'.sprintf("%02d", $tgl_a[1]).'-'.sprintf("%02d", $i);
        }

        $data['array_tgl'] = $array_tgl;
        $tgl_awal = date('Y-m-d', strtotime('1/1/1971'));
        $tgl_akhir = date('Y-m-01', strtotime($data['now']));

        // // perhitungan hpp
        $dt_transaksi = array();
        foreach($data['barang'] as $row){
            // mencari data transaksi terkait keluar masuk
            $saldo_awal = $this->_saldo_awal_barang($row['id_barang'], $tgl_awal, $tgl_akhir);

            $transaksi = array();
            foreach($array_tgl as $row_tgl) {
                // mutasi stok
                $tgl_set = date('Y-m-d', strtotime($row_tgl));
                $mutasi = $this->barang->getMutasiBarangByDate($row['id_barang'], $dt_user['cabang_id'], $tgl_set, $tgl_set); 

                $qty_in_baru = 0;
                $qty_out_baru = 0;
                foreach($mutasi as $row_mutasi) {
                    if($row_mutasi['jenis'] == 'in_tr' || $row_mutasi['jenis'] == 'in') {
                        $qty_in_baru = intval($row_mutasi['jml']);
                    } else {
                        $qty_out_baru += intval($row_mutasi['jml']);
                    }
                }
                // die;
                $transaksi[] = array(
                    'tgl' => $row_tgl,
                    'masuk' => $qty_in_baru,
                    'keluar' => $qty_out_baru,
                    'persentase' => ($qty_in_baru == 0) ? 0 : ($qty_out_baru/$qty_in_baru)*100,
                );
            }

            $dt_transaksi[] = array(
                'id_barang' => $row['id_barang'],
                'nm_barang' => $row['nama_barang'],
                'saldo_awal' => $saldo_awal,
                'transaksi' => $transaksi,
            );
        }
        
        
        
        $sum_qty_awal = 0;
        $sum_stok_in = 0;
        $sum_stok_out = 0; 
        $sum_tot = 0;

        $sum_array = array();
                    
        foreach ($dt_transaksi as $dt) :

            $sum_qty_awal += $dt['saldo_awal']['qty'];

            $qty = $dt['saldo_awal']['qty'];

            $sum_in = 0;
            $sum_out = 0;

            $sum_transaksi = array();

            foreach($dt['transaksi'] as $trans) { 
                // perhitungan hpp
                if ($trans['masuk'] > 0) {
                    $qty += $trans['masuk'];
                }

                if ($trans['keluar'] > 0) {
                    $qty -= $trans['keluar'];
                } 


                $sum_transaksi[] = array(
                    'tgl' => $trans['tgl'],
                    'qty_in' => $trans['masuk'],
                    'qty_out' => $trans['keluar'],
                    'qty_res' => $qty,
                ); 
                    
            }

            $sum_array[] = array(
                'nm_barang' => $dt['nm_barang'],
                'transaksi' => $sum_transaksi
            );

            $sum_stok_in += $sum_in;
            $sum_stok_out += $sum_out; 

        endforeach;
    
        // menyusun disini
        $res_result = array();            
        foreach($array_tgl as $row_tgl) { 

            $qty_in = 0;
            $qty_out = 0;
            $qty_res = 0;

            foreach($sum_array as $row_sum) {
                foreach($row_sum['transaksi'] as $row_rs) {
                    if($row_rs['tgl'] == $row_tgl) {
                        $qty_in += $row_rs['qty_in'];
                        $qty_out += $row_rs['qty_out'];
                        $qty_res += $row_rs['qty_res'];
                    }
                }
                
            }

            // $res_result[] = array(
            //     'tgl' => $row_tgl,
            //     'qty_in' => $qty_in ,
            //     'qty_out' => $qty_out,
            //     'qty_res' => $qty_res,
            //     'persentase' => ($qty_in == 0) ? 0 : ($qty_out/$qty_in)*100,
            // );
            
            $res_result[] = ($qty_in == 0) ? 0 : ($qty_out/$qty_in)*100;
        }
        
        
        return $res_result;
    }
    
    function total_barang_all()
    {
        $dt_user = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);
        $dt_cabang = $this->admin->getDataCabangByUser($dt_user['cabang_id']);
        $dt_barang = $this->admin->getBarang();

        $tgl_awal = date('Y-m-d', strtotime('1/1/1971'));
        $tgl_akhir = date('Y-m-d');

        $data['barang'] = array(); 
        $total_barang = 0;
        foreach($dt_barang as $row){
            $dtBarangById = $this->admin->get('barang', ['id_barang' => $row['id_barang']]);
            $mutasi_barang = $this->barang->getMutasiBarang($row['id_barang'], $dt_user['cabang_id']);

            $sisa_stok = $dtBarangById['stokawal'];
            foreach ($mutasi_barang as $b) :

                switch ($b['jenis']) {
                    case "in_tr":
                        $jenis = 'Mutasi Barang Masuk ke ' . $b['trs_cbg'];
                        break;
                    case "out_tr":
                        $jenis = 'Mutasi Barang Keluar ke ' . $b['trs_cbg'];
                        break;
                    case "in":
                        $jenis = 'Barang Masuk';
                        break;
                    case "in_retur":
                        $jenis = 'Barang Retur dari ' . $b['nama_cabang'];
                        break;
                    case "stkpn":
                        $jenis = 'Stok Op Name dari ' . $b['nama_cabang'];
                        break;
                    default:
                        $jenis = 'Barang Keluar';
                }

                if($b['jenis'] == 'in' || $b['jenis'] == 'in_retur') {
                     $sisa_stok += $b['jml']; 
                } else if($b['jenis'] == 'in_tr' ) { 
                     $sisa_stok += $b['jml']; 
                } else if($b['jenis'] == 'stkpn' ) { 
                    $sisa_stok += $b['jml']; 
                } else { 
                    $sisa_stok -= $b['jml']; 
                } 
            endforeach;
            
            
            $tgl_akhir = date('Y-m-d');
            $tgl_awal = date('Y-m-d', strtotime('-30 days', strtotime($tgl_akhir)));
            $dtbrg_keluar = $this->admin->getBarangKeluarById($tgl_awal, $tgl_akhir, $dt_user['cabang_id'], $row['id_barang']);
           
            $jml_brg_keluar = 0;
            foreach($dtbrg_keluar as $row_klr) {
                $jml_brg_keluar += $row_klr['jumlah'];
            }
           
            // cek total barang keluar 30 hari terakhir
            $faktor_z = 1.645; //biasanya untuk tingkat layanan 95% nilainya 1,645
            $deviasi_standar_permintaan = $jml_brg_keluar/30; //misal historis penjualan selama 30 hari ada 300, maka 300/30 hari = 10
            $lead_time = 30; //waktu tunggu pemesanan barang sampai jadi inventori toko
            
            $safety_stock = $faktor_z * $deviasi_standar_permintaan * sqrt($lead_time);
            $safety_stock = round($safety_stock);
            

            $data['barang'][] = array(
                'tgl' => $row['tgl'],
                'id_barang' => $row['id_barang'],
                'nama_barang' => $row['nama_barang'],
                'nama_jenis' => $row['nama_jenis'],
                'safety_stock' => $safety_stock,
                'saldo' => $row['stokawal'],
                'saldo_akhir' => $sisa_stok,
                'nama_satuan' => $row['nama_satuan'],
            );
            
            $total_barang += $sisa_stok;
        }
        
        return $total_barang;
    }
    
    
    function _saldo_awal_barang($id_barang, $tgl_awal, $tgl_akhir)
    {
        $dt_user = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);

        $getBarangById = $this->admin->get('barang', ['id_barang' => $id_barang]);
        $mutasi_barang = $this->barang->getMutasiBarangByDate($id_barang, $dt_user['cabang_id'], $tgl_awal, $tgl_akhir);

        $sisa_stok = $getBarangById['stokawal'];
        foreach ($mutasi_barang as $b) :

            switch ($b['jenis']) {
                case "in_tr":
                    $jenis = 'Mutasi Barang Masuk ke ' . $b['trs_cbg'];
                    break;
                case "out_tr":
                    $jenis = 'Mutasi Barang Keluar ke ' . $b['trs_cbg'];
                    break;
                case "in":
                    $jenis = 'Barang Masuk';
                    break;
                case "in_retur":
                    $jenis = 'Barang Retur dari ' . $b['nama_cabang'];
                    break;
                case "stkpn":
                    $jenis = 'Stok Op Name dari ' . $b['nama_cabang'];
                    break;
                default:
                    $jenis = 'Barang Keluar';
            }

            if($b['jenis'] == 'in' || $b['jenis'] == 'in_retur') {
                 $sisa_stok += $b['jml']; 
            } else if($b['jenis'] == 'in_tr' ) { 
                 $sisa_stok += $b['jml']; 
            } else if($b['jenis'] == 'stkpn' ) { 
                $sisa_stok += $b['jml']; 
            } else { 
                $sisa_stok -= $b['jml']; 
            } 
        endforeach;

        $saldo_awal = array(
            'qty' => $sisa_stok,
        );

        return $saldo_awal;
    }
}
