<?php 

class App_model extends CI_Model {
    public function kurir() {
        $get  = $this -> db -> get_where('kurir', ['status' => 1]) -> result();
        $data = [];

        foreach($get as $item) {
            $item -> logo = base_url('upload/ekspedisi/'. $item -> code . '.png');
            $data[] = $item;
        }

        return $data;
    }

    public function get_app($name = 'semua') {
        if($name == 'semua') {
            $get  = $this -> db -> get('app') -> result();
            $data = [];

            foreach($get as $item) {
                $data[$item -> name] = $item -> value;
            }

            return $data;

        } else {
            $get  = $this -> db -> get_where('app', ['name' => $name]) -> row();
            return $get ? $get -> value : null;
        }
    }

    private function set_produk($obj) { 
        if($obj -> id == 'semua') {
            if(is_int($obj -> limit)) {
                $this -> db -> limit($obj -> limit, $obj -> index);
            }
            if($obj -> random) {
                $this -> db -> order_by('RAND()');
            }
            
            if($obj -> kategori) {
                $this -> db -> where('kategori', $kategori);
            }

            if($obj -> search) {
                $this -> db -> like('nama', $obj -> search);
            }

            $this -> db -> order_by('id', $obj -> ordering);
            $data = $this -> db -> get('produk') -> result();
            $new  = [];

            foreach($data as $item) {
                $varian   = $this -> get_varian($item -> id);
                $kategori = $this -> get_kategori($item -> kategori, 'nama');

                $min  = $varian ? min(array_column($varian, 'harga')) : $item -> harga;
                $max  = $varian ? max(array_column($varian, 'harga')) : $item -> harga;

                $item -> range_min = $varian ? $min : $item -> harga;
                $item -> range_v2  = $varian ? 
                        short_uang($min) .' ~ '.  short_uang($max) : 
                        short_uang($item -> harga);
                $item -> range_v1  = $varian ? 
                        format_uang($min) .' ~ '. format_uang($max) : 
                        format_uang($item -> harga);
                $item -> range_v2  = $varian ? 
                        short_uang($min) .' ~ '.  short_uang($max) : 
                        short_uang($item -> harga);

                $item -> nama_kategori = $kategori ? $kategori : null;
                $item -> diskon_label  = $item -> diskon > 0 ? diskon_produk($item -> harga, $item -> diskon) : null;
                $item -> varian = $varian;

                $new[] = $item;
            }

            return $new;

        } else {
            $get      = $this -> db -> get_where('produk', ['id' => $obj -> id]) -> row();
            $varian   = $this -> get_varian($get -> id);
            $kategori = $this -> get_kategori($get -> kategori, 'nama');

            $min = $varian ? min(array_column($varian, 'harga')) : $get -> harga;
            $max = $varian ? max(array_column($varian, 'harga')) : $get -> harga;
            
            $get -> range_v1  = $varian ? 
                    format_uang($min) .' ~ '. format_uang($max) : 
                    format_uang($get -> harga);
            $get -> range_v2  = $varian ? 
                    short_uang($min) .' ~ '.  short_uang($max) : 
                    short_uang($get -> harga);

            $get -> nama_kategori = $kategori ? $kategori : null;
            $get -> diskon_label  = $get -> diskon > 0 ? diskon_produk($get -> harga, $get -> diskon) : null;
            $get -> varian        = $varian;

            return $get ? $get : null;
        }
    }

    public function get_produk($array = []) {
        $object = (object) [
            'id'       => isset($array['id']) ? $array['id'] : 'semua',
            'limit'    => isset($array['limit']) ? $array['limit'] : 'semua',
            'index'    => isset($array['index']) ? $array['index'] : 0,
            'random'   => isset($array['random']) ? $array['random'] : '',
            'kategori' => isset($array['kategori']) ? $array['kategori'] : '',
            'search'   => isset($array['search']) ? $array['search'] : '',
            'ordering' => isset($array['ordering']) ? $array['ordering'] : 'DESC'
        ];

        return $this -> set_produk($object);
    }

