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

class Proses extends CI_Controller {
    public function __construct() {
		parent::__construct();
		cek_login();
	}

    // proses kategori
    public function load_kategori() {
        $data['input'] =  $this -> input -> post(null, TRUE);
		$this -> load -> view('barang/kategori/data', $data);
	}
    
    public function get_kategori() {
		$data = $this -> db -> get_where('kategori', ['id' => $_POST['id']]) -> row();
        echo json_encode($data);
	}

	public function hps_kategori() {
		$input = $this -> input -> post(null, TRUE);
        $this -> db -> delete('kategori', ['id' => $input['id']]);
        $this -> app -> tambah_aktivitas('Menghapus data kategori ' . $_POST['nama']);
        echo json_encode(['success' => 1, 'msg' => 'Kategori sudah dihapus']);
	}

	public function simpan_kategori() {
		$input = $this -> input -> post(null, TRUE);

        if($input['id'] == 0) {
            $this -> db -> insert('kategori', $input);
            $this -> app -> tambah_aktivitas('Menambahkan kategori baru ' . $input['nama']);
            echo json_encode(['success' => 1, 'msg' => 'Kategori baru sudah disimpan']);
            
        } else {
            $this -> db -> update('kategori', ['nama' => $input['nama']], ['id' => $input['id']]);
            $this -> app -> tambah_aktivitas('Update data kategori ' . $input['nama']);
            echo json_encode(['success' => 1, 'msg' => 'Kategori sudah diupdate']);
        }

	}

    // proses satuan
    public function load_satuan() {		
        $data['input'] =  $this -> input -> post(null, TRUE);
		$this -> load -> view('barang/satuan/data', $data);
	}
    
    public function get_satuan() {		
		$data = $this -> db -> get_where('satuan', ['id' => $_POST['id']]) -> row();
        echo json_encode($data);
	}

	public function hps_satuan() {
		$input = $this -> input -> post(null, TRUE);
        $this -> db -> delete('satuan', ['id' => $input['id']]);
        $this -> app -> tambah_aktivitas('Menghapus data satuan ' . $_POST['nama']);
        echo json_encode(['success' => 1, 'msg' => 'satuan sudah dihapus']);
	}

	public function simpan_satuan() {
		$input = $this -> input -> post(null, TRUE);

        if($input['id'] == 0) {
            $this -> db -> insert('satuan', $input);
            $this -> app -> tambah_aktivitas('Menambahkan satuan baru ' . $input['nama']);
            echo json_encode(['success' => 1, 'msg' => 'satuan baru sudah disimpan']);
            
        } else {
            $this -> db -> update('satuan', ['nama' => $input['nama']], ['id' => $input['id']]);
            $this -> app -> tambah_aktivitas('Update data satuan ' . $input['nama']);
            echo json_encode(['success' => 1, 'msg' => 'Satuan sudah diupdate']);
        }

	}

    // proses supplier
    public function load_supplier() {		
        $data['input'] =  $this -> input -> post(null, TRUE);
		$this -> load -> view('barang/supplier/data', $data);
	}
    
    public function get_supplier() {		
		$data = $this -> db -> get_where('supplier', ['id' => $_POST['id']]) -> row();
        echo json_encode($data);
	}

	public function hps_supplier() {
		$input = $this -> input -> post(null, TRUE);
        $this -> db -> delete('supplier', ['id' => $input['id']]);
        $this -> app -> tambah_aktivitas('Menghapus data supplier ' . $_POST['nama']);
        echo json_encode(['success' => 1, 'msg' => 'supplier sudah dihapus']);
	}

	public function simpan_supplier() {
		$input = $this -> input -> post(null, TRUE);

        if($input['id'] == 0) {
            $this -> db -> insert('supplier', $input);
            $this -> app -> tambah_aktivitas('Menambahkan supplier baru ' . $input['nama']);
            echo json_encode(['success' => 1, 'msg' => 'supplier baru sudah disimpan']);
            
        } else {
            $this -> db -> update('supplier', $input, ['id' => $input['id']]);
            $this -> app -> tambah_aktivitas('Update data supplier ' . $input['nama']);
            echo json_encode(['success' => 1, 'msg' => 'supplier sudah diupdate']);
        }

	}

    // Proses opname
    public function load_data_opname() {
        $data['input'] = $_POST;
        
        $this -> load -> view('barang/opname/load', $data);
    }
    
    public function load_tambah_list() {
        $data['input'] = $_POST;
        
        $this -> load -> view('barang/opname/tambah_list', $data);
    }
    
    public function load_detail_opname() {
        $data['id'] = $_POST['id'];
        
        $this -> load -> view('barang/opname/detail', $data);
    }
    
    public function hps_item_opname() {
        $where['id'] = $_POST['id'];
        
        $this -> db -> delete('opname_detail', $where);

        echo json_encode(['success' => 1]);
    }
    
    public function update_stok_fisik() {
        $id['id']          = $_POST['id'];
        $qty['stok_fisik'] = $_POST['stok'];
        
        $this -> db -> update('opname_detail', $qty, $id);

        echo json_encode(['success' => 1]);
    }
    
    public function update_ket_opname() {
        $id['id']          = $_POST['id'];
        $ket['keterangan'] = $_POST['ket'];
        
        $this -> db -> update('opname_detail', $ket, $id);

        echo json_encode(['success' => 1]);
    }
    
    public function update_satuan_opname() {
        $id     = $_POST['id'];
        $satuan = $_POST['satuan'];
        $toko   = $this -> session -> mart_toko;

        $where['id'] = $id;
        
        $detail = $this -> db -> get_where('opname_detail', $where) -> row();

        $where_satuan['id_brg']    = $detail -> id_brg; 
        $where_satuan['id_satuan'] = $satuan; 
        $where_satuan['id_toko']   = $toko; 

        $get = $this -> db -> get_where('barang_satuan', $where_satuan) -> row();

        $update['id_satuan']   = $satuan;
        $update['stok_sistem'] = $get -> stok;
        $update['stok_fisik']  = 0;
        
        $this -> db -> update('opname_detail', $update, $where);

        echo json_encode(['success' => 1]);
    }
    
