<?php

namespace App\Http\Controllers\HR;

use App\HrCompanyModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Yajra\DataTables\DataTables;
use App\User;
use App\Fun\Fun;
use Auth;


class HrCompanyController extends Controller
{
    public function index()
    {
        return view('hr.company-structure.index');
    }

    public function get_company_structure()
    {
        $data = HrCompanyModel::get();
        return DataTables::of($data)
            ->addIndexColumn()
            ->addColumn('action', function ($data) {
                $check_language = Fun::lang();

                if ($check_language == 'km') {
                    $edit = "កែសម្រួល";
                } else {
                    $edit = "Edit";
                }
                $del = '';
                return '<a href="'.route('hr-company-structure.edit',encrypt($data->id)).'" class="button_warning">'.$edit.'</a>';
            })
            ->addColumn('parent_id', function ($data) {
                @$p = HrCompanyModel::find($data->parent_id);
                return @$p->name;
            })
            ->rawColumns(['action' => 'action', 'complete_status' => 'complete_status'])
            ->make(true);
    }

    public function create()
    {
        $parent = HrCompanyModel::pluck('name', 'id');
        return view('hr.company-structure.create',compact('parent'));
    }

    public function store(Request $request)
    {
        $this->validate($request,[
            'name'=>'required',
            'type'=>'required',
        ]);
        $com = new HrCompanyModel();
        $com->name = $request->name;
        $com->type = $request->type;
        $com->parent_id = $request->parent;
        $com->address = $request->address;
        $com->note = $request->note;
        $com->save();
        return redirect()->route('hr-company-structure.index')->with('success','Structure was added successful...');
    }

    public function show($id)
    {
        //
    }

    public function edit($id)
    {
        $company = HrCompanyModel::find(decrypt($id));
        $parent = HrCompanyModel::where('id','!=',$company->id)->pluck('name', 'id');
        return view('hr.company-structure.edit',compact('company','parent'));
    }

    public function update(Request $request, $id)
    {
        $this->validate($request,[
            'name'=>'required',
            'type'=>'required',
        ]);
        $com = HrCompanyModel::find($id);
        $com->name = $request->name;
        $com->type = $request->type;
        $com->parent_id = $request->parent_id;
        $com->address = $request->address;
        $com->note = $request->note;
        $com->update();
        return redirect()->route('hr-company-structure.index')->with('success','Structure was updated successful...');
    }

    public function destroy($id)
    {
        //
    }
}