    public function get_varian($id = '') { 
        $data   = $this -> db -> get_where('varian', ['id_produk' => $id]) -> result();
        $new    = [];
        foreach($data as $item) {
            $sub = $this -> get_varian_sub($item -> id);
            if($sub) {  
                foreach($sub as $var) {
                    $new[] = (object) [
                        'id_varian'    => $var -> id,
                        'is_sub'       => 1,
                        'nama_varian'  => $item -> nama . ' ('. $var -> nama .')',
                        'stok'         => $var -> stok,
                        'harga'        => $var -> harga,
                        'diskon'       => $var -> diskon,
                    ];
                }             

            } else {
                $new[] = (object) [
                    'id_varian'    => $item -> id,
                    'is_sub'       => 0,
                    'nama_varian'  => $item -> nama,
                    'stok'         => $item -> stok,
                    'harga'        => $item -> harga,
                    'diskon'       => $item -> diskon,
                ];
            }

        }

        return $new;
    }

    public function get_varian_sub($id) {
        return $this -> db -> get_where('varian_sub', ['id_varian' => $id]) -> result();
    }

    public function get_detail_varian($id, $is_sub, $kolom = 'semua') {
        if($is_sub == 0) {
            $varian = $this -> db -> get_where('varian', ['id' => $id]) -> row();
        } else {
            $data = $this -> db -> get_where('varian_sub', ['id' => $id]) -> row();
            $var  = $this -> db -> get_where('varian', ['id' => $data -> id_varian]) -> row();
            $data -> nama = $var -> nama . ' ('.$data -> nama.')';
            $varian = $data;
        }
        
        if($varian) {
            return $kolom == 'semua' ? $varian : $varian -> $kolom;
        }
    }

    public function get_kategori($id = 'semua', $kolom = 'semua') {
        if($id == 'semua') {
            return $this -> db -> get('kategori') -> result();

        } else {
            $get = $this -> db -> get_where('kategori', ['id' => $id]) -> row();

            if($kolom == 'semua') {
                return $get;

            } else {
                return $get ? $get -> $kolom : null;
            }
        }
    }

    public function get_produk_terkait($id = 'semua', $idkat, $limit = 10) { 
        $this -> db -> where('status', 1);       
        $this -> db -> where('kategori', $idkat);
        $this -> db -> where('id != ', $id);
        $get = $this -> db -> get('produk') -> result();
        $new = []; 

        foreach($get as $item) {
            $varian = $this -> get_varian($item -> id);
            $min    = $varian ? min(array_column($varian, 'harga')) : ($item -> harga - $item -> diskon);

            $new[] = (object) [
                'id'    => $item -> id,
                'nama'  => $item -> nama,
                'harga' => $min
            ];
        }

        return $new;
    }

    public function get_kurir($id = 'semua') { 
        $this -> db -> where('status', 1);       
        if($id == 'semua') {
            return $this -> db -> get('kurir') -> result();

        } else {
            $get  = $this -> db -> get_where('kurir', ['id' => $id]) -> row();
            return $get ? $get : null;
        }
    }

    public function get_img_produk($id, $i = 1) { 
        $get = $this -> db -> get_where('produk', ['id' => $id]) -> row();
        if(is_int($i) && $i <= 4) {
            if($i == 1) {
                $img = $get -> img_1;
            } else if($i == 2) {
                $img = $get -> img_2;
            } else if($i == 3) {
                $img = $get -> img_3;
            } else if($i == 4) {
                $img = $get -> img_4;
            }

            return base_url('upload/produk/' . $img); 
        }
    }

    public function searching($search = '') {
        $html = '';
        $data = $this -> get_produk(
            [
                'limit'  => 10,
                'search' => $search
            ]
        );

        if($data) {
            foreach($data as $item) {
                $html .= '
                    <li>
                        <a href="'.slug($item -> id, 'produk').'" class="d-flex justify-content-between align-items-start">
                            <div class="_img">
                                <img src="'.$this -> get_img_produk($item -> id) .'" alt="img">
                            </div>
                            <div class="_text">
                                <p>
                                    '. $item -> nama .'
                                </p>
                            </div>
                        </a>
                    </li> 
                ';
            }

        } else {
            if($search) {
                $html = '
                    <li class="text-center">
                        <span>Produk tidak tersedia</span>
                    </li>
                ';
            } else {
                $html = '
                    <li class="text-center">
                        <span>Belum ada produk</span>
                    </li>
                ';
            }
        }

        return $html;
    }