    public function add_item_opname() {
        $kode  = $_POST['kode'];
        $toko  = $this -> session -> mart_toko;
        $admin = $this -> session -> mart_id;

        $where_cek['id_toko'] = $toko;
        $where_cek['kode']    = $kode;

        $cek    = $this -> db -> get_where('barang', $where_cek) -> row();
        
        if($cek) {
            $where_satuan['id_brg']     = $cek -> id;
            $where_satuan['id_toko']    = $cek -> id_toko;
            $satuan = $this -> db -> get_where('barang_satuan', $where_satuan) -> first_row();
            
            $where['id_brg']    = $cek -> id;
            $where['id_satuan'] = $satuan -> id_satuan;
            $where['id_toko']   = $toko;
            $where['id_admin']  = $admin;
            $where['id_opname'] = 0;
            
            $detail = $this -> db -> get_where('opname_detail', $where) -> row();
                       
            if($detail) {
                echo json_encode(['success' => 1, 'msg' => 'tersedia']);                

            } else {
                $data['id_brg']       = $cek -> id;
                $data['id_satuan']    = $satuan -> id_satuan;
                $data['stok_sistem']  = $satuan -> stok;
                $data['id_toko']      = $toko;
                $data['id_admin']     = $admin;

                $this -> db -> insert('opname_detail', $data);
                echo json_encode(['success' => 1, 'msg' => 'Item ditambahkan']);
            }


        } else {
            echo json_encode(['success' => 0, 'msg' => 'Item tidak tersedia']);
        }
        
    }

    public function submit_opname() {
        $tgl    = $_POST['tgl'];
        $toko   = $this -> session -> mart_toko;
        $admin  = $this -> session -> mart_id;
        $kode   = 'OPN' . date('ymdhi') . rand(10, 99);
        $detail = $this -> app -> get_stok_opname();
        $count  = 0;

        $data['tgl']      = $tgl;
        $data['kode']     = $kode;
        $data['id_toko']  = $toko;
        $data['id_admin'] = $admin;

        $this -> db -> insert('opname_data', $data);
        $id = $this -> db -> insert_id();

        foreach($detail as $item) {
            $where['id']         = $item -> id;
            $update['id_opname'] = $id;
            
            $where_satuan['id_brg']     = $item -> id_brg;
            $where_satuan['id_satuan']  = $item -> id_satuan;
            $where_satuan['id_toko']    = $item -> id_toko;
            $get = $this -> db -> get_where('barang_satuan', $where_satuan) -> row();

            if($item -> stok_fisik > 0) {
                $update_stok['stok'] = $item -> stok_fisik;
                
                $riwayat['id_brg']     = $item -> id_brg;
                $riwayat['id_satuan']  = $item -> id_satuan;
                $riwayat['id_toko']    = $item -> id_toko;
                $riwayat['id_admin']   = $item -> id_admin;
                $riwayat['jml']        = $item -> stok_fisik;
                $riwayat['stok_awal']  = $get -> stok;
                $riwayat['stok_akhir'] = $item -> stok_fisik;
                $riwayat['status']     = $item -> stok_fisik;
                $riwayat['keterangan'] = 'Stok Opname';
                $riwayat['tgl']        = $tgl . ' ' . date('H:i:s');
                
                $this -> db -> insert('riwayat_stok', $riwayat);
                $this -> db -> update('barang_satuan', $update_stok, $where_satuan);
            }

            $this -> db -> update('opname_detail', $update, $where);
            $count++;
        }

        if($count > 0) {
            echo json_encode(['success' => 1, 'msg' => 'Data stok opname sudah disimpan']);
        } else {
            echo json_encode(['success' => 0, 'msg' => 'Terjadi Kesalahan! Coba periksa kembali']);
        }
    }

    // proses pelanggan
    public function load_pelanggan() {
        $data['input'] =  $this -> input -> post(null, TRUE);
		$this -> load -> view('pelanggan/data', $data);
	}
    
    public function get_pelanggan() {
		$data = $this -> db -> get_where('pelanggan', ['id' => $_POST['id']]) -> row();
        echo json_encode($data);
	}

	public function hps_pelanggan() {
		$input = $this -> input -> post(null, TRUE);
        $this -> db -> delete('pelanggan', ['id' => $input['id']]);
        $this -> app -> tambah_aktivitas('Menghapus data pelanggan ' . $input['nama']);
        echo json_encode(['success' => 1, 'msg' => 'pelanggan sudah dihapus']);
	}

	public function simpan_pelanggan() {
		$input = $this -> input -> post(null, TRUE);

        if($input['id'] == 0) {
            $this -> db -> insert('pelanggan', $input);
            $this -> app -> tambah_aktivitas('Menambahkan pelanggan baru ' . $input['nama']);
            echo json_encode(['success' => 1, 'msg' => 'pelanggan baru sudah disimpan']);
            
        } else {
            $update = [
                'nama' => $input['nama'],
                'nohp' => $input['nohp'],
                'alamat' => $input['alamat']
            ];
            $this -> db -> update('pelanggan', $update, ['id' => $input['id']]);
            $this -> app -> tambah_aktivitas('Update data pelanggan ' . $input['nama']);
            echo json_encode(['success' => 1, 'msg' => 'pelanggan sudah diupdate']);
        }
	}

    // proses karyawan
    public function load_karyawan() {
        $data['input'] =  $this -> input -> post(null, TRUE);
		$this -> load -> view('karyawan/data', $data);
	}
    
    public function get_karyawan() {
		$data = $this -> db -> get_where('admin', ['id' => $_POST['id']]) -> row();
        echo json_encode($data);
	}

	public function hps_karyawan() {
		$input = $this -> input -> post(null, TRUE);
        $this -> db -> delete('admin', ['id' => $input['id']]);
        $this -> app -> tambah_aktivitas('Menghapus data karyawan ' . $input['nama']);
        echo json_encode(['success' => 1, 'msg' => 'karyawan sudah dihapus']);
	}

