<?php

namespace App\Http\Controllers\inventori;

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

class TransfergudangController 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); 
        });

        $this->session = array('id_gudang'=>Session::get('id_gudang'), 'id_lokasi'=>Session::get('id_lokasi'), 'kode_user' => Session::get('kode_user'), 'kode_group' => Session::get('kode_group'));
    }

    public function index(){

        $gudang = DB::table('ms_gudang as g')->select('id_gudang as id', 'nama_gudang')->get();
       
    	return view('inventori.TransfergudangList')->with(compact('gudang'));
    }

    public function rekapLaporan(Request $request)
    {
        $data['header'] = (object) array(
                            "tanggal_awal" => $request->tanggal_awal,
                            "tanggal_akhir" => $request->tanggal_akhir,
                            "gudang_asal" => (!is_null($this->get_gudang($request->gudang_asal))) ? $this->get_gudang($request->gudang_asal)->nama_gudang : '',
                            "gudang_tujuan" => (!is_null($this->get_gudang($request->gudang_tujuan))) ? $this->get_gudang($request->gudang_tujuan)->nama_gudang : '',
                            "text_status" => ($request->status == 1) ? "Dikeluarkan Gudang Asal":"Diterima Gudang Tujuan",
                            "status" => $request->status,
                            "text_tanggal" => ($request->filter_tanggal == 1) ? "Tanggal Keluar":"Tanggal Masuk",
                        );
        $var_tgl = "";
        if(!is_null($request->filter_tanggal)){
            if($request->filter_tanggal == 1){
                $var_tgl = "itg.tanggal_keluar";
            }else{
                $var_tgl = "itg.tanggal_masuk";
            }
        }
        $data_transfer_benang = DB::table('view_edit_transferbarang as vet')
                        ->join('inv_transfergudang as itg', 'vet.kode_transfergudang', 'itg.id_transfergudang')
                        ->leftJoin('ms_warnakomposisi as mw', 'vet.id_komposisi', 'mw.id_komposisi')
                        ->leftjoin("ms_barang as mb", "vet.id_barang", "mb.id")
                        ->leftjoin("ms_kategori_barang as mkb", "mb.id_kb", "mkb.id_kb")
                        ->whereBetween(DB::raw("DATE_FORMAT(".$var_tgl.", '%Y-%m-%d')"), [date_db($request->tanggal_awal, false, 2), date_db($request->tanggal_akhir, false, 2)])
                        ->where('itg.status', $request->status)
                        ->where('itg.gudang_awal', $request->gudang_asal)
                        ->where('itg.gudang_tujuan', $request->gudang_tujuan)
                        ->whereIn('vet.id_proses', ['', 18, 80, 81, 82, 84, 85])
                        ->groupBy(DB::raw("vet.id_barang, vet.id_proses, vet.id_satuan, mkb.id_kb, vet.id_komposisi"))
                        ->select(DB::raw("vet.kode_barang,
                                        vet.nama_barang,
                                        SUM(vet.jumlah) as jumlah,
                                        vet.nama_gudang,
                                        vet.nama_satuan,
                                        vet.id_proses,
                                        vet.nama_proses,
                                        vet.id_motif,
                                        vet.nama_motif,
                                        vet.id_corak,
                                        vet.nama_corak,
                                        vet.no_workorder_barang,
                                        vet.keterangan,
                                        CASE WHEN mw.id_komposisi IS NULL THEN '' ELSE mw.inisial END as inisial_komposisi, 
                                        mkb.nama as kategori"));

        $data_transfer_corak = DB::table('view_edit_transferbarang as vet')
                        ->join('inv_transfergudang as itg', 'vet.kode_transfergudang', 'itg.id_transfergudang')
                        ->leftJoin('ms_warnakomposisi as mw', 'vet.id_komposisi', 'mw.id_komposisi')
                        ->leftjoin("ms_barang as mb", "vet.id_barang", "mb.id")
                        ->leftjoin("ms_kategori_barang as mkb", "mb.id_kb", "mkb.id_kb")
                        ->whereBetween(DB::raw("DATE_FORMAT(".$var_tgl.", '%Y-%m-%d')"), [date_db($request->tanggal_awal, false, 2), date_db($request->tanggal_akhir, false, 2)])
                        ->where('itg.status', $request->status)
                        ->where('itg.gudang_awal', $request->gudang_asal)
                        ->where('itg.gudang_tujuan', $request->gudang_tujuan)
                        ->whereIn('vet.id_proses', [22, 25, 26, 27, 28, 29, 30, 31, 32, 33])
                        ->groupBy(DB::raw("vet.id_corak, vet.id_proses, vet.id_satuan, mkb.id_kb, vet.id_komposisi"))
                        ->select(DB::raw("vet.kode_barang,
                                        vet.nama_barang,
                                        SUM(vet.jumlah) as jumlah,
                                        vet.nama_gudang,
                                        vet.nama_satuan,
                                        vet.id_proses,
                                        vet.nama_proses,
                                        vet.id_motif,
                                        vet.nama_motif,
                                        vet.id_corak,
                                        vet.nama_corak,
                                        vet.no_workorder_barang,
                                        vet.keterangan,
                                        CASE WHEN mw.id_komposisi IS NULL THEN '' ELSE mw.inisial END as inisial_komposisi, 
                                        mkb.nama as kategori"));
        
        $data_transfer_motif = DB::table('view_edit_transferbarang as vet')
                        ->join('inv_transfergudang as itg', 'vet.kode_transfergudang', 'itg.id_transfergudang')
                        ->leftJoin('ms_warnakomposisi as mw', 'vet.id_komposisi', 'mw.id_komposisi')
                        ->leftjoin("ms_barang as mb", "vet.id_barang", "mb.id")
                        ->leftjoin("ms_kategori_barang as mkb", "mb.id_kb", "mkb.id_kb")
                        ->whereBetween(DB::raw("DATE_FORMAT(".$var_tgl.", '%Y-%m-%d')"), [date_db($request->tanggal_awal, false, 2), date_db($request->tanggal_akhir, false, 2)])
                        ->where('itg.status', $request->status)
                        ->where('itg.gudang_awal', $request->gudang_asal)
                        ->where('itg.gudang_tujuan', $request->gudang_tujuan)
                        ->where('vet.id_proses', 24)
                        ->groupBy(DB::raw("vet.id_motif, vet.id_proses, vet.id_satuan, mkb.id_kb, vet.id_komposisi"))
                        ->select(DB::raw("vet.kode_barang,
                                        vet.nama_barang,
                                        SUM(vet.jumlah) as jumlah,
                                        vet.nama_gudang,
                                        vet.nama_satuan,
                                        vet.id_proses,
                                        vet.nama_proses,
                                        vet.id_motif,
                                        vet.nama_motif,
                                        vet.id_corak,
                                        vet.nama_corak,
                                        vet.no_workorder_barang,
                                        vet.keterangan,
                                        CASE WHEN mw.id_komposisi IS NULL THEN '' ELSE mw.inisial END as inisial_komposisi, 
                                        mkb.nama as kategori"));

        $data['data'] = DB::table('view_edit_transferbarang as vet')
                        ->join('inv_transfergudang as itg', 'vet.kode_transfergudang', 'itg.id_transfergudang')
                        ->leftJoin('ms_warnakomposisi as mw', 'vet.id_komposisi', 'mw.id_komposisi')
                        ->leftjoin("ms_barang as mb", "vet.id_barang", "mb.id")
                        ->leftjoin("ms_kategori_barang as mkb", "mb.id_kb", "mkb.id_kb")
                        ->whereBetween(DB::raw("DATE_FORMAT(".$var_tgl.", '%Y-%m-%d')"), [date_db($request->tanggal_awal, false, 2), date_db($request->tanggal_akhir, false, 2)])
                        ->where('itg.status', $request->status)
                        ->where('itg.gudang_awal', $request->gudang_asal)
                        ->where('itg.gudang_tujuan', $request->gudang_tujuan)
                        ->whereNotIn('vet.id_proses', ['',18, 80, 81, 82, 84, 85, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33])
                        ->groupBy(DB::raw("vet.id_motif, vet.id_proses, vet.id_satuan, mkb.id_kb, vet.id_komposisi"))
                        ->select(DB::raw("vet.kode_barang,
                                        vet.nama_barang,
                                        SUM(vet.jumlah) as jumlah,
                                        vet.nama_gudang,
                                        vet.nama_satuan,
                                        vet.id_proses,
                                        vet.nama_proses,
                                        vet.id_motif,
                                        vet.nama_motif,
                                        vet.id_corak,
                                        vet.nama_corak,
                                        vet.no_workorder_barang,
                                        vet.keterangan,
                                        CASE WHEN mw.id_komposisi IS NULL THEN '' ELSE mw.inisial END as inisial_komposisi, 
                                        mkb.nama as kategori"))
                        ->union($data_transfer_benang)
                        ->union($data_transfer_corak)
                        ->union($data_transfer_motif)
                        ->get();
        
        require('fpdf181/Mc_table.php');

        $html = view('inventori.cetak.RekapTransferbarangCetak')->with('data', $data);

        return response($html)->header('Content-Type', 'application/pdf');
    }

    function get_data(){
        $id_gudang = $this->session['id_gudang'];
        $kode_user = $this->session['kode_user'];
        $id_group = $this->session['kode_group'];

        $arr = DB::table('inv_transfergudang as a')->join('ms_gudang as b','a.gudang_awal','b.id_gudang')->join('ms_gudang as c','a.gudang_tujuan','c.id_gudang')->select('a.*','b.nama_gudang as awal','c.nama_gudang as tujuan');

        if($id_group != '3' && $id_gudang != 0){
            $arr->whereIn('a.gudang_awal', explode("," , $id_gudang));   
        }
        $data = array();
        foreach($arr->get() as $a){

        //    $jum = $this->get_barangtransfer($a->id_transfergudang);

            $data[] = array('id_transfergudang' => $a->id_transfergudang,
                            'faktur' => $a->no_faktur.$a->faktur,
                            'awal' => $a->awal,
                            'tujuan' => $a->tujuan,
                            'tanggal' => tgl_full($a->tanggal, ''),
                            'tanggal_masuk' => ($a->tanggal_masuk == '0000-00-00 00:00:00') ? "":tgl_full($a->tanggal_masuk, ''),
                            'status' => status_transfer($a->status),
                            'status_id' => $a->status,
                            'rownum' => 0, // array_sum($jum),
                            'aksi' => $this->get_aksi($a->id_transfergudang, 0, 0)); //array_sum($jum), $a->status
        }
        $val = new Collection($data);
        return Datatables::of($val)->make(true);
    }

    public function formtambah(){
    	$data['gudang'] = DB::table('ms_gudang')->orderBy('id_gudang','asc');
        $id_gudang = $this->session['id_gudang'];
        if($id_gudang != 0){
            $data['gudang']->whereIn('id_gudang', explode(',', $id_gudang));
        }
        $data['gudang'] = $data['gudang']->get();
        $data['gudang_tujuan'] = DB::table('ms_gudang')->orderBy('id_gudang','asc')->get();
        $data['data'] = $this->data(array());
    	return view('inventori.TransfergudangAdd')->with('data',$data);
    }

    public function edit($id){
        $d_data = DB::table('inv_transfergudang')->where('id_transfergudang', '=', $id)->first();
        $data['gudang'] = DB::table('ms_gudang')->orderBy('id_gudang','asc');
        $id_gudang = $this->session['id_gudang'];
        if($id_gudang != 0){
            $data['gudang']->whereIn('id_gudang', explode(',', $id_gudang));
        }
        $data['gudang'] = $data['gudang']->get();
        $data['gudang_tujuan'] = DB::table('ms_gudang')->orderBy('id_gudang','asc')->get();
        $data['data'] = $this->data($d_data);
        return view('inventori.TransfergudangAdd')->with('data',$data);
    }

    function detail($id){
        $d_data = DB::table('inv_transfergudang as it')->join('ms_gudang as mg1', 'mg1.id_gudang', 'it.gudang_awal')->join('ms_gudang as mg2', 'mg2.id_gudang', 'it.gudang_tujuan')->where('id_transfergudang', '=', $id)->select(DB::raw('it.*, mg1.nama_gudang gudang_awal, mg2.nama_gudang gudang_tujuan'))->first();
        $data['gudang'] = DB::table('ms_gudang')->orderBy('id_gudang','asc')->get();
        $data['data'] = $d_data;
        return view('inventori.TransfergudangDetail')->with('data',$data);
    }

    function get_gudang($id=null){
        if (is_null($id)) {
            $d_data = DB::table('ms_gudang');
            if($d_data->count() > 0){
                $arr['data'] = $d_data->get();
                $arr['status'] = array('1');
            }else{
                $arr['status'] = array('0');
            }

            return response()->json($arr);
        } else {
            $d_data = DB::table('ms_gudang')->where('id_gudang', $id)->first();
            return $d_data;
        }
    }

    function get_jml(Request $request){
        $id = $request->get('id');
        $d_data = DB::table('pem_penerimaan as terima')
                ->join('pem_pembelian_barang as bb', 'terima.id_beli_barang', '=', 'bb.id_beli_barang')
                ->join('ms_barang as barang', 'bb.id_barang', '=', 'barang.id')
                ->join('ms_gudang as gudang', 'terima.id_gudang', '=', 'gudang.id_gudang')
                ->select(DB::raw('barang.id id_barang, barang.kode_barang, barang.nama_barang, gudang.id_gudang as id_gudang, gudang.nama_gudang as nama_gudang, SUM(terima.jml_barang_terima) jum_barang'))
                ->where('barang.id', '=', $id)
                ->groupBy('barang.kode_barang','barang.id', 'gudang.id_gudang');

        if($d_data->count() > 0){
            $arr['data'] = $d_data->first();
            $arr['status'] = array('1');
        }else{
            $arr['status'] = array('0');
        }

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


    function get_barang(Request $request){
            $id = $request->get('id');
            $id_barang = $request->get('id_barang');
            $id_proses = $request->get("id_proses");
            $id_komposisi= $request->get("id_komposisi");
            $id_corak = $request->get('id_corak');
            $spk = $request->get('spk');
            $workorder = $request->get('workorder'); 
            $id_kualitas = $request->get('id_kualitas');
            $id_dudul = $request->get('id_dudul');
            $id_motif = $request->get('id_motif');
            $id_label = $request->get('id_label');
            $id_kemasan = $request->get('id_kemasan');
            $id_kemasansatuan = $request->get('id_kemasansatuan');
            $id_kemasansepuluh = $request->get('id_kemasansepuluh');
            $id_kemasanseratus = $request->get('id_kemasanseratus');
            $id_cap = $request->get('id_cap');
            $id_kualitasproses = $request->get('id_kualitasproses');
            $id_kualitasperiksa = $request->get('id_kualitasperiksa');
            $id_rencana = $request->get('id_rencana');
            $jumlah_rencana = $request->get('jumlah_rencana');

            $where = "WHERE B.id_gudang = '$id'";
            if($id_barang != ''){
                $where .= " AND B.id_barang = '$id_barang'";
            }
            
            $warna = "";
            if($id_komposisi != ''){
                $warna .= " AND B.id_komposisi = '$id_komposisi'";
            }

            $corak = "";
            if($id_corak != '' || $id_corak != 0){
                $corak .= " AND B.id_corak ='$id_corak'";
            }

            $motif = "";
            if($id_motif != '' || $id_motif != 0){
                $motif .= " AND B.id_motif ='$id_motif'";
            }

            $kualitas = '';
            if($id_kualitas != '' || $id_kualitas !=0){
                $kualitas .= " AND B.id_kualitas = '$id_kualitas'";
            }

            $dudulan = '';
            if($id_dudul != ''||$id_dudul != 0){
                $dudulan .= " AND B.id_kualitas_dudul = '$id_dudul'";
            }
            
            $label = '';
            if($id_dudul != '' || $id_dudul != 0){
                $label .= " AND B.id_label = '$id_label'";
            }

            $kemasan = '';
            if($id_kemasan != '' || $id_kemasan != 0){
                $kemasan .= " AND B.id_kemasan = '$id_kemasan'";
            }

            $kemasan_satuan = '';
            if($id_kemasansatuan != '' || $id_kemasansatuan != 0){
                $kemasan_satuan .= " AND B.id_kemasansatuan = '$id_kemasansatuan'";
            }

            $kemasan_sepuluh = '';
            if($id_kemasansepuluh != '' || $id_kemasansepuluh != 0){
                $kemasan_sepuluh .= " AND B.id_kemasansepuluh = '$id_kemasansepuluh'";
            }

            $kemasan_seratus = '';
            if($id_kemasanseratus != '' || $id_kemasanseratus != 0){
                $kemasan_seratus .= " AND B.id_kemasanseratus = '$id_kemasanseratus'";
            }

            $proses = '';
            if($id_proses != '' || $id_proses != 0){
                $proses .= " AND B.id_proses = '$id_proses'";
            }

            $id_workorder = '';
            if($spk != '' || $spk != 0){
                $id_workorder .= " AND B.id_workorder = '$spk'";
            }

            $id_workorder_barang = '';
            if($workorder != '' || $workorder != 0){
                $id_workorder_barang .= " AND B.id_workorder_barang = '$workorder'";
            }

            $cap = '';
            if($id_cap != '' || $id_cap != 0){
                $cap .= " AND B.id_cap = '$id_cap'";
            }

            $periksa = '';
            if($id_kualitasperiksa != '' || $id_kualitasperiksa != 0){
                $periksa .= " AND B.id_kualitas_periksa = '$id_kualitasperiksa'";
            }

            $kual_proses = '';
            if($id_kualitasproses != '' || $id_kualitasproses != 0){
                $kual_proses .= " AND B.id_kualitas_proses = '$id_kualitasproses'";
            }

            $rencana = '';
            if($id_rencana != '' || $id_rencana != 0){
                $rencana .= " AND B.id_perubahansatuan = '$id_rencana'";
            }
            
            $jum_rencana = '';
            if($jumlah_rencana != '' || $jumlah_rencana != 0){
                $jum_rencana .= " AND B.jumlah_rencana = '$jumlah_rencana'";
            }

        $PDO = DB::connection('mysql')->getPdo();
        $all_where = " $where $proses $id_workorder $id_workorder_barang $warna $corak $id_workorder $id_workorder_barang $motif $kualitas $dudulan $label $kemasan $kemasan_satuan $kemasan_sepuluh $kemasan_seratus $cap $periksa $kual_proses $rencana $jum_rencana ";
        $billingStmt = $PDO->prepare("SELECT B.*, mkb.nama kategori, mkb2.nama sub_kategori, CASE WHEN mwk.id_komposisi IS NULL THEN '' ELSE mwk.inisial END AS inisial_komposisi
                                     FROM (
                                         ".base_stok($all_where)."
                                     ) B
                                     JOIN ms_barang mb ON B.id_barang = mb.id
                                     JOIN ms_kategori_barang mkb ON mb.id_kb = mkb.id_kb
                                     JOIN ms_kategori_barang mkb2 ON mkb.induk_kb = mkb2.id_kb
                                     LEFT JOIN ms_warnakomposisi as mwk ON mwk.id_komposisi = B.id_komposisi
                                     $all_where ");
    
        $billingStmt->execute();
        $usersBills = $billingStmt->fetchAll((\PDO::FETCH_ASSOC));

       return response()->json(barang_byproses($usersBills, 1));
    }

    function get_barangdetail(Request $request){
            $id = $request->get('id');
            $id_barang = $request->get('id_barang');
            $id_proses = $request->get("id_proses");
            $id_komposisi= $request->get("id_komposisi");
            $id_corak = $request->get('id_corak');
            $spk = $request->get('spk');
            $workorder = $request->get('workorder'); 
            $id_kualitas = $request->get('id_kualitas');
            $id_dudul = $request->get('id_dudul');
            $id_motif = $request->get('id_motif');
            $id_label = $request->get('id_label');
            $id_kemasan = $request->get('id_kemasan');
            $id_kemasansatuan = $request->get('id_kemasansatuan');
            $id_kemasansepuluh = $request->get('id_kemasansepuluh');
            $id_kemasanseratus = $request->get('id_kemasanseratus');
            $id_cap = $request->get('id_cap');
            $id_kualitasproses = $request->get('id_kualitasproses');
            $id_kualitasperiksa = $request->get('id_kualitasperiksa');
            $id_perubahansatuan = $request->get('id_rencana');
            $jumlah_rencana = $request->get('jumlah_rencana');
            $id_satuan = $request->get('id_satuan');

            $where = "WHERE B.id_gudang = '$id'";

            

            $where .= " AND B.id_barang = '$id_barang'";
            $where .= " AND B.id_komposisi = '$id_komposisi'";
            $where .= " AND B.id_corak ='$id_corak'";
            $where .= " AND B.id_motif ='$id_motif'";
            $where .= " AND B.id_kualitas = '$id_kualitas'";
            $where .= " AND B.id_kualitas_dudul = '$id_dudul'";
            $where .= " AND B.id_label = '$id_label'";
            $where .= " AND B.id_kemasan = '$id_kemasan'";
            $where .= " AND B.id_kemasansatuan = '$id_kemasansatuan'";
            $where .= " AND B.id_kemasansepuluh = '$id_kemasansepuluh'";
            $where .= " AND B.id_kemasanseratus = '$id_kemasanseratus'";
            $where .= " AND B.id_proses = '$id_proses'";
            $where .= " AND B.id_workorder = '$spk'";
            $where .= " AND B.id_workorder_barang = '$workorder'";
            $where .= " AND B.id_cap = '$id_cap'";
            $where .= " AND B.id_kualitas_periksa = '$id_kualitasperiksa'";
            $where .= " AND B.id_kualitas_proses = '$id_kualitasproses'";
            $where .= " AND B.id_perubahansatuan = '$id_perubahansatuan'";
            $where .= " AND B.jumlah_rencana = '$jumlah_rencana'";
            $where .= " AND B.id_satuan = '$id_satuan'";

        $PDO = DB::connection('mysql')->getPdo();
        
        $billingStmt = $PDO->prepare("SELECT B.*, mkb.nama kategori, mkb2.nama sub_kategori, CASE WHEN mwk.id_komposisi IS NULL THEN '' ELSE mwk.inisial END AS inisial_komposisi
                                     FROM (
                                         ".base_stok()."
                                     ) B
                                     JOIN ms_barang mb ON B.id_barang = mb.id
                                     JOIN ms_kategori_barang mkb ON mb.id_kb = mkb.id_kb
                                     JOIN ms_kategori_barang mkb2 ON mkb.induk_kb = mkb2.id_kb
                                     LEFT JOIN ms_warnakomposisi as mwk ON mwk.id_komposisi = B.id_komposisi
                                     $where");
    
        $billingStmt->execute();
        $usersBills = $billingStmt->fetchAll((\PDO::FETCH_ASSOC));

       return response()->json(barang_byproses($usersBills, 1));
    }


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




    function get_edit(Request $request){
        $id = request()->get('id');
        $d_data = DB::table('view_edit_transferbarang')->where('kode_transfergudang', '=', $id);
        if($d_data->count() > 0){
            foreach($d_data->get() as $d){
                
                $arr[] = array('id' => $d->id_transfergudang_detail,
                                'id_barang' => $d->id_barang,
                                'kode_barang' => $d->kode_barang,
                                'nama_barang' => $d->nama_barang,
                                'id_proses' => $d->id_proses,
                                'nama_proses' => $d->nama_proses,
                                'id_satuan' => $d->id_satuan,
                                'nama_satuan' => $d->nama_satuan,
                                'id_gudang' => $d->id_gudang,
                                'nama_gudang' => $d->nama_gudang,
                                'id_komposisi' => $d->id_komposisi,
                                'nama_komposisi' => $d->nama_komposisi,
                                'id_motif' => $d->id_motif,
                                'nama_motif' => $d->nama_motif,
                                'id_corak' => $d->id_corak,
                                'nama_corak' => $d->nama_corak,
                                'id_workorder' => $d->id_workorder,
                                'no_workorder' => $d->no_workorder,
                                'id_workorder_barang' => $d->id_workorder_barang,
                                'no_workorder_barang' => $d->no_workorder_barang,
                                'id_label' => $d->id_label,
                                'nama_label' => $d->nama_label,
                                'id_cap' => $d->id_cap,
                                'nama_cap' => $d->nama_cap,
                                'id_kemasan' => $d->id_kemasan,
                                'nama_kemasan' => $d->nama_kemasan,
                                'id_kemasansatuan' => $d->id_kemasansatuan,
                                'nama_kemasansatuan' => $d->nama_kemasansatuan,
                                'id_kemasansepuluh' => $d->id_kemasanseratus,
                                'nama_kemasansepuluh' => $d->nama_kemasansepuluh,
                                'id_kemasanseratus' => $d->id_kemasanseratus,
                                'nama_kemasanseratus' => $d->nama_kemasanseratus,
                                'spk' => $d->id_workorder,
                                'no_spk' => $d->no_workorder,
                                'workorder' => $d->id_workorder_barang,
                                'no_workorder' => $d->no_workorder_barang,
                                'id_kualitas' => $d->id_kualitas,
                                'nama_kualitas' => $d->nama_kualitas,
                                'id_dudul' => $d->id_kualitas_dudul,
                                'nama_dudul' => $d->kualitas_dudul,
                                'jumlah' => $d->jumlah,
                                'id_kualitas_proses' => $d->id_kualitas_proses,
                                'nama_kualitas_proses' => $d->nama_kualitas_proses,
                                'id_kualitas_periksa' => $d->id_kualitas_periksa,
                                'nama_kualitas_periksa' => $d->nama_kualitas_periksa,
                                'id_perubahansatuan' => $d->id_perubahansatuan,
                                'nama_perubahansatuan' => $d->nama_perubahansatuan,
                                'jumlah_rencana' => $d->jumlah_rencana,
                                'keterangan' => $d->keterangan);
            }
        }else{
            $arr = array();
        }

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

    
    public function simpan(Request $request){
        $id_gudang = $request->get('id_gudang');
        $data['tanggal'] = date('Y-m-d', strtotime($request->get('tanggal')));
        $data['gudang_awal'] = $request->get('gudang_awal');
        $data['gudang_tujuan'] = $request->get('gudang_tujuan');
        
        $data['is_cv'] = ($request->get('cv') == 'on') ? 1:0;
        $data['nomor_minta'] = $request->get('nomor_permintaan');
        $data['tanggal_minta'] = tgl_full($request->get('tgl_permintaan'), '2');
        $data['tanggal_full'] = tgl_full($request->get('tanggal'), '5');
        
        // $data['no_faktur'] = $request->get('nomor_faktur');
        // $data['faktur'] = $request->get('faktur');
        $data = $data+$this->validasi_nomor($id_gudang, $request->get('nomor_faktur'), $request->get('faktur'));

        // print_r($data);
        // print_r("\n");
        // print_r($request->get('nomor_faktur')." | ".$request->get('faktur'));

        $data['id_user'] = $this->session['kode_user'];

        $tabel_id = $request->get('tabel_id');
        $tabel_satuan = $request->get('tabel_idsatuan');
        $tabel_kode = $request->get('tabel_kode');
        $tabel_nama = $request->get('tabel_nama');
        $tabel_idgudang = $request->get('tabel_idgudang');
        $tabel_idproses = $request->get('tabel_idproses');
        $tabel_idkomposisi = $request->get('tabel_idwarna');
        $tabel_idcorak = $request->get('tabel_idcorak');
        $tabel_idmotif = $request->get('tabel_idmotif');
        $tabel_idlabel = $request->get('tabel_idlabel');
        $tabel_idkualitas = $request->get('tabel_idkualitas');
        $tabel_idkualitas_dudul = $request->get('tabel_idkualitas_dudul');
        $tabel_idkemasan = $request->get('tabel_idkemasan');
        $tabel_idkemasan_satuan = $request->get('tabel_idkemasan_satuan');
        $tabel_idkemasan_sepuluh = $request->get('tabel_idkemasan_sepuluh');
        $tabel_idkemasan_seratus = $request->get('tabel_idkemasan_seratus');
        $tabel_spk = $request->get('tabel_spk');
        $tabel_workorder = $request->get('tabel_workorder');
        $tabel_jumlah = $request->get('tabel_jumlah');
        $tabel_idcap = $request->get('tabel_idcap');
        $tabel_idkualitasproses = $request->get('tabel_idkualitas_proses');
        $tabel_idkualitasperiksa = $request->get('tabel_idkualitas_periksa');
        $tabel_idrencana = $request->get('tabel_idrencana');
        $tabel_jumlahrencana = $request->get('tabel_rencanajumlah');
        $tabel_keterangan = $request->get('tabel_keterangan');


        if($id_gudang == ''){
            $id = DB::table('inv_transfergudang')->insertGetId($data);
            
            for($i = 0; $i < count($tabel_id); $i++){
                $barang['kode_transfergudang'] = $id;
                $barang['kode_barang'] = $tabel_kode[$i];
                $barang['nama_barang'] = $tabel_nama[$i];
                $barang['id_satuan'] = $tabel_satuan[$i];
                $barang['id_gudang'] = $tabel_idgudang[$i];
                $barang['id_proses'] = $tabel_idproses[$i];
                $barang['id_komposisi'] = $tabel_idkomposisi[$i];
                $barang['id_motif'] = $tabel_idmotif[$i];
                $barang['id_motif_barang'] = $tabel_idcorak[$i];
                $barang['id_kualitas'] = $tabel_idkualitas[$i];
                $barang['id_kualitas_dudul'] = $tabel_idkualitas_dudul[$i];
                $barang['id_kemasan'] = $tabel_idkemasan[$i];
                $barang['id_label'] = $tabel_idlabel[$i];
                $barang['id_cap'] = $tabel_idcap[$i];
                $barang['id_kemasansatuan'] = $tabel_idkemasan_satuan[$i];
                $barang['id_kemasansepuluh'] = $tabel_idkemasan_sepuluh[$i];
                $barang['id_kemasanseratus'] = $tabel_idkemasan_seratus[$i];
                $barang['id_workorder'] = $tabel_spk[$i];
                $barang['id_workorder_barang'] = $tabel_workorder[$i];
                $barang['jumlah'] = $tabel_jumlah[$i];
                $barang['id_kualitas_proses'] = $tabel_idkualitasproses[$i];
                $barang['id_kualitas_periksa'] = $tabel_idkualitasperiksa[$i];
                $barang['id_perubahansatuan'] = $tabel_idrencana[$i];
                $barang['jumlah_rencana'] = $tabel_jumlahrencana[$i];
                $barang['keterangan'] = $tabel_keterangan[$i];

                DB::table('inv_transfergudang_barang')->insert($barang);
            }
        }else{
            DB::table('inv_transfergudang')->where(array('id_transfergudang' => $id_gudang))->update($data);
            $id_del = array();
            $id_store = array();
            $d_barang = DB::table('inv_transfergudang_barang')->where('kode_transfergudang', '=', $id_gudang);
            foreach($d_barang->get() as $d){
                $id_store[] = $d->id_transfergudang_detail;
            }

            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['kode_transfergudang'] = $id_gudang;
                $barang['kode_barang'] = $tabel_kode[$i];
                $barang['nama_barang'] = $tabel_nama[$i];
                $barang['id_satuan'] = $tabel_satuan[$i];
                $barang['id_gudang'] = $tabel_idgudang[$i];
                $barang['id_proses'] = $tabel_idproses[$i];
                $barang['id_komposisi'] = $tabel_idkomposisi[$i];
                $barang['id_motif'] = $tabel_idmotif[$i];
                $barang['id_motif_barang'] = $tabel_idcorak[$i];
                $barang['id_kualitas'] = $tabel_idkualitas[$i];
                $barang['id_kualitas_dudul'] = $tabel_idkualitas_dudul[$i];
                $barang['id_kemasan'] = $tabel_idkemasan[$i];
                $barang['id_label'] = $tabel_idlabel[$i];
                $barang['id_cap'] = $tabel_idcap[$i];
                $barang['id_kemasansatuan'] = $tabel_idkemasan_satuan[$i];
                $barang['id_kemasansepuluh'] = $tabel_idkemasan_sepuluh[$i];
                $barang['id_kemasanseratus'] = $tabel_idkemasan_seratus[$i];
                $barang['id_workorder'] = $tabel_spk[$i];
                $barang['id_workorder_barang'] = $tabel_workorder[$i];
                $barang['jumlah'] = $tabel_jumlah[$i];
                $barang['id_kualitas_proses'] = $tabel_idkualitasproses[$i];
                $barang['id_kualitas_periksa'] = $tabel_idkualitasperiksa[$i];
                $barang['id_perubahansatuan'] = $tabel_idrencana[$i];
                $barang['jumlah_rencana'] = $tabel_jumlahrencana[$i];
                $barang['keterangan'] = $tabel_keterangan[$i];

                if($tabel_id[$i] == ''){
                    DB::table('inv_transfergudang_barang')->insert($barang);
                }else if($tabel_id != ''){
                    $where = 
                    DB::table('inv_transfergudang_barang')->where(array('id_transfergudang_detail' => $tabel_id[$i]))->update($barang);
                }
            }

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

        return redirect('transfergudang');

    }

    function data($data = array()){
        if(count($data) > 0){
            $store['id_gudang'] = $data->id_transfergudang;
            $store['tanggal'] = date('d-m-Y', strtotime($data->tanggal));
            $store['gudang_awal'] = $data->gudang_awal;
            $store['gudang_tujuan'] = $data->gudang_tujuan;
            $store['status'] = $data->status;
            $store['is_cv'] = $data->is_cv;
            $store['nomor_minta'] = $data->nomor_minta;
            $store['tanggal_minta'] = tgl_full($data->tanggal_minta, '');
            $store['no_faktur'] = $data->no_faktur;
            $store['faktur'] = $data->faktur;
        }else{
            $store['id_gudang'] = '';
            $store['tanggal'] = '';
            $store['gudang_awal'] = '';
            $store['gudang_tujuan'] = '';
            $store['status'] = '0';
            $store['is_cv'] = '';
            $store['nomor_minta'] = '';
            $store['tanggal_minta'] = '';
            $store['no_faktur'] = '';
            $store['faktur'] = '';
        }

        return $store;
    }

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

        DB::table('inv_transfergudang')->where(array('id_transfergudang' => $id))->delete();
        DB::table('inv_transfergudang_barang')->where(array('kode_transfergudang' => $id))->delete();
    }

    public function cetak(Request $request, $id){
        $req = $request->all();

        $data['data'] = DB::table('inv_transfergudang as it')->join('ms_gudang as mg','it.gudang_awal','mg.id_gudang')->join('ms_gudang as mg2','it.gudang_tujuan','mg2.id_gudang')->select('it.*','mg.nama_gudang as nama_gudang_awal','mg2.nama_gudang as nama_gudang_tujuan')->where('id_transfergudang', '=', $id)->first();
        $data['detail'] = DB::table('view_edit_transferbarang as v')->leftjoin("ms_warnakomposisi as mw", "v.id_komposisi", "mw.id_komposisi")->leftjoin("ms_barang AS mb", "v.id_barang", "mb.id")->leftjoin("ms_kategori_barang AS mkb", "mb.id_kb", "mkb.id_kb")->select(DB::raw("v.*, CASE WHEN mw.id_komposisi IS NULL THEN '' ELSE mw.inisial END AS inisial_komposisi, mkb.nama kategori"))->where('kode_transfergudang', '=', $id)->orderByRaw("v.id_transfergudang_detail")->get();
        
        require('fpdf181/Mc_table.php');

        if(isset($req['kertas'])){
            if($req['kertas'] == 0){
                $html = view('inventori.cetak.TransferbarangCetakKecil')->with('data', $data);
            }else{
                $html = view('inventori.cetak.TransferbarangCetak')->with('data', $data);
            }
        }else{
            $html = view('inventori.cetak.TransferbarangCetak')->with('data', $data);
        }

        return response($html)->header('Content-Type', 'application/pdf');

    }


    function get_barangtransfer($id){
        $d_data = DB::table('view_edit_transferbarang')->where('kode_transfergudang', $id)->where('status', '=', '2');

        if($d_data->count() > 0){
            foreach($d_data->get() as $d){

                $jumlah = $d->jumlah;

                $where = "WHERE B.id_gudang = '$d->id_gudangtujuan' AND B.id_barang = '$d->id_barang' AND B.id_komposisi = '$d->id_komposisi' AND B.id_corak ='$d->id_corak' AND B.id_motif ='$d->id_motif' AND B.id_kualitas = '$d->id_kualitas' AND B.id_kualitas_dudul = '$d->id_kualitas_dudul' AND B.id_label = '$d->id_label' AND B.id_kemasan = '$d->id_kemasan' AND B.id_kemasansatuan = '$d->id_kemasansatuan' AND B.id_kemasansepuluh = '$d->id_kemasansepuluh' AND B.id_kemasanseratus = '$d->id_kemasanseratus' AND B.id_proses = '$d->id_proses' AND B.id_workorder = '$d->id_workorder' AND B.id_workorder_barang = '$d->id_workorder_barang' AND B.id_cap = '$d->id_cap' AND B.id_kualitas_periksa = '$d->id_kualitas_periksa' AND B.id_kualitas_proses = '$d->id_kualitas_proses' AND B.id_perubahansatuan = '$d->id_perubahansatuan' AND B.jumlah_rencana = '$d->jumlah_rencana'";

                $PDO = DB::connection('mysql')->getPdo();
                $billingStmt = $PDO->prepare("SELECT B.*
                                             FROM (
                                                 ".base_stok()."
                                             ) B
                                             $where ");
            
                $billingStmt->execute();
                $usersBills = $billingStmt->fetchAll((\PDO::FETCH_ASSOC));

                if($usersBills[0]['stok'] < $jumlah){
                    $jum[] = 1;
                }else{
                    $jum[] = 0;
                }
            }
        }else{
            $jum[] = 1;
        }

        return $jum;
   // return $where;
    }


    // FUngsi Lainnya

    function get_aksi($id, $status, $status_gudang){
        if($status_gudang == 0){
            $ret = '<div class="btn-group"><a class="btn bg-info-400" type="button" href="'.url('transfergudang/detail').'/'.$id.'"><i class="icon-notification2"></i></a> <a class="btn bg-warning-400" type="button" href="'.url('transfergudang/edit').'/'.$id.'"><i class="icon-pencil"></i> </a> <button class="btn bg-danger-800" type="button" onclick="hapus('.$id.')"><i class="icon-eraser"></i></button> 
                <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown"><i class="icon-printer"></i><span class="caret"></span></button> <ul class="dropdown-menu dropdown-menu-right"> <li><a href="'.url('transfergudang/cetak/'.$id).'?kertas=1'.'" target="_blank"><i class="icon-printer4"></i> Cetak Sedang</a></li> <li><a href="'.url('transfergudang/cetak/'.$id).'?kertas=0'.'" target="_blank"><i class="icon-printer4"></i> Cetak Kecil</a></li> </ul></div>';
        }else{
            // if($status > 0){
            // $ret = '<div class="btn-group"><a class="btn bg-info-400" type="button" href="'.url('transfergudang/detail').'/'.$id.'"><i class="icon-notification2"></i></a> <a class="btn bg-success-400" type="button" target="_blank" href="'.url('transfergudang/cetak').'/'.$id.'"><i class="icon-printer"></i> </a></div>';
            // }else if($status == 0){
            //     $ret = '<div class="btn-group"><a class="btn bg-info-400" type="button" href="'.url('transfergudang/detail').'/'.$id.'"><i class="icon-notification2"></i></a> <a class="btn bg-warning-400" type="button" href="'.url('transfergudang/edit').'/'.$id.'"><i class="icon-pencil"></i> </a> <button class="btn bg-danger-800" type="button" onclick="hapus('.$id.')"><i class="icon-eraser"></i></button> <a class="btn bg-success-400" type="button" target="_blank" href="'.url('transfergudang/cetak').'/'.$id.'"><i class="icon-printer"></i> </a></div>';
            // }else{
            //    $ret = '<a class="btn bg-info-400" type="button" href="'.url('transfergudang/detail').'/'.$id.'"><i class="icon-notification2"></i> </a>'; 
            // }

            $ret = '<div class="btn-group"><a class="btn bg-info-400" type="button" href="'.url('transfergudang/detail').'/'.$id.'"><i class="icon-notification2"></i></a> <a class="btn bg-warning-400" type="button" href="'.url('transfergudang/edit').'/'.$id.'"><i class="icon-pencil"></i></a> <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown"><i class="icon-printer"></i><span class="caret"></span></button> <ul class="dropdown-menu dropdown-menu-right"> <li><a href="'.url('transfergudang/cetak/'.$id).'?kertas=1'.'" target="_blank"><i class="icon-printer4"></i> Cetak Sedang</a></li> <li><a href="'.url('transfergudang/cetak/'.$id).'?kertas=0'.'" target="_blank"><i class="icon-printer4"></i> Cetak Kecil</a></li> </ul></div>'; //<a class="btn bg-success-400" type="button" target="_blank" href="'.url('transfergudang/cetak').'/'.$id.'"><i class="icon-printer"></i> </a> 
        }

        return $ret;
    }

    function get_faktur(Request $request){
        $data = $request->all();
        $arr = array();
        if($data['id'] != ''){
            $d_data = Transfergudang::where('id_transfergudang', $id)->first();
            $arr = array('no_faktur' => sprintf('%03d', $d_data->no_faktur),
                        'faktur' => $d_data->faktur);
        }else{
            $tgl = explode('-', $data['tgl']);
            $d_data = Transfergudang::whereRaw("YEAR(tanggal) = $tgl[2] AND MONTH(tanggal) = $tgl[1]")->max('no_faktur');

            $arr = array('no_faktur' => sprintf('%03d', $d_data+1),
                        'faktur' => '/'.$tgl[1].'/'.$tgl[2]);
        }

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

    function validasi_nomor($id, $noAuto, $noAuto_ext){
        $arr = array();

        if($noAuto != '' && $noAuto_ext != ''){
            
            if($id > 0){
                $d_data = DB::table('inv_transfergudang')->where('id_transfergudang', $id);
                if($d_data->count() > 0){
                    if($d_data->first()->no_faktur == $noAuto && $d_data->first()->faktur == $noAuto_ext){
                        $arr = array('no_faktur' => $noAuto,
                            'faktur' => $noAuto_ext); 
                    }else{
                        DB::table('inv_transfergudang')->where('id_transfergudang', $id)->update(['no_faktur' => '', 'faktur' => '']);
                        return $this->validasi_nomor(0, $noAuto, $noAuto_ext);
                    }
                }else{
                    $arr = array('no_faktur' => $noAuto,
                            'faktur' => $noAuto_ext); 
                }

            }else{
                $no = 1;
                // $d_kemasan = DB::table("pro_barangmasuk_kemasan")->select(DB::raw("noAuto, noAuto_ext"));
                // $d_data = DB::table('pro_barangmasuk')->unionAll($d_kemasan)->select(DB::raw("noAuto, noAuto_ext"));
                

                // $test = DB::table(DB::raw("({$d_data->toSql()}) as u"))->where(['u.noAuto' => $noAuto, 'u.noAuto_ext' => $noAuto_ext]);

                $d_data = DB::table('inv_transfergudang')->where(['no_faktur' => $noAuto,'faktur' => $noAuto_ext]);

                if($d_data->count() > 0){
                    $nomor = DB::table('inv_transfergudang')->select(DB::raw("no_faktur, faktur"))->get()->max('no_faktur');


                    if($nomor == 0 || $nomor == ''){
                        $no = 1;
                    }else{
                        $no = sprintf('%03d', $nomor + 1);
                    }

                    $arr = array('no_faktur' => $no,
                                    'faktur' => $noAuto_ext);                
                }else{
                    $arr = array('no_faktur' => $noAuto,
                                'faktur' => $noAuto_ext);

                }

            }
        }

        return $arr;
    }
    
}