    public function autoupdate() {
        $sesi   = $this -> session -> ci_usrid;
        $today  = time();
        $where  = [
            'usrid'         => $sesi, 
            'status'        => 0,
            'kadaluarsa < ' => date('Y-m-d H:i:s', $today)
        ];

        $get_topup      = $this -> db -> get_where('saldo_riwayat', $where) -> result();        
        $get_order      = $this -> db -> get_where('transaksi', $where) -> result();
        
        if($get_order) {
            $detail_order   = $this -> db -> get_where('transaksi_detail', ['id_transaksi' => $get_order -> id]) -> row();
            $jenis          = $detail_order ? $detail_order -> jenis : 'Fisik'; 
            $url_notif      = "akun/pesanan?produk=$jenis";

            foreach ($get_order as $item) { 
                $this -> db -> update('transaksi', ['status' => 4], ['id' => $item -> id]);

                $notif_order    = [
                    'jenis'     => 'batal',
                    'judul'     => 'Pesanan dibatalkan',
                    'usrid'     => $sesi,
                    'url'       => $url_notif,
                    'deskripsi' => 'Pesanan ' . $item -> invoice . ' dibatalkan otomatis oleh sistem.'
                ];
        
                $this -> app -> push_notif($notif_order);
            }
        }
        
        if($get_topup) {
            foreach ($get_topup as $item) { 
                $this -> db -> update('saldo_riwayat', ['status' => 2], ['id' => $item -> id]);
                
                $url_top = 'saldo?detail=' . $item -> token;
                $notif_topup      = [
                    'jenis'     => 'batal',
                    'judul'     => 'Topup dibatalkan',
                    'usrid'     => $sesi,
                    'url'       => $url_top,
                    'deskripsi' => 'Permintaan topup '. $item -> kode_ref .' dibatalkan otomatis oleh sistem. '
                ];
        
                $this -> app -> push_notif($notif_topup);
            }

        }
    }
    
    public function get_transaksi_produk($array = null) {
        if($array) {
            $obj = (object) $array;
            if($obj -> id_transaksi == 0) {
                $this -> db -> where('id_transaksi', 0);
            }
            $this -> db -> where('varian', $obj -> varian);
            $this -> db -> where('varian_sub', $obj -> varian_sub);
            $this -> db -> where('id_produk', $obj -> id_produk);
            $this -> db -> where('id_user', $obj -> id_user);
            return $this -> db -> get('transaksi_detail') -> row();
        }
    }

    public function get_detail_transaksi($id) {
        $get    = $this -> db -> get_where('transaksi', ['token' => $id]) -> row();

        if($get) {
            $detail = $this -> db -> get_where('transaksi_detail', ['id_transaksi' => $get -> id]) -> result();
            $produk = [];

            foreach($detail as $row) {
                $getprd = $this -> get_produk(['id' => $row -> id_produk]); 
                $varian = $this -> get_detail_varian($row -> varian, $row -> varian_sub, 'nama');
                
                $produk[] = (object) [
                    'nama_produk' => $getprd -> nama,
                    'varian'      => $varian,
                    'jml'         => $row -> jml,
                    'harga'       => $row -> harga,
                    'subtotal'    => $row -> jml * $row -> harga,
                    'img'         => $this -> get_img_produk($getprd -> id),
                    'slug'        => slug($getprd -> id, 'produk'),
                    'catatan'     => $row -> catatan,
                    'jenis'       => $row -> jenis,
                ];
            }
            
            if($get -> gateway == 'Tripay') {
                $payment = $this -> db -> get_where('transaksi_tripay', ['merchant_ref' => $get -> invoice]) -> row();
            }
    
            $get -> kode_bayar = isset($payment) ? $payment -> pay_code : null;
            $get -> detail     = $produk;
    
            return $get;
        }
    }