	public function simpan_karyawan() {
		$input = $this -> input -> post(null, TRUE);

        if($input['id'] == 0) {
            $cek = $this -> db -> get_where('admin', ['email' => $input['email']]) -> row();
            
            if($cek) {
                echo json_encode(['success' => 0, 'msg' => 'Email sudah terdaftar']);
                exit;
            }

            $input['password'] = password_hash($input['password'], PASSWORD_DEFAULT);
            $this -> db -> insert('admin', $input);
            $this -> app -> tambah_aktivitas('Menambahkan karyawan baru ' . $input['nama']);
            echo json_encode(['success' => 1, 'msg' => 'karyawan baru sudah disimpan']);
            
        } else {
            $get = $this -> db -> get_where('admin', ['id' => $input['id']]) -> row();
            $cek = $this -> db -> get_where('admin', ['email' => $input['email'], 'id != ' => $input['id']]) -> row();

            $input['password'] = $input['password'] ? password_hash($input['password'], PASSWORD_DEFAULT) : $get -> password; 

            if($cek) {
                echo json_encode(['success' => 0, 'msg' => 'Email sudah terdaftar']);
                exit;
            }

            $this -> db -> update('admin', $input, ['id' => $input['id']]);
            $this -> app -> tambah_aktivitas('Update data karyawan ' . $input['nama']);
            echo json_encode(['success' => 1, 'msg' => 'karyawan sudah diupdate']);
        }
	}

    // proses barang
    public function load_brg() {
        $data['input'] = $this -> input -> post(null, TRUE); 
        $this -> load -> view('barang/data/load', $data);
    }

    public function get_brg() {
        $toko = $this -> session -> mart_toko; 
        $data = $this -> db -> get_where('barang', ['id' => $_POST['id'], 'id_toko' => $toko]) -> row(); 
        
        if($data) {
            $barang_satuan      = $this -> db -> get_where('barang_satuan', ['id_brg' => $data -> id, 'jenis' => 1]) -> row();
            $data -> id_satuan  = $barang_satuan ? $barang_satuan -> id_satuan : 0;
            $data -> stok       = $barang_satuan ? $barang_satuan -> stok : 0;
            $data -> harga_jual = $barang_satuan ? $barang_satuan -> harga_jual : 0;
            $data -> harga_beli = $barang_satuan ? $barang_satuan -> harga_beli : 0;

            echo json_encode(['success' => 1, 'data' => $data]);
        }
    }

    public function cek_data() {
        $toko  = $this -> session -> mart_toko;
        $get   = $this -> db -> get_where('barang', ['kode' => $_POST['code'],'id_toko' => $toko]) -> row();
        
        if($get) {
            $getsa = $this -> app -> get_barang_satuan($get -> id);
            $get -> satuan = $getsa; 
            echo json_encode(['success' => 1, 'msg' => 'Barang ditemukan', 'data' => $get]);
        } else {
            echo json_encode(['success' => 0, 'msg' => 'Barang tidak ditemukan']);
        }
    }
    
    public function modal_barcode() {
        $data['kode'] = $_POST['id'];
        $this -> load -> view('barang/data/barcode', $data);
    }

    public function hps_brg() {
        $id = $_POST['id'];
        $this -> db -> delete('barang', ['id' => $id]);
        $this -> db -> delete('barang_satuan', ['id_brg' => $id]);
        $this -> db -> delete('barang_grosir', ['id_brg' => $id]);
        $this -> app -> tambah_aktivitas('Menghapus data barang ' . $_POST['nama']);
        echo json_encode(['success' => 1]);
    }

    public function submit_barang() {
        $input = $this -> input -> post(null, TRUE);
        $toko  = $this -> session -> mart_toko;

        if(empty($input['kode'])) {
            echo json_encode(['success' => 0, 'msg' => 'Kode barang belum diisi']);

        } else if(empty($input['nama'])) {
            echo json_encode(['success' => 0, 'msg' => 'Nama barang belum diisi']);

        } else {
            $barang = $this -> db -> get_where('barang', ['kode' => $input['kode'], 'id_toko' => $toko]) -> row();

            if($barang) {
                if($barang -> id != $input['id']) {
                    echo json_encode(['success' => 0, 'msg' => 'Kode barang sudah tersedia']);
                    exit;
                }
            }

            $data_brg = [
                'kode'           => $input['kode'],
                'nama'           => $input['nama'],
                'id_kategori'    => isset($input['id_kategori']) ? $input['id_kategori'] : null,
                'id_supplier'    => isset($input['id_supplier']) ? $input['id_supplier'] : null ,
                'tgl_kadaluarsa' => $input['tgl_kadaluarsa'] ? $input['tgl_kadaluarsa'] : null,
                'harga_beli'     => form_uang($input['harga_beli'], false),
                'is_retur'       => isset($input['is_retur']) ? 1 : 0,
                'id_toko'        => $toko
            ];

            $brg_satuan = [
                'harga_jual' => form_uang($input['harga_jual'], false),
                'harga_beli' => form_uang($input['harga_beli'], false),
                'id_satuan'  => isset($input['id_satuan']) ? $input['id_satuan'] : null,
                'jenis'      => 1,
                'id_toko'    => $toko
            ];

            if($input['id'] == 0) {
                $this -> db -> insert('barang', $data_brg);
                $idbrg =  $this -> db -> insert_id(); 
                $brg_satuan['id_brg'] = $idbrg; 
                $brg_satuan['stok']   = $input['stok']; 

                $this -> db -> insert('barang_satuan', $brg_satuan);  
                
                if($input['stok'] > 0) {
                    $riwayat_stok['id_brg']     = $idbrg;
                    $riwayat_stok['stok_awal']  = 0;
                    $riwayat_stok['stok_akhir'] = $input['stok'];
                    $riwayat_stok['jml']        = $input['stok'];
                    $riwayat_stok['status']     = 1;
                    $riwayat_stok['id_satuan']  = $input['id_satuan'];
                    $riwayat_stok['id_toko']    = $toko;
                    $riwayat_stok['id_admin']   = $this -> session -> mart_id;
                    $riwayat_stok['tgl']        = date('Y-m-d H:i:s');

                    $this -> db -> insert('riwayat_stok', $riwayat_stok);
                }

                $this -> app -> tambah_aktivitas('Menambahkan barang baru ' . $input['nama']);
                echo json_encode(['success' => 1, 'msg' => 'Data barang sudah ditambahkan']);
                
            } else {
                $this -> db -> update('barang', $data_brg, ['id' => $input['id'], 'id_toko' => $toko]);
                $rows = $this -> db -> affected_rows();
                $brg_satuan['id_satuan'] = $input['id_satuan'];

                $cek_where ['id_brg'] =  $input['id'];
                $cek_where ['jenis']  =  1;

                $ceksatuan = $this -> db -> get_where('barang_satuan', $cek_where) -> row();

                if($ceksatuan) {
                    $this -> db -> update('barang_satuan', $brg_satuan, $cek_where);
                    $rows = $this -> db -> affected_rows() + $rows;

                } else {
                    $brg_satuan['id_brg']    = $input['id']; 
                    $this -> db -> insert('barang_satuan', $brg_satuan);
                    $rows = $this -> db -> affected_rows() + $rows;
                }
                
                if($rows > 0) {                    
                    $this -> app -> tambah_aktivitas('Update data barang ' . $input['nama']);
                    echo json_encode(['success' => 1, 'msg' => 'Data barang sudah diupdate']);
                    
                } else {
                    echo json_encode(['success' => 1, 'msg' => 'edit-0']);
                }
            }

        }

    }

