<?php

namespace App\Http\Controllers\master;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Yajra\Datatables\Datatables;
use Illuminate\Support\Facades\Session;

class KomposisiController extends Controller
{
    //
    public function __construct(){      
        $this->middleware(function ($request, $next) {
        $url = request()->segment(1);
        $kode_group = Session::get('kode_group');
        $d_menu = DB::table("tb_menu as a")->join("tb_role as b","a.kode_menu","b.kode_menu")->where([['a.link_menu',$url],['b.kode_group',$kode_group],['b.status_role','1'],['a.active','1']])->orderBy('a.sort_menu','asc')->count();
        if(Session::get('decode') <> 1)
         {
            Session::flash('message', 'Silahkan login dengan username dan password anda.!!');
             return redirect()->to('login');
         }
         if($d_menu == 0){
            Session::flush();
            Session::flash('message', 'Anda Tidak Punya Akses ke Halaman ini.!!');
             return redirect()->to('login');
         }
        return $next($request); 
        });
    }

    public function index(){
    	$d_data = DB::table('ms_warnakomposisi as mw')->join('ms_satuan as ms','mw.satuan','ms.id_satuan')->get();
    	return view("master.KomposisiList")->with('data',$d_data);
    }

    public function tambah(){
    	$data['data'] = $this->data(array());
    	$data['satuan'] = DB::table('ms_satuan')->get();
        $data['gudang'] = DB::table('ms_gudang')->orderBy('nama_gudang')->get();
    	return view("master.KomposisiAdd")->with('data',$data);	
    }

    function get_data(){
        DB::statement(DB::raw('set @rownum=0'));
        $d_data = DB::table('ms_warnakomposisi as mw')->join('ms_satuan as ms','mw.satuan','ms.id_satuan')->select(DB::raw('*, @rownum  := @rownum  + 1 AS rownum'))->get();

        return Datatables::of($d_data)
                ->addColumn('aksi', function($d_data){
                    $btnAction = '<center><a class="btn bg-warning-400" href="'.url('komposisi/edit/'.$d_data->id_komposisi).'"><i class="icon-pencil"></i> </a> <button class="btn bg-danger-800" type="button" onclick="hapus('.$d_data->id_komposisi.')"><i class="icon-eraser"></i></button></center>'
                        ;
                    return $btnAction;
                })
                ->make(true);
    }

    function get_barang(){
    	$d_data = DB::table('ms_barang AS mb')->join('ms_kategori_barang AS mkb', 'mb.id_kb', 'mkb.id_kb')->join('ms_kategori_barang AS mkb2', 'mkb.induk_kb', 'mkb2.id_kb')->join('ms_satuan AS ms', 'mb.id_satuan', 'ms.id_satuan')->select(DB::raw('mb.*, mkb2.id_kb AS id_kategori, mkb2.nama nama_kategori, mkb.id_kb id_sub, mkb.nama nama_sub, ms.id_satuan, ms.nama_satuan'));

        if($d_data->count() > 0){
            foreach($d_data->orderBy('nama_kategori', 'asc')->orderBy('nama_sub', 'asc')->orderBy('kode_barang', 'asc')->orderBy('nama_barang', 'asc')->get() as $d){
                $arr[] = array('id_barang' => $d->id,
                                'kode_barang' => $d->kode_barang,
                                'nama_barang' => $d->nama_barang,
                                'id_kategori' => $d->id_kategori,
                                'kategori' => $d->nama_kategori,
                                'id_sub' => $d->id_sub,
                                'nama_sub' => $d->nama_sub,
                                'satuan' => $d->nama_satuan);
            }
        }else{
            $arr = array();
        }

        return response()->json($arr);
    }

    function get_satuan(){
    	$d_data = DB::table('ms_satuan AS ms');

        if($d_data->count() > 0){
            foreach($d_data->get() as $d){
                $arr[] = array('id_satuan' => $d->id_satuan,
                                'nama_satuan' => $d->nama_satuan,
                                'satuan' => $d->satuan);
            }
        }else{
            $arr = array();
        }

        return response()->json($arr);
    }

