<?php

namespace App\Http\Controllers\HR;

use App\DepartmentModel;
use App\Fun\Fun;
use App\HrJobBenefitModel;
use App\HrJobEducationLevelModel;
use App\HrJobEmploymentTypeModel;
use App\HrJobExpLevelModel;
use App\HrJobFunctionModel;
use App\HrJobPostDetailModel;
use App\HrJobPostModel;
use App\ProvinceModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\DataTables;
use Gate;
class HrJobPostController extends Controller
{
    function __construct()
    {
         $this->middleware('permission:Job-Post-List');
         $this->middleware('permission:Job-Post-Create', ['only' => ['create','store']]);
         $this->middleware('permission:Job-Post-Edit', ['only' => ['edit','update']]);
         $this->middleware('permission:Job-Post-View', ['only' => ['view_job_post']]);
    }
    public function index()
    {
        return view('hr.job-post.index');
    }

    public function get_job_post(Request $request)
    {
        $search = $request->input('search.value');
        $count_total = HrJobPostModel::where('status',1)
            ->count();
        $count_filter = HrJobPostModel::where('status',1)
            ->where(function ($query) use ($search) {
//                $query->orWhere('nso007_journal.journal_acccode', 'LIKE', '%' . $search . '%');
//                $query->orWhere('nso007_journal.journal_des', 'LIKE', '%' . $search . '%');
//                $query->orWhere('nso007_journal.journal_invoice', 'LIKE', '%' . $search . '%');
//                $query->orWhere('nso007_account_chart.acc_name_en', 'LIKE', '%' . $search . '%');
            })
            ->count();
        $data = HrJobPostModel::where('status',1)
            ->orderBy('id', 'asc')
            ->take(20);
        return DataTables::of($data)
            ->addIndexColumn()
            ->with([
                "recordsTotal" => $count_total,
                "recordsFiltered" => $count_filter,
            ])
            ->editColumn('department', function ($data) {
                return optional($data->get_department)->department_name;
            })
            ->editColumn('employment_type', function ($data) {
                return optional($data->get_employment)->name;
            })
            ->editColumn('location', function ($data) {
                $check_language = Fun::lang();
                if($check_language=='km'){
                    return optional($data->get_location)->province_km;
                }
                else{
                    return optional($data->get_location)->province_en;
                }

            })
            ->addColumn('action', function ($capital) {
                $check_language = Fun::lang();

                if ($check_language == 'km') {
                    $edit = "កែសម្រួល";
                    $action = "សកម្មភាព";
                    $delete = "លុប";
                    $task = "ភារកិច្ច";
                    $view = "បង្ហាញ";

                } else {
                    $task = "Task";
                    $delete = "Delete";
                    $edit = "Edit";
                    $action = 'Action';
                    $view = 'View';

                }
                $li_view = '';
                $li_edit = '';
                if(Gate::check('Job-Post-View')){
                    $li_view = '<li><a class="viewot" role="button" data-id="' . $capital->id . '" data-toggle="modal tooltip" data-target="#viewModal" data-placement="top" title="View">'.$view.'</a></li>';
                }
                if(Gate::check('Job-Post-Edit')){
                    $li_edit = '<li><a href="' . route("hr-job-post.edit", $capital->id) . '" title="Edit">'.$edit.'</a></li>';
                }
                if(Gate::check('Job-Post-View') || Gate::check('Jop-Post-Edit')){
                    return '<div class="btn-group">
                    <button type="button" class="btn btn-reddit dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                      '.$action.' <span class="fa fa-caret-down"></span>
                    </button>
                    <div class="dropdown-menu dropdown-menu-right">
                      '.$li_view.'
                      '.$li_edit.'
                      </div>
                    </div>';
                }else{
                    return '';
                }
            })
            ->rawColumns(['action' => 'action', 'status' => 'status'])
            ->make(true);


    }