    public function load_multi_satuan() {
        $data['id'] = $_POST['id'];
        $this -> load -> view('barang/data/multi_satuan', $data);
    }

    public function hps_multi_satuan() {
        $id = $_POST['id'];
        $data = $this -> db -> get_where('barang_satuan', ['id' => $id]) -> result();
        
        foreach($data as $item) {
            $this -> db -> delete('barang_satuan', ['id' => $item -> id]);
            $this -> db -> delete(
                'barang_grosir', 
                [
                    'id_brg'    => $item -> id_brg,
                    'id_satuan' => $item -> id_satuan,
                    'id_toko'   => $item -> id_toko,
                ]
            );

        }

        $this -> app -> tambah_aktivitas('Menghapus multi satuan');
    }

    public function toggle_multi_satuan() {
        $id = $_POST['id'];
        $update['is_multi_satuan'] = $_POST['active'];
        $this -> db -> update('barang', $update, ['id' => $id]);
    }

    public function submit_multi_satuan() {
        $input    = $this -> input -> post(null, TRUE);
        $tokoid   = $this -> session -> mart_toko;
        $idbrg    = $input['multi_satuan_brg'];
        $msg      = 'Terjadi kesalahan! harap periksa kembali';
        $success  = 0;
        $added    = 0; 
        $updated  = 0; 
       
        foreach($input['multi_satuan_id'] as $i => $v) {
            $satuan = $input['multi_satuan_name'][$i];
            $stok   = $input['multi_satuan_stock'][$i];
            $harga  = $input['multi_satuan_price'][$i];
            $beli   = $input['multi_satuan_beli'][$i];

            if(!empty($satuan)) {
                if($v == 0) {
                    $data = [
                        'id_brg'     => $idbrg,
                        'id_satuan'  => $satuan,
                        'isi'        => $stok,
                        'harga_jual' => form_uang($harga, false),
                        'harga_beli' => form_uang($beli, false),
                        'jenis'      => 2,
                        'id_toko'    => $tokoid
                    ];

                    $this -> db -> insert('barang_satuan', $data);
                    $msg   = 'Multi satuan sudah ditambahkan';
                    $added = 1;

                } else {
                    $data = [
                        'id_satuan'   => $satuan,
                        'isi'         => $stok,
                        'harga_jual'  => form_uang($harga, false),
                        'harga_beli'  => form_uang($beli, false),
                    ];

                    $get = $this -> db -> get_where('barang_satuan', ['id' => $v]) -> row();

                    $where['id_satuan']   = $get -> id_satuan;
                    $where['id_toko']     = $tokoid;
                    $where['id_brg']      = $idbrg;
                    $riwayat['id_satuan'] = $satuan;

                    $this -> db -> update('barang_satuan', $data, ['id' => $v]);
                    $this -> db -> update('riwayat_stok', $riwayat, $where);

                    $updated = 1;
                    $msg     = 'Multi satuan sudah diupdate';
                } 
                $success = 1;
            }
        }

        if($added == 1) {
            $this -> app -> tambah_aktivitas('Menambahkan multi satuan');
        }
        if($updated == 1) {
            $this -> app -> tambah_aktivitas('Update multi satuan');
        }
       
        echo json_encode(['success' => $success, 'msg' => $msg]);
    }
    
    public function load_grosir() {
        $data['id'] = $_POST['id'];
        $this -> load -> view('barang/data/grosir', $data);
    }
    
    public function load_grosir_list() {
        $data = $_POST;
        $this -> load -> view('barang/data/grosir_list', $data);
    }
    
    public function hps_grosir() {
        $id = $_POST['id'];
        $this -> db -> delete('barang_grosir', ['id' => $id]);
        $this -> app -> tambah_aktivitas('Menghapus harga grosir');
    }

    public function toggle_grosir() {
        $id = $_POST['id'];
        $update['is_grosir'] = $_POST['active'];
        $this -> db -> update('barang', $update, ['id' => $id]);
    }

    public function submit_grosir() {
        $input    = $this -> input -> post(null, TRUE);
        $toko     = $this -> session -> mart_toko;
        $idbrg    = $input['grosir_brg'];
        $satuan   = $input['grosir_satuan_brg'];
        $msg      = 'Terjadi kesalahan! harap periksa kembali';
        $success  = 0;
        $updated  = 0;
        $added    = 0;
       
        foreach($input['grosir_id'] as $i => $v) {
            $stok   = $input['min_stock'][$i];
            $harga  = $input['grosir_price'][$i];

            if(!empty($stok)) {
                if($v == 0) {
                    $data = [
                        'id_brg'     => $idbrg,
                        'id_satuan'  => $satuan,
                        'min'        => $stok,
                        'id_toko'    => $toko,
                        'harga'      => form_uang($harga, false),
                    ];

                    $this -> db -> insert('barang_grosir', $data);
                    $msg   = 'Harga grosir sudah ditambahkan';
                    $added = 1;

                } else {
                    $data = [
                        'min'      => $stok,
                        'harga'    => form_uang($harga, false),
                    ];

                    $this -> db -> update('barang_grosir', $data, ['id' => $v]);
                    $rows = $this -> db -> affected_rows();

                    if($rows > 0) {
                        $msg     = 'Harga grosir sudah diupdate';
                        $updated = 1;
                        
                    } else {
                        $msg     = 'update-0';
                    }
                } 
                $success = 1;
            }
        }

        if($added == 1) {
            $this -> app -> tambah_aktivitas('Menambahkan harga grosir baru');
        }
        if($updated == 1) {
            $this -> app -> tambah_aktivitas('Update harga grosir');
        }
       
        echo json_encode(['success' => $success, 'msg' => $msg]);
    }

    public function load_riwayat() {
        $data['input'] = $_POST;

        $this -> load -> view('barang/data/riwayat_stok', $data);
    }