    public function get_riwayat_saldo() {
        $sesi   = $this -> session -> ci_usrid;
        $new    = [];

        $this -> db -> order_by('id DESC');
        $riwayat = $this -> db -> get_where('saldo_riwayat', ['usrid' => $sesi, 'status >' => 0]) -> result();

        $this -> db -> order_by('id ASC');
        $topup  = $this -> db -> get_where('saldo_riwayat', ['usrid' => $sesi, 'status' => 0]) -> result();

        foreach($topup as $item) {
            $item -> jenis = 'topup';
            $new[] = $item;
        } 
        
        foreach($riwayat as $item) {
            $item -> jenis = 'riwayat';
            $new[] = $item;
        } 

        return $new;
    }

    public function get_detail_topup($id) {
        $get = $this -> db -> get_where('saldo_riwayat', ['token' => $id]) -> row();

        if($get) {
            $get -> invoice = $get -> kode_ref;
            $get -> total   = $get -> nominal;
            $get -> metode_bayar   = $get -> payment_code;

            return $get;
        }
    }

    public function get_semua_transaksi($status = 'semua', $jenis = 'semua') {
        if($status != 'semua') {
            $this -> db -> where('status', $status);
        } 

        if($status > 0) {
            $this -> db -> order_by('id', 'DESC');
        } 

        $sesi  = $this -> session -> ci_usrid;
        $data  = $this -> db -> get_where('transaksi', ['usrid' => $sesi]) -> result(); 
        $today = time();
        $new   = [];

        foreach($data as $item) {
            if($jenis != 'semua') {
                $this -> db -> where('jenis', ucwords($jenis));
            }

            $detail = $this -> db -> get_where('transaksi_detail', ['id_transaksi' => $item -> id]) -> result();
            $exp    = strtotime($item -> kadaluarsa);
            $payload = [
                'produk' => $jenis,
                'detail' => $item -> token
            ];

            if($detail) {
                $item -> thumb      = $this -> get_img_produk($detail[0] -> id_produk); 
                $item -> view       = site_url('akun/pesanan?' . http_build_query($payload)); 
                $item -> jml_order  = count($detail) . ' Barang'; 
                $item -> total_tr   = $item -> total + $item -> biaya_admin + $item -> ongkir; 
                $item -> detail     = $detail;
                
                if($exp > $today) {
                    $new[] = $item;
                    
                } else if($item -> status > 0) {
                    $new[] = $item;
                } 
            }
        }

        return $new;
    }

    public function get_keranjang($group = true) {
        $sesi = $this -> session -> ci_usrid;
        $this -> db -> order_by('id', 'DESC');
        $data = $this -> db -> get_where('transaksi_detail', ['id_user' => $sesi, 'id_transaksi' => 0]) -> result();
        $new  = [];

        if($data) {
            foreach($data as $item) {
                $produk = $this -> get_produk(['id' => $item -> id_produk]);
                $varian = $this -> get_detail_varian($item -> varian, $item -> varian_sub, 'nama');
    
                $item -> nama_produk = $produk -> nama;
                $item -> nama_varian = $varian;

                if($group == 'semua') {
                    $new[$item -> jenis][] = $item;
                    
                } else {
                    $new[] = $item;
                }
            }
        }

        return $new;
    }

    public function get_jml_keranjang() {
        $sesi = $this -> session -> ci_usrid;
        $row = $this -> db -> get_where('transaksi_detail', ['id_user' => $sesi, 'id_transaksi' => 0]) -> num_rows();
        return $row;
    }

    public function total_keranjang($jenis = 'semua') {
        $sesi  = $this -> session -> ci_usrid;
        $total = 0;
               
        if($jenis == 'fisik') {
            $row   = $this -> db -> get_where('transaksi_detail', ['id_user' => $sesi, 'id_transaksi' => 0, 'jenis' => 'Fisik']) -> result();

            foreach($row as $item) {
                $total += $item -> jml * $item -> harga;
            }
    
            return $total;

        } else if($jenis == 'digital') {
            $row   = $this -> db -> get_where('transaksi_detail', ['id_user' => $sesi, 'id_transaksi' => 0, 'jenis' => 'Digital']) -> result();

            foreach($row as $item) {
                $total += $item -> jml * $item -> harga;
            }
    
            return $total;

        } else {
            $row   = $this -> db -> get_where('transaksi_detail', ['id_user' => $sesi, 'id_transaksi' => 0]) -> result();
            foreach($row as $item) {
                $total += $item -> jml * $item -> harga;
            }
    
            return $total;
        }
    }