    public function create()
    {
        $benefit = HrJobBenefitModel::selectRaw('CONCAT(id,"+",name) as value,name')->where('status',1)->pluck('name','value');
        $emp_type = HrJobEmploymentTypeModel::where('status',1)->pluck('name','id');
        $exp_level = HrJobExpLevelModel::where('status',1)->pluck('name','id');
        $job_func = HrJobFunctionModel::where('status',1)->pluck('name','id');
        $edu_level = HrJobEducationLevelModel::where('status',1)->pluck('name','id');
        $department = DepartmentModel::where('delete_status',0)->pluck('department_name','id');
        $check_language = Fun::lang();
        if($check_language=='km'){
            $province = ProvinceModel::pluck('province_km','province_id');
        }else{
            $province = ProvinceModel::pluck('province_en','province_id');
        }
        return view('hr.job-post.create',compact('benefit','emp_type','exp_level','job_func','edu_level','department','province'));
    }

    public function store(Request $request)
    {
        $this->validate($request,[
            'job_code'=>'required|unique:nso007_hr_job_post,job_code',
            'job_title'=>'required',
            'requirement'=>'required',
            'department'=>'required',
            'employment_type'=>'required',
            'closing_date'=>'required',
        ]);
        $benefit = $request->benefit;
        $arr1 = [];
//        explode benefit to array 1
        foreach ($benefit as $key=>$row){
            $arr1[$key] = (explode(',',$row))[0];
        }
        $job = new HrJobPostModel();
        $job->job_code = $request->job_code;
        $job->job_title = $request->job_title;
        $job->company_name = $request->company_name;
        $job->job_description = $request->job_description;
        $job->requirement = $request->requirement;
        $job->department = $request->department;
        $job->job_function = $request->job_function;
        $job->sex = $request->sex;
        $job->from_age = $request->from_age;
        $job->to_age = $request->to_age;
        $job->employment_type = $request->employment_type;
        $job->exp_level = $request->exp_level;
        $job->exp_year = $request->exp_year;
        $job->education_level = $request->education_level;
        $job->currency = $request->currency;
        $job->salary_min = $request->salary_min;
        $job->salary_max = $request->salary_max;
        $job->hiring_amt = $request->hiring_amt;
        $job->location = $request->location;
        $job->closing_date = date('Y-m-d',strtotime($request->closing_date));
        $job->status = 1;
        $job->save();

        // save benefit
        foreach ($arr1 as $key => $row){
            if($row!=null){
                $ben = new HrJobPostDetailModel();
                $ben->component_id = (explode('+',$row))[0];
                $ben->name = (explode('+',$row))[1];
                $ben->job_post_id = $job->id;
                $ben->type = 'benefit';
                $ben->save();
            }
        }
        return redirect()->route('hr-job-post.index')->with('success','Job position was save successful...');
    }

    public function show($id)
    {
        //
    }

    public function edit($id)
    {
        $store = [];
        $job_post = HrJobPostModel::find($id);
        $benefit = HrJobBenefitModel::selectRaw('CONCAT(id,"+",name) as value,name')->where('status',1)->pluck('name','value');
        $get_benefit = HrJobPostDetailModel::selectRaw('CONCAT(component_id,"+",name) as value,name')->where('job_post_id',$id)->pluck('name','value');
        foreach ($get_benefit as $key=>$row){
            $store[] = $key;
        }
        $emp_type = HrJobEmploymentTypeModel::where('status',1)->pluck('name','id');
        $exp_level = HrJobExpLevelModel::where('status',1)->pluck('name','id');
        $job_func = HrJobFunctionModel::where('status',1)->pluck('name','id');
        $edu_level = HrJobEducationLevelModel::where('status',1)->pluck('name','id');
        $department = DepartmentModel::where('delete_status',0)->pluck('department_name','id');
        $check_language = Fun::lang();
        if($check_language=='km'){
            $province = ProvinceModel::pluck('province_km','province_id');
        }else{
            $province = ProvinceModel::pluck('province_en','province_id');
        }
        return view('hr.job-post.edit',compact('benefit','emp_type','exp_level','job_func','edu_level','department','province','job_post','store'));
    }