    // Proses pembelian barang
    public function load_data_beli() {
        $this -> load -> view('pembelian/load');
    }

    public function load_list_brg() {
        $data['input'] = $_POST;
        $this -> load -> view('barang/list', $data);
    }

    public function hps_item_beli() {
        $where['id'] = $_POST['id'];
        $this -> db -> delete('pembelian_detail', $where);
    }

    public function update_qty_beli() {
        $where['id']   = $_POST['id'];
        $update['qty'] = $_POST['qty'];
        $this -> db -> update('pembelian_detail', $update, $where);
    }

    public function update_satuan_beli() {
        $where['id'] = $_POST['id'];

        $get    = $this -> db -> get_where('pembelian_detail', $where) -> row_array(); 
        $satuan = $this -> db -> get_where(
            'barang_satuan', 
            [
                'id_brg'     => $get['id_brg'],
                'id_satuan'  => $_POST['satuan']
            ]
        ) -> row_array();

        $update['id_satuan']  = $_POST['satuan'];
        $update['harga_beli'] = $satuan['harga_beli'];

        $this -> db -> update('pembelian_detail', $update, $where);
    }

    public function update_harga_beli() {
        $where['id']          = $_POST['id'];
        $update['harga_beli'] = form_uang($_POST['harga'], false);
        $this -> db -> update('pembelian_detail', $update, $where);
    }

    public function update_supplier_beli() {
        $where['id']   = $_POST['id'];
        $update['id_supplier'] = $_POST['supplier'];
        $this -> db -> update('pembelian_detail', $update, $where);
    }

    public function reset_transaksi_beli() {
        $where['id_toko']   = $this -> session -> mart_toko;
        $where['id_beli']   = 0;
        
        $this -> db -> delete('pembelian_detail', $where);
    }
    
    public function home_transaksi() {
       $data['input'] = $_POST;
       $this -> load -> view('transaksi/home', $data);
    }

    public function home_terlaris() {
       $this -> load -> view('barang/home');
    }

    public function select_item_beli() {
        $toko = $this -> session -> mart_toko;
        $kode = $_POST['kode'];

        $where_brg['kode']    = $kode;
        $where_brg['id_toko'] = $toko;

        $barang = $this -> db -> get_where('barang', $where_brg) -> row();
        
        if($barang) {
            $where_satuan['id_brg']  = $barang -> id;
            $where_satuan['id_toko'] = $toko;
            $where_satuan['jenis']   = 1;
            $satuan = $this -> db -> get_where('barang_satuan', $where_satuan) -> row();

            $where_beli['id_brg']     = $barang -> id;
            $where_beli['id_satuan']  = $satuan -> id_satuan;
            $where_beli['id_toko']    = $toko;
            $where_beli['id_beli']    = 0;

            $data_beli['id_brg']      = $barang -> id;
            $data_beli['qty']         = 1;
            $data_beli['id_satuan']   = $satuan -> id_satuan;
            $data_beli['id_supplier'] = $barang -> id_supplier;
            $data_beli['harga_beli']  = $satuan -> harga_beli;
            $data_beli['id_toko']     = $barang -> id_toko;
            $cek = $this -> db -> get_where('pembelian_detail', $where_beli) -> row();

            if($cek) {
                
                $up_beli['qty'] = $cek -> qty + 1; 
                $this -> db -> update('pembelian_detail', $up_beli, $where_beli);
                echo json_encode(['success' => 1, 'msg' => 'tersedia']);
                
            } else {
                $this -> db -> insert('pembelian_detail', $data_beli);
                echo json_encode(['success' => 1, 'msg' => 'Barang ditambahkan']);
            }
            
        } else {
            echo json_encode(['success' => 0, 'msg' => 'Barang tidak tersedia']);
        }

    }

    public function submit_transaksi_beli() {
        $toko  = $this -> session -> mart_toko;
        $kode  = 'TRB' . date('ymdhi') . rand(10, 99);
        $total = 0;
        $tgl   = date('Y-m-d H:i:s');

        $where['id_toko'] = $toko;
        $where['id_beli'] = 0;

        $data['kode']      = $kode;
        $data['id_toko']   = $toko;
        $data['tgl']       = $tgl;
        $data['id_admin']  = $this -> session -> mart_id;

        $this -> db -> insert('pembelian_data', $data);
        $id = $this -> db -> insert_id();

        $get = $this -> db -> get_where('pembelian_detail', $where) -> result();

        if($get) {
            foreach($get as $tr) {
                $update['id_beli'] = $id;
                $this -> db -> update('pembelian_detail', $update, $where);

                $where_stok['id_brg']    = $tr -> id_brg; 
                $where_stok['id_satuan'] = $tr -> id_satuan; 
                $where_stok['id_toko']   = $tr -> id_toko; 

                $get_stok = $this -> db -> get_where('barang_satuan', $where_stok) -> row();
                $new_stok = $get_stok -> stok + $tr -> qty;

                $riwayat['id_brg']     = $tr -> id_brg; 
                $riwayat['id_satuan']  = $tr -> id_satuan; 
                $riwayat['id_toko']    = $tr -> id_toko; 
                $riwayat['jml']        = $tr -> qty; 
                $riwayat['stok_awal']  = $get_stok -> stok; 
                $riwayat['stok_akhir'] = $new_stok; 
                $riwayat['tgl']        = $tgl; 
                $riwayat['id_admin']   = $this -> session -> mart_id;
                $riwayat['status']     = 1;                
                $update_stok['stok']   = $new_stok;

                $this -> db -> update('barang_satuan', $update_stok,  $where_stok);
                $this -> db -> insert('riwayat_stok', $riwayat);
                
                $total += $tr -> qty * $tr -> harga_beli;
            }
            
            $transaksi['kode']      = $kode;
            $transaksi['tgl']       = $tgl;
            $transaksi['total']     = $total;
            $transaksi['jenis']     = 2;
            $transaksi['id_admin']  =  $this -> session -> mart_id;;
            $transaksi['id_toko']   =  $this -> session -> mart_toko;;
            $this -> db -> insert('riwayat_transaksi', $transaksi);
            
            $this -> app -> tambah_aktivitas('Melakukan transaksi pembelian dengan kode ' . $kode);
            echo json_encode(['success' => 1, 'msg' => 'Trasaksi pembelian sudah disimpan']);

        } else {
            echo json_encode(['success' => 0, 'msg' => 'Belum ada transaksi']);
        }
    }