    function get_jml(Request $request){
    	if($_POST){
            $id = $request->get('id');
        }else{
            $id = $request->id;
        }

        $PDO = DB::connection('mysql')->getPdo();

        $billingStmt = $PDO->prepare("SELECT B.*, ms.nama_satuan, mkb.nama kategori, mkb2.nama sub_kategori
                                    FROM (
                                        SELECT A.*, sum(masuk - keluar) as stok
                                        FROM (
                                          SELECT * FROM view_penerimaan
                                         UNION
                                         SELECT * FROM view_transfer 
                                         UNION
                                         SELECT * FROM view_keluar
                                         UNION
                                         SELECT * FROM view_masuk
                                         UNION
                                         SELECT * FROM view_penjualan
                                         UNION
                                         SELECT * FROM view_opname
                                        ) A 
                                        GROUP BY A.id_barang
                                    ) B
                                    JOIN ms_barang mb ON B.id_barang = mb.id
                                    JOIN ms_satuan ms ON mb.id_satuan = ms.id_satuan
                                    JOIN ms_kategori_barang mkb ON mb.id_kb = mkb.id_kb
                                    JOIN ms_kategori_barang mkb2 ON mkb.induk_kb = mkb2.id_kb
                                    WHERE B.id_barang = '$id'");
        $billingStmt->execute();
        $usersBills = $billingStmt->fetchAll((\PDO::FETCH_ASSOC));

        return response()->json($usersBills);
    }

    function get_konversi(Request $request){
        $id = request()->get('id');

        $d_data = DB::table('ms_konversi AS mk')->join('ms_satuan AS ms', 'mk.satuan_awal', 'ms.id_satuan')->join('ms_satuan AS ms2', 'mk.satuan_akhir', 'ms2.id_satuan')->select(DB::raw('mk.* , ms.nama_satuan ns_awal, ms.satuan s_awal, ms2.nama_satuan ns_akhir, ms2.satuan s_akhir'))->where('kode', '=', $id);
        if($d_data->count() > 0){
            foreach($d_data->get() as $d){
                $arr[] = array('id_konversi' => $d->id_konversi,
                            'satuan_awal' => $d->ns_awal,
                            'satuan_akhir' => $d->ns_akhir,
                            'nilai_awal' => $d->nilai_awal,
                            'nilai_akhir' => $d->nilai_akhir);
            }
        }else{
            $d_data = DB::table('ms_barang AS mb')->join('ms_satuan AS ms', 'mb.id_satuan', 'ms.id_satuan')->where('mb.id', $id)->select(DB::raw('mb.*, ms.nama_satuan AS satuan'));
            if($d_data->count() > 0){
                $arr = array('satuan_awal' => $d_data->first()->satuan);
            }else{
                $arr = array('satuan_awal' => '');
            }
        }

        return response()->json($arr);
    }

    public function edit($id){
    	$d_data = DB::table('ms_warnakomposisi')->where('id_komposisi',$id)->first();
    	$data['satuan'] = DB::table('ms_satuan')->get();
    	$data['data'] = $this->data($d_data);
    	return view('master.KomposisiAdd')->with('data',$data);
    }

    function data($data = array()){
    	if(count($data) > 0){
    		$store['id_komposisi'] = $data->id_komposisi;
    		$store['nama_warna'] = $data->nama;
    		$store['inisial'] = $data->inisial;
    		$store['jumlah_warna'] = $data->jumlah;
    		$store['satuan_warna'] = $data->satuan;
    	}else{
    		$store['id_komposisi'] = '';
    		$store['nama_warna'] = '';
    		$store['inisial'] = '';
    		$store['jumlah_warna'] = '';
    		$store['satuan_warna'] = '';
    	}

    	return $store;

    }

    function get_edit(Request $request){
    	$id = request()->get('id');
    	$d_data = DB::table('ms_warnakomposisi_barang as mwb')->join('ms_barang as mb','mwb.id_barang','mb.id')->select('mwb.*','mb.kode_barang','mb.nama_barang')->where('mwb.id_komposisi',$id);
    	if($d_data->count() > 0){
    		foreach($d_data->get() as $d){
    			$arr[] = ['id' => $d->id_komposisi_barang,
    					  'id_komposisi' => $d->id_komposisi,
    					  'id_barang' => $d->id_barang,
    					  'kode_barang' => $d->kode_barang,
    					  'nama_barang' => $d->nama_barang,
    					  'jumlah' => $d->jumlah,
                          'jumlah_konv' => $d->jumlah_konv];
    		}
    	}else{
    		$arr = array();
    	}
    	return response()->json($arr);
    }

    function simpan(Request $request){
    	$id_komposisi = $request->get('id_komposisi');
    	$data['nama'] = $request->get('nama_warna');
    	$data['inisial'] = $request->get('inisial_warna');
    	$data['jumlah'] = $request->get('jumlah_warna');
    	$data['satuan'] = $request->get('satuan_warna');

    	$tabel_id = $request->get('tabel_id');
    	$tabel_idbarang = $request->get('tabel_idbarang');
    	$tabel_jumlah = $request->get('tabel_jumlah');
        $tabel_jumlah_konv = $request->get('tabel_jumlah_konv');


    	if($id_komposisi == ''){
    		$id = DB::table('ms_warnakomposisi')->insertGetId($data);

    		for($i=0; $i < count($tabel_id); $i++){
    			$barang['id_komposisi'] = $id;
    			$barang['id_barang'] = $tabel_idbarang[$i];
    			$barang['jumlah'] = $tabel_jumlah[$i];
                $barang['jumlah_konv'] = $tabel_jumlah_konv[$i];
                $barang['jum_satuan'] = pembagi($tabel_jumlah[$i], $data['jumlah']);
                $barang['jum_konv'] = pembagi($tabel_jumlah_konv[$i], $data['jumlah']);
    			DB::table('ms_warnakomposisi_barang')->insert($barang);
    		}

    	}else{
    		DB::table('ms_warnakomposisi')->where(array('id_komposisi'=>$id_komposisi))->update($data);
    		$id_del = array();
            $id_store = array();
    		$d_barang = DB::table('ms_warnakomposisi_barang')->where('id_komposisi',$id_komposisi);
    		
    		foreach($d_barang->get() as $d){
    			$id_store[] = $d->id_komposisi_barang;
    		}

    		foreach($id_store as $d){
                if(count($tabel_id) > 0){
                	if(!in_array($d, $tabel_id)){
	                    $id_del[] = $d;
	                }
                }else{
                	$id_del[] = $d;
                }
            }

            for($i = 0; $i < count($tabel_id); $i++){
            	$barang['id_komposisi'] = $id_komposisi;
            	$barang['id_barang'] = $tabel_idbarang[$i];
            	$barang['jumlah'] = $tabel_jumlah[$i];
                $barang['jumlah_konv'] = $tabel_jumlah_konv[$i];
                $barang['jum_satuan'] = pembagi($tabel_jumlah[$i], $data['jumlah']);
                $barang['jum_konv'] = pembagi($tabel_jumlah_konv[$i], $data['jumlah']);
            	if($tabel_id[$i] == ''){
                    DB::table('ms_warnakomposisi_barang')->insert($barang);
                }else if($tabel_id != ''){
                    $where = 
                    DB::table('ms_warnakomposisi_barang')->where(array('id_komposisi_barang' => $tabel_id[$i]))->update($barang);
                }
            }

            if(count($id_del) > 0){
                DB::table('ms_warnakomposisi_barang')->whereIn('id_komposisi_barang', $id_del)->delete();
            }

    	}

    	return redirect('komposisi');
    }

    function hapus(Request $request){
        $id = $request->get('id');

        DB::table('ms_warnakomposisi')->where(array('id_komposisi' => $id))->delete();
        DB::table('ms_warnakomposisi_barang')->where(array('id_komposisi' => $id))->delete();
    }
}