    public function update(Request $request, $id)
    {
        $this->validate($request,[
            'job_code'=>'required|unique:nso007_hr_job_post,job_code,'.$id,
            'job_title'=>'required',
            'requirement'=>'required',
            'department'=>'required',
            'employment_type'=>'required',
            'closing_date'=>'required',
        ]);
        $benefit = $request->benefit?$request->benefit:[];
        $arr1 = [];
//        explode benefit to array 1
        foreach ($benefit as $key=>$row){
            $arr1[$key] = (explode(',',$row))[0];
        }
        $job = HrJobPostModel::find($id);
        $job->job_code = $request->job_code;
        $job->job_title = $request->job_title;
        $job->company_name = $request->company_name;
        $job->job_description = $request->job_description;
        $job->requirement = $request->requirement;
        $job->department = $request->department;
        $job->job_function = $request->job_function;
        $job->sex = $request->sex;
        $job->from_age = $request->from_age;
        $job->to_age = $request->to_age;
        $job->employment_type = $request->employment_type;
        $job->exp_level = $request->exp_level;
        $job->exp_year = $request->exp_year;
        $job->education_level = $request->education_level;
        $job->currency = $request->currency;
        $job->salary_min = $request->salary_min;
        $job->salary_max = $request->salary_max;
        $job->hiring_amt = $request->hiring_amt;
        $job->location = $request->location;
        $job->closing_date = date('Y-m-d',strtotime($request->closing_date));
        $job->update();
        // save benefit
        HrJobPostDetailModel::where('job_post_id',$job->id)->delete();
        foreach ($arr1 as $key => $row){
            if($row!=null){
                $ben = new HrJobPostDetailModel();
                $ben->component_id = (explode('+',$row))[0];
                $ben->name = (explode('+',$row))[1];
                $ben->job_post_id = $job->id;
                $ben->type = 'benefit';
                $ben->save();
            }
        }
        return redirect()->route('hr-job-post.index')->with('success','Job position was update successful...');
    }

    public function destroy($id)
    {
        //
    }
    public function view_job_post(){
        $job_post = HrJobPostModel::find($_GET['id']);
        $benefit = HrJobPostDetailModel::where('job_post_id',$job_post->id)->get();
        $label_benefit = '';
        if($benefit->count()>0){
            foreach ($benefit as $key => $row){
                $br = '';
                if($key%2 == 1){
                    $br = '';
                }
                $label_benefit .= '&nbsp<span class="my-label my-bg-red">'.$row->name.'</span>'.$br;
            }
        }
        $check_language = Fun::lang();
        if ($check_language == 'km') {
            $pending = "រង់ចាំ";
            $approve = "ទទួលយកសំណើរ";
            $reject = "បដិសេធសំណើរ";
            $male = "ប្រុស";
            $female = "ស្រី";
            $year = 'ឆ្នាំ';
            $riel = "រៀល";
            $usd = "ដុល្លា";
            $per = "នាក់";
            $province = optional($job_post->get_location)->province_km;
        } else {
            $pending = "Pending";
            $reject = "Rejected";
            $approve = "Approved";
            $male = "Male";
            $female = "Female";
            $year = "Year(s)";
            $riel = "Riel";
            $usd = "USD";
            $per = "";
            $province = optional($job_post->get_location)->province_en;
        }
        $gender = '';
        if($job_post->sex == 'male'){
            $gender = $male;
        }
        if($job_post->sex == 'female'){
            $gender = $female;
        }
        if($job_post->currency == 'usd'){
            $currency = $usd;
        }else{
            $currency = $riel;
        }
        $data = [
            'job_code'=>$job_post->job_code,
            'job_title'=>$job_post->job_title,
            'job_description'=>$job_post->job_description,
            'requirement'=>$job_post->requirement,
            'department'=>optional($job_post->get_department)->department_name,
            'employment_type'=>optional($job_post->get_employment)->name,
            'exp_year'=>$job_post->exp_year.$year,
            'job_function'=>optional($job_post->get_job_function)->name,
            'education_level'=>optional($job_post->get_education_level)->name,
            'currency'=>$job_post->currency,
            'salary'=>$job_post->salary_min.$currency.' <span class="fa fa-arrow-right"></span> '.$job_post->salary_max.$currency,
            'hiring_amt'=>$job_post->hiring_amt.$per,
            'sex'=>$gender,
            'age'=>$job_post->from_age.$year .' <span class="fa fa-arrow-right"></span> '.$job_post->to_age.$year,
            'location'=>$province,
            'benefit'=>$label_benefit,
            'closing_date'=>date('Y-m-d',strtotime($job_post->closing_date)),
        ];
        return response()->json(['datas' => $data]);
    }
}