    // Proses penjualan barang
    public function load_data_jual() {
        $this -> load -> view('penjualan/keranjang');
    }

    public function load_list_plg() {
        $data['input'] = $_POST;
        $this -> load -> view('pelanggan/list', $data);
    }
    
    public function submit_plg_jual() {
        $input = $this -> input -> post(null, TRUE);
        $data  = [
            'nama'   => $input['nama_plg'],
            'nohp'   => $input['nohp_plg'],
            'alamat' => $input['alamat_plg'],
        ];

        $this -> db -> insert('pelanggan', $data);
        $id = $this -> db -> insert_id();

        echo json_encode(['success' => 1, 'id' => $id, 'nama' => $input['nama_plg']]);
    }
        
    public function update_qty_jual() {
        $where['id']   = $_POST['id'];
        $update['qty'] = $_POST['qty'];

        $cek = $this -> db -> get_where('penjualan_detail', $where) -> row();

        $where_get['id_brg']    = $cek -> id_brg; 
        $where_get['id_satuan'] = $cek -> id_satuan; 
        $where_get['id_toko']   = $cek -> id_toko; 
        $get    = $this -> db -> get_where('barang_satuan', $where_get) -> row();

        $where_brg['id']        = $cek -> id_brg;
        $where_brg['id_toko']   = $this -> session -> mart_toko;

        $brg = $this -> db -> get_where('barang', $where_brg) -> row();

        $this -> db -> where('min <= ', $_POST['qty']);
        $this -> db -> where('id_brg ', $cek -> id_brg);
        $this -> db -> where('id_satuan ', $cek -> id_satuan);
        $this -> db -> where('id_toko ', $cek -> id_toko);
        $this -> db -> order_by('id', 'desc');
        $grosir = $this -> db -> get('barang_grosir') -> row();

        if($grosir && $brg -> is_grosir == 1) {
            $update['harga_jual'] = $grosir -> harga;
            $update['is_grosir']  = 1;
            
        } else {
            $update['harga_jual'] = $get -> harga_jual;
            $update['is_grosir']  = 0;
        }

        if($_POST['qty'] > $get -> stok) {
            echo json_encode(['success' => 0, 'msg' => 'Stok tidak mencukupi']);
            exit;
        }

        $this -> db -> update('penjualan_detail', $update, $where);

        echo json_encode(['success' => 1]);
    }

    public function hps_item_jual() {
        $where['id'] = $_POST['id'];
        $this -> db -> delete('penjualan_detail', $where);

        echo json_encode(['success' => 1]);
    }

    public function clean_cart() {
        $where['id_toko']  = $this -> session -> mart_toko;
        $where['id_admin'] = $this -> session -> mart_id;
        $where['id_jual']  = 0;
        $this -> db -> delete('penjualan_detail', $where);

        echo json_encode(['success' => 1]);
    }

    public function update_satuan_jual() {
        $where['id']        = $_POST['id'];

        $where_cek['id_brg']    = $_POST['brg'];
        $where_cek['id_satuan'] = $_POST['satuan'];
        $where_cek['id_toko']   = $this -> session -> mart_toko;
        
        $get = $this -> db -> get_where('barang_satuan', $where_cek) -> row();
        $cek = $this -> db -> get_where('penjualan_detail', $where) -> row();

        $where_brg['id']        = $_POST['brg'];
        $where_brg['id_toko']   = $this -> session -> mart_toko;

        $brg = $this -> db -> get_where('barang', $where_brg) -> row();

        if($cek -> qty > $get -> stok) {
            echo json_encode(['success' => 0, 'msg' => 'stok tidak mencukupi']);
            exit;
        }

        $this -> db -> where('min <= ', $cek -> qty);
        $this -> db -> where('id_brg ', $cek -> id_brg);
        $this -> db -> where('id_satuan ', $_POST['satuan']);
        $this -> db -> where('id_toko ', $cek -> id_toko);
        $this -> db -> order_by('id', 'desc');
        $grosir = $this -> db -> get('barang_grosir') -> row();

        $update['id_satuan']  = $_POST['satuan'];

        if($grosir && $brg -> is_grosir == 1) {
            $update['harga_jual'] = $grosir -> harga;
            $update['is_grosir']  = 1;
            
        } else {
            $update['harga_jual'] = $get -> harga_jual;
            $update['is_grosir']  = 0;
        }

 
        $this -> db -> update('penjualan_detail', $update, $where);

        echo json_encode(['success' => 1]);
    }

    public function select_item_jual() {
        $toko  = $this -> session -> mart_toko;
        $admin = $this -> session -> mart_id;
        $kode = $_POST['kode'];

        $where_brg['kode']    = $kode;
        $where_brg['id_toko'] = $toko;

        $barang = $this -> db -> get_where('barang', $where_brg) -> row();
        
        if($barang) {
            $where_satuan['id_brg']  = $barang -> id;
            $where_satuan['id_toko'] = $toko;
            $where_satuan['stok > '] = 0;

            $satuan = $this -> db -> get_where('barang_satuan', $where_satuan);
            $cekto  = 0;

            foreach($satuan -> result() as $ceksa) {
                $cekto += $ceksa -> stok;
            }

            if($cekto == 0) {
                echo json_encode(['success' => 0, 'msg' => 'Stok item kosong']);
                exit;
            }

            $satuan = $satuan -> first_row();
            $data_jual['id_brg']      = $barang -> id;
            $data_jual['qty']         = 1;
            $data_jual['id_satuan']   = $satuan -> id_satuan;
            $data_jual['harga_jual']  = $satuan -> harga_jual;
            $data_jual['id_toko']     = $toko;
            $data_jual['id_admin']    = $admin;

            $where_jual['id_brg']    = $barang -> id;
            $where_jual['id_satuan'] = $satuan -> id_satuan;
            $where_jual['id_toko']   = $toko;
            $where_jual['id_admin']  = $admin;
            $where_jual['id_jual']   = 0;
            $cek = $this -> db -> get_where('penjualan_detail', $where_jual) -> row();
            
            if($cek) {
                if($cek -> qty + 1 > $satuan -> stok) {
                    echo json_encode(['success' => 0, 'msg' => 'Stok tidak mencukupi']);
                    exit;
                }

                $updateqty['qty'] = $cek -> qty + 1; 
                $cek = $this -> db -> update('penjualan_detail', $updateqty, $where_jual);

                echo json_encode(['success' => 1, 'msg' => 'tersedia']);
                
            } else {
                $this -> db -> insert('penjualan_detail', $data_jual);
                echo json_encode(['success' => 1, 'msg' => 'Item ditambahkan ke keranjang']);
            }
            
        } else {
            echo json_encode(['success' => 0, 'msg' => 'Item tidak tersedia']);
        }

    }

