<?php

namespace App\Http\Controllers\master;

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

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

	function index(){
		return view('master.LokasiProduksiList');
	}

	function get_lokasi(){
		$d_data = DB::table('ms_lokasi_produksi')->orderby('nama_lokasi', 'asc');


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

	function simpan(Request $request){

		$id_lokasi = $request->get('id_lokasi');
		$data['nama_lokasi'] = $request->get('popup_nama');
		$data['alamat'] = $request->get('popup_alamat');
		$data['keterangan'] = $request->get('popup_keterangan');

		if($id_lokasi == ''){
			DB::table('ms_lokasi_produksi')->insert($data);
		}else{
			DB::table('ms_lokasi_produksi')->where(array('id_lokasi' => $id_lokasi))->update($data);
		}

		return response()->json(array('status' => '1'));
	}

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

		$d_data = DB::table('ms_lokasi_produksi')->where('id_lokasi', $id);

		return response()->json($d_data->first());
	}

	function hapus(Request $request){
		$data['id_lokasi'] = $request->get('id');

		DB::table('ms_lokasi_produksi')->where($data)->delete();
	}
}