<?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 MesinController 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(){
		$data['lokasi'] = DB::table('ms_lokasi_produksi')->orderby('nama_lokasi', 'asc')->get();
		return view('master.MesinList')->with('data', $data);
	}

	function get_mesin(){
		DB::statement(DB::raw('set @rownum=0'));
		$d_data = DB::table('ms_mesin as mm')->join('ms_lokasi_produksi as ml', 'mm.id_lokasi', 'ml.id_lokasi')->select(DB::raw('mm.*, ml.nama_lokasi, @rownum  := @rownum  + 1 AS rownum'))->orderby('mm.nama','ASC');


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

	function simpan(Request $request){

		$id_mesin = $request->get('id_mesin');
		$data['nama'] = $request->get('popup_nama_mesin');
		$data['id_lokasi'] = $request->get('popup_lokasi');

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

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

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

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