    public function simpan_cart() {
        $cart    = $this -> app -> get_keranjang();
        $admin   = $this -> session -> mart_id;
        $toko    = $this -> session -> mart_toko;
        $bayar   = form_uang($this -> input -> post('bayar', TRUE), false);
        $diskon  = form_uang($this -> input -> post('diskon', TRUE), false);
        $id_plg  = $this -> input -> post('id_plg', TRUE);
        $kode    = 'TRJ' . date('ymdhi') . rand(10, 99);
        $tgl     = date('Y-m-d H:i:s');
        
        $data['kode']       = $kode;
        $data['id_admin']   = $admin;
        $data['id_toko']    = $toko;
        $data['id_plg']     = $id_plg;
        $data['diskon']     = $diskon;
        $data['bayar']      = $bayar;
        
        $this -> db -> insert('penjualan_data', $data);

        $id_jual = $this -> db -> insert_id();
        $total   = 0;
        
        foreach($cart as $item) {
            $where_stok['id_satuan'] = $item -> id_satuan;
            $where_stok['id_toko']   = $item -> id_toko;
            $where_stok['id_brg']    = $item -> id_brg;

            $get_stok = $this -> db -> get_where('barang_satuan', $where_stok) -> row();
            $stok_akhir = $get_stok -> stok - $item -> qty;
            
            $riwayat_stok['id_brg']     = $item -> id_brg;
            $riwayat_stok['jml']        = $item -> qty;
            $riwayat_stok['stok_awal']  = $get_stok -> stok;
            $riwayat_stok['stok_akhir'] = $stok_akhir;
            $riwayat_stok['status']     = 2;
            $riwayat_stok['id_satuan']  = $item -> id_satuan;
            $riwayat_stok['id_toko']    = $item -> id_toko;
            $riwayat_stok['id_admin']   = $item -> id_admin;
            $riwayat_stok['tgl']        = $tgl;
            $update_stok['stok']        = $stok_akhir; 
            $total += $item -> qty * $item -> harga_jual;

            $this -> db -> update('penjualan_detail', ['id_jual' => $id_jual], ['id' => $item -> id]);
            $this -> db -> update('barang_satuan', $update_stok, $where_stok);
            $this -> db -> insert('riwayat_stok', $riwayat_stok);
        }        
        
        $riwayat_transaksi['kode']      = $kode;
        $riwayat_transaksi['tgl']       = $tgl;
        $riwayat_transaksi['id_admin']  = $admin;
        $riwayat_transaksi['id_toko']   = $toko;
        $riwayat_transaksi['total']     = $total;
        $riwayat_transaksi['jenis']     = 1;
        
        $this -> db -> update('penjualan_data', ['total' => $total], ['id' => $id_jual]);
        $this -> db -> insert('riwayat_transaksi', $riwayat_transaksi);
        $this -> app -> tambah_aktivitas('Melakukan transaksi penjualan dengan kode ' . $kode);

        echo json_encode(['success' => 1, 'redirect' => site_url('invoice/penjualan/' . base64_encode($kode))]);
    }

    // proses Riwayat Pembelian
    public function load_riwayat_beli() {
        $data['input'] = $_POST;

        $this -> load -> view('riwayat/pembelian_list', $data);
    }

    public function detail_riwayat_beli() {
        $data['input'] = $_POST;

        $this -> load -> view('riwayat/pembelian_detail_list', $data);
    }

    public function load_riwayat_jual() {
        $data['input'] = $_POST;

        $this -> load -> view('riwayat/penjualan_list', $data);
    }

    public function load_riwayat_retur() {
        $data['input'] = $_POST;

        $this -> load -> view('riwayat/retur_list', $data);
    }

    public function load_penjualan_retur() {
        $get    = $this -> db -> get_where('penjualan_data', ['id' => $_POST['id']]) -> row();
        $data   = $this -> app -> get_detail_belanja($get -> kode);

        $this -> load -> view('riwayat/penjualan_retur', ['data' => $data]);
    }

    public function submit_retur_brg() {
        $input = $this -> input -> post(null, TRUE);
        $data  = [];
        $count = 0;
        $total_baru = 0;
        
        if(isset($input['id'])) {
            foreach($input['id'] as $id) {
                if(isset($input['is_retur'][$id]))  {
                    $qty    = $input['qty'][$id];
                    $jenis  = $input['jenis'][$id];
                    $satuan = $input['id_satuan'][$id];
                    $brg    = $input['id_brg'][$id];
                    $ket    = $input['ket'][$id];    
    
                    $where['id'] = $id;
                    $get         = $this -> db -> get_where('penjualan_detail', $where) -> row(); 
                    $data_jual   = $this -> db -> get_where('penjualan_data', ['id' => $get -> id_jual]) -> row(); 
                    $kode_jual   = $data_jual -> kode;
                    $qty_baru    = $get -> qty - $qty; 
                    $total_baru += $get -> harga_jual * $qty_baru;
    
                    $data['id_jual']   = $id;
                    $data['qty']       = $qty;
                    $data['jenis']     = $jenis;
                    $data['id_brg']    = $brg;
                    $data['id_satuan'] = $satuan;
                    $data['id_toko']   = $get -> id_toko;
                    $data['ket']       = $ket;
                    $data['tgl']       = date('Y-m-d H:i:s');
                    
                    $update['qty'] = $qty_baru;
    
                    if($jenis == 2) {
                        $this -> db -> update('penjualan_detail', $update, $where);
                        $update_riwayat = 1;
                    }

                    $where_stok['id_brg']    = $brg;
                    $where_stok['id_satuan'] = $satuan;
                    $where_stok['id_toko']   = $get -> id_toko;

                    $get_stok = $this -> db -> get_where('barang_satuan', $where_stok) -> row();
                    
                    if($get_stok) {
                        $stok_lama = $get_stok -> stok;
                        $stok_baru = $stok_lama + $qty; 
                        $update_stok['stok'] = $stok_baru;
                        $this -> db -> update('barang_satuan', $update_stok, $where_stok);
                    }
    
                    $this -> db -> insert('penjualan_retur', $data);
                    $count++;
                }
            }
        }

        if($count > 0) {
            echo json_encode(['success' => 1, 'msg' => 'Barang sudah diretur']);
            if(isset($update_riwayat)) {
                $this -> db -> update('riwayat_transaksi', ['total' => $total_baru], ['kode' => $kode_jual]);
            }

        } else {
            echo json_encode(['success' => 1, 'msg' => 'selected-0']);
        }
    }