    public function get_user($id, $kolom = 'semua') {
        $this -> db -> where('id', $id);
        $this -> db -> or_where('email', $id);
        $get = $this -> db -> get('user') -> row();
        
        if($kolom == 'semua') {
            $getmax = $this -> db -> get_where('saldo_max', ['level' => $get -> level]) -> row();
            $get -> max_saldo = $getmax -> max;
            
            return $get;
        } else {
            $getmax = $this -> db -> get_where('saldo_max', ['level' => $get -> level]) -> row();
            $get -> max_saldo = $getmax -> max;

            return $get ? $get -> $kolom : null;
        }
    }

    public function get_init($str) {
        $str = str_split($str);
        return $str[0];
    }

    public function get_saldo($format = false) {
        $id      = $this -> session -> ci_usrid;  
        $get     = $this -> db -> get_where('saldo', ['usrid' => $id]) -> row();
        $get     = $get ? $get : new stdClass();
        $riwayat = $this -> db -> get_where('saldo_riwayat', ['usrid' => $id, 'status' => 1]) -> last_row();
        $get -> saldo = $riwayat && $riwayat -> saldo_akhir == $get -> saldo ? $get -> saldo : 0;

        if($format) {
            return $get ? format_uang($get -> saldo) : 0;
            
        } else {
            return $get ? $get -> saldo : 0;
        }
    }

    public function cek_topup_status($status = 0) {
        $sesi = $this -> session -> ci_usrid;
        $get  = $this -> db -> get_where('saldo_riwayat', ['status' => $status, 'usrid' => $sesi]) -> row();

        return $get;
    }

    public function get_notif($jenis = null) {
        $this -> db -> limit(100);
        $this -> db -> order_by('id', 'DESC');
        $id  = $this -> session -> ci_usrid;  
        
        if($jenis === 0) {
            $this -> db -> where('is_read', 0);
        }
        
        $get = $this -> db -> get_where('notif', ['usrid' => $id]) -> result();
        $new = [];

        foreach($get as $item) {
            switch($item -> jenis) {
                case 'blm_bayar':
                    $bg     = 'bg-warning';
                    $text   = 'text-warning';
                    $icon   = 'fa fa-list-check';
                break;
    
                case 'diproses':
                    $bg     = 'bg-primary';
                    $text   = 'text-primary';
                    $icon   = 'fa fa-box-open';
                break;
    
                case 'dikirim':
                    $bg   = 'bg-primary';
                    $text = 'text-primary';
                    $icon = 'fa fa-truck-fast';
                break;
    
                case 'selesai':
                    $bg   = 'bg-success';
                    $text = 'text-success';
                    $icon = 'fa fa-check';
                break;
    
                case 'batal':
                    $bg     = 'bg-danger';
                    $text   = 'text-danger';
                    $icon   = 'fa fa-times';
                break;

                case 'topup_saldo':
                    $bg     = 'bg-warning';
                    $text   = 'text-warning';
                    $icon   = 'fa fa-wallet';
                break;
    
                case 'topup_sukses':
                    $bg     = 'bg-success';
                    $text   = 'text-success';
                    $icon   = 'fa fa-wallet';
                break;
    
                default:
                    $bg     = 'bg-primary';
                    $text   = 'text-primary';
                    $icon   = 'fa fa-bell';
                break;
            }

            $item -> url       = $item -> url ? $item -> url : 'javascript:void(0)';
            $item -> is_read   = $item -> is_read == 0 ? 'bg-light' : null;
            $item -> bg        = $bg;
            $item -> icon      = $icon;
            $item -> color     = $text;

            $new[] = $item;
        }

        return $new;
    }

