<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use App\Company;
use Illuminate\Support\Facades\Validator;
use DataTables;


class CompanyController extends Controller
{
    public function __construct()
    {
        // $this->middleware('auth');
        $this->middleware('administrator');
        $this->pageTitle = 'Company';
        $this->masterActive = 'active';
        $this->companyActive = 'active';
    }
    public function index()
    {
        $data = (array)$this;
        $data['form'] = [
            [ 'name' => 'name', 'label' => 'Nama', 'type' => 'text'],
            [ 'name' => 'description', 'label' => 'Deskripsi', 'type' => 'text'],
            // ['name' => 'ket', 'label' => 'Keterangan', 'type'=>'select', 'value' => ['sa', 'tu', 'dua']]  
        ];
        $data['form_action'] = "company.store";
        $data['form_update'] = "company.update";
        // return json_encode($data);
        return View::make('dashboard.company.index', $data);
    }
    public function indexData(Request $request){
        $data = Company::all();
         return Datatables::of($data)
               ->editColumn('action', function($data){ return view('dashboard.company.index-action', compact('data'));})
               ->rawColumns(['action'])
               ->make(true); 

   }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'description' => 'required',
        ]);

        if ($validator->fails()) {
            session()->put('error','Input gagal.');
            return back();
        }
        $researche = Company::create([
            'name' => $request->name,
            'description' => $request->description

            ]);

        session()->put('success','Berhasil Input.');   
        return redirect('/company');
        
        // return json_encode($request->all());
    }

    public function destroy($id)
    {
        $data = Company::find($id);
        if($data->count() < 1){
        session()->put('error','Gagal hapus.');
            return redirect('/company');
        };
        $data->delete();
        session()->put('success','Berhasil Hapus.');
            return redirect('/company');
    }
    public function look(Request $request)
    {
       
        $data = Company::findOrFail($request->data);
        return json_encode($data);

    }
    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
        ]);
        if ($validator->fails()) {
            session()->put('error','Input gagal.');
            return back();
        }
        $data = Company::find($request->id);
        $data->name = $request->name;
        $data->description = $request->description;
        $data->save();
        session()->put('success','Berhasi edit!');
        return redirect('/company');  
    }

}