    public function load_riwayat_semua() {
        $data['input'] = $_POST;

        $this -> load -> view('riwayat/semua_list', $data);
    }

    public function detail_riwayat_jual() {
        $data['input'] = $_POST;

        $this -> load -> view('riwayat/penjualan_detail_list', $data);
    }

    // Proses data toko
    public function load_toko() {
        $this -> load -> view('toko');
    }
    
    public function get_toko() {
        $data = $this -> db -> get_where('toko', ['id' => $_POST['id']]) -> row();
        echo json_encode($data);
    }
    
    public function hapus_toko() {
        $this -> db -> delete('toko', ['id' => $_POST['id']]);
        $this -> db -> delete('barang_satuan', ['id_toko' => $_POST['id']]);
        $this -> app -> tambah_aktivitas('Menghapus data toko ' . $_POST['nama']);
    }
    
    public function masuk_toko() {
        $sesi = $this -> session -> mart_id;
        $update['mart_toko'] = $_POST['id'];
        $this -> db -> update('admin', ['id_toko' => $_POST['id']], ['id' => $sesi]);
        $this -> session -> set_userdata($update);
    }
    
    public function submit_toko() {
        $input = $this -> input -> post(null, TRUE);

        $data = [
            'nama'   => $input['namatoko'],
            'alamat' => $input['alamatoko'],
            'cabang' => 2,
        ];

        if($input['idtoko'] == 0) {
            $this -> db -> insert('toko', $data);

            $this -> app -> tambah_aktivitas('Tambah toko baru ' . $input['namatoko']);
            echo json_encode(['success' => 1, 'msg' => 'Data toko baru sudah ditambahkan']);

        } else {
            $this -> db -> update('toko', $data, ['id' => $input['idtoko']]);
            $rows = $this -> db -> affected_rows();

            if($rows > 0) {
                $this -> app -> tambah_aktivitas('Update data toko ' . $input['namatoko']);
                echo json_encode(['success' => 1, 'msg' => 'Data toko sudah diupdate']);
            } else {
                echo json_encode(['success' => 1, 'msg' => 'update-0']);
            }
        }
    }

    // Proses laporan
    public function load_laporan_stok() {
        $_POST['limit'] = 25;
        $data['input']  = $_POST;
        $this -> load -> view('laporan/stok/data', $data);
    }

    public function load_laporan_jual() {
        $_POST['limit'] = 25;
        $data['input']  = $_POST;
        $this -> load -> view('laporan/penjualan/data', $data);
    }

    public function load_laporan_beli() {
        $_POST['limit'] = 25;
        $data['input']  = $_POST;
        $this -> load -> view('laporan/pembelian/data', $data);
    }

    public function load_laporan_retur() {
        $_POST['limit'] = 25;
        $data['input']  = $_POST;
        $this -> load -> view('laporan/retur/data', $data);
    }

    public function load_laporan_opname() {
        $_POST['limit'] = 25;
        $data['input']  = $_POST;
        $this -> load -> view('laporan/opname/data', $data);
    }

    public function load_laporan_keuangan() {
        $_POST['limit'] = 25;
        $data['input']  = $_POST;
        $this -> load -> view('laporan/keuangan/data', $data);
    }

    // Proses pengaturan
    public function upload_logo() {
        $file = $_FILES['file']['name'];
        $old  = $this -> app -> get_app('logo');

        if(!empty($file)) {
            $config['file_name'] 	 = time(); 
            $config['upload_path']   = 'uploads/'; 
            $config['allowed_types'] = 'jpeg|jpg|png'; 
            $config['file_size'] 	 = 1024;

            $this -> load -> library('upload', $config);

            if(file_exists('uploads/' . $old)) {
                unlink('uploads/' . $old);
            }
	
            if($this->upload->do_upload('file')) {
                $name = $this -> upload -> data('file_name');	
                $where['logo']  = $old;
                $update['logo'] = $name;
                $this -> db -> update('app', $update, $where);

                echo json_encode(['success' => 1, 'msg' => 'Logo sudah diupdate']);
            } else {
                $error = $this->upload->display_errors('<span>', '</span>');
                echo json_encode(['success' => 0, 'msg' => $error]);
            }
        } else {
            echo json_encode(['success' => 0, 'msg' => 'update-0']);
        }
    }

    public function update_thermal_size() {
        $this -> db -> update('app', ['thermal_size' => $_POST['val']]);
        echo json_encode(['success' => 1, 'msg' => 'Thermal paper sudah diupdate']);
    }

    public function update_app() {
        if(!empty($_FILES['file']['name'])) {
            $name       = $_FILES['file']['name'];
            $explode    = explode('.', $name);
            $filename   = $explode[0];
            $ext        = $explode[1];

            if($ext == 'zip') {
                $path     = './';
                $location = $path . $name;

                if(move_uploaded_file($_FILES['file']['tmp_name'], $location)) {
                    $zip = new ZipArchive;
                    if($zip -> open($location)) {
                        $zip -> extractTo($path);
                        $zip -> close();

                        echo json_encode(['success' => 1, 'msg' => 'Update berhasil']);
                        
                    } else {
                        echo json_encode(['success' => 0, 'msg' => 'Update Gagal']);
                    }
                    
                    unlink($location);
                }
            } else {
                echo json_encode(['success' => 0, 'msg' => 'Hanya mendukung format .zip']);
            }
        }
    }
    
    public function create_users() {
        // $data = [
        //     'nama'      => 'Akun Demo Admin',
        //     'email'     => 'admin.demo@cimart.com',
        //     'password'  => password_hash('admin.demo@2023', PASSWORD_DEFAULT),
        //     'level'     => 'admin',
        //     'id_toko'   => 1
        // ];

        // $this -> db -> insert('admin', $data);
        
        $this -> load -> view('tes');
    }
}

// Controller Proses
// Kode ini dibuat dan dikembangkan oleh codelingker