    public function push_notif($array) {
        $obj  = (object) $array;
        $obj  ->  jenis = isset($obj -> jenis) ? $obj -> jenis : 'lainnya'; 

        $push = [
            'url'       => $obj -> url,
            'jenis'     => $obj -> jenis,
            'judul'     => $obj -> judul,
            'deskripsi' => $obj -> deskripsi,
            'usrid'     => isset($obj -> usrid) ? $obj -> usrid : 0,
            'tgl'       => date('Y-m-d H:i:s'),
            'token'     => md5(date('dmYGis') . rand(11111, 99999)),
        ];

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

    public function get_favorit($produk = 'semua') {    
        $id = $this -> session -> ci_usrid;    
        if($produk == 'semua') {
            $get = $this -> db -> get_where('favorit', ['usrid' => $id]) -> result();
            $new = [];
            foreach($get as $item) {
                $produk = $this -> get_produk(['id' => $item -> id_produk]);
                $item -> nama_produk = $produk -> nama;
                $new[] = $item;
            }
            return $new;

        } else {
            $get = $this -> db -> get_where('favorit', ['usrid' => $id, 'id_produk' => $produk]) -> row();
            return $get;
        }
    }

    public function get_prov($id = 'semua', $kolom = '') {
        if($id == 'semua') {
            $data = $this -> db -> get('data_prov') -> result();
            return $data;
            
        } else {
            $data = $this -> db -> get_where('data_prov', ['id' => $id]) -> row();

            if($kolom) {
                return $data ? $data -> $kolom : null;

            } else {
                return $data;
            }

        }
    }

    public function get_kab($prov = 'semua', $id = 'semua', $kolom = '') {
        if($prov == 'semua') {
            $data = $this -> db -> get_where('data_kab', ['id' => $id]) -> row();

            if($kolom) {
                return $data ? $data -> $kolom : null;
            } else {
                return $data ? $data : null;
            }

        } else {
            $data = $this -> db -> get_where('data_kab', ['prov' => $prov]) -> result();
            return $data;
        }
    }

    public function get_kec($kab = 'semua', $id = 'semua', $kolom = '') {
        if($kab == 'semua') {
            $data = $this -> db -> get_where('data_kec', ['id' => $id]) -> row();

            if($kolom) {
                return $data ? $data -> $kolom : null;
            } else {
                return $data ? $data : null;
            }

        } else {
            $data = $this -> db -> get_where('data_kec', ['kab' => $kab]) -> result();
            return $data;
        }
    }

    public function get_kel($kec, $id = 'semua') {
        $data = $this -> db -> get_where('data_kel', ['kec' => $kec]) -> result();
        return $data;
    }

    public function get_alamat($id = 'semua') {
        $sesi = $this -> session -> ci_usrid;
        if($id == 'semua') {
            $this -> db -> order_by('id ASC, utama DESC');
            $data = $this -> db -> get_where('alamat', ['usrid' => $sesi]) -> result();
            return $data;
            
        } else if($id == 'cek_primary') {
            $data = $this -> db -> get_where('alamat', ['usrid' => $sesi, 'utama' => 1]) -> row();
            return $data;

        } else {
            $data = $this -> db -> get_where('alamat', ['id' => $id, 'usrid' => $sesi]) -> row();
            return $data;
        }
    }

    public function get_rekening($id = 'semua') {
        $sesi = $this -> session -> ci_usrid;
        if($id == 'semua') {
            $this -> db -> order_by('id DESC');
            $data = $this -> db -> get_where('user_rekening', ['usrid' => $sesi]) -> result();
            return $data;
            
        } else {
            $data = $this -> db -> get_where('user_rekening', ['token' => $id]) -> row();
            return $data;
        }
    }

    public function get_bank_bayar($id = 'semua', $kolom = null) {
        if($id == 'semua') {
            $get = $this -> db -> get('bank') -> result();
            return $get;
            
        } else {
            $this -> db -> where('id', $id);
            $this -> db -> or_where('kode', $id);
            $get = $this -> db -> get('bank') -> row();

            if($kolom) {
                return $get ? $get -> $kolom : null;

            } else {
                return $get;
            }
        }
    }
}

// Mode APP
// Kode ini dibuat oleh codelingker