<?php

namespace App\Http\Controllers\HR;

use App\Model\Hr\HrDepartmentModel;
use App\Fun\Fun;
use App\Model\Hr\HrCandidateModel;
use App\Model\Hr\HrJobBenefitModel;
use App\Model\Hr\HrJobEducationLevelModel;
use App\Model\Hr\HrJobEmploymentTypeModel;
use App\Model\Hr\HrJobExpLevelModel;
use App\Model\Hr\HrJobFunctionModel;
use App\Model\Hr\HrJobPostDetailModel;
use App\Model\Hr\HrJobPostModel;
use App\Model\ProvinceModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Facades\Gate;

class HrJobPostController extends Controller
{

    function __construct()
    {
        $this->middleware('permission:Job Position Create', ['only' => ['create', 'store']]);
        $this->middleware('permission:Job Position List', ['only' => ['index', 'get_job_post']]);
        $this->middleware('permission:Job Position Edit', ['only' => ['update', 'edit']]);
        $this->middleware('permission:Job Position Show', ['only' => ['show', '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 = "បង្ហាញ";
                    $veiw_job = "បង្ហាញការងារ";
                    $view_web = 'បង្ហាញ Web';

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

                }
                $btn = '<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">';
                if (Gate::check('Job Position Show')) {
                    $btn .= '<li><a href="' . route('hr.view-web', ($capital->id)) . '" class="" target="blank">' . $view_web . '</a></li>';
                    $btn .= '<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 Position Edit')) {
                    $btn .= '<li><a href="' . route("hr-job-post.edit", $capital->id) . '" title="Edit">' . $edit . '</a></li>';
                }
                $btn .= '</div>';
                return $btn;

            })
            ->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 = HrDepartmentModel::where('delete_status', 1)->pluck('english_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',
        ]);
        try{
            $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...');
        }catch(\Exception $ex){
            return back()->withErrors($ex->getMessage())->withInput();
        }
    }

    public function show($id)
    {
        //
        $job_post = HrJobPostModel::find($id);

        return view('hr.job-post.view-job', compact('id', 'job_post'));
    }

    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 = HrDepartmentModel::where('delete_status', 1)->pluck('english_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',
        ]);
        try{
            $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...');
        }catch(\Exception $ex){
            return back()->withErrors($ex->getMessage())->withInput();
        }
    }

    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('d-m-Y', strtotime($job_post->closing_date)),
        ];

        return response()->json(['datas' => $data]);
    }

    public function job_post(Request $request)
    {

        $this->validate($request, [
            'first_name' => 'required',
            'last_name' => 'required',
            'sex' => 'required',
            'phone' => 'required',
            'email' => 'required',
            'cv' => 'required',

        ]);

        try {
            $candidate = new HrCandidateModel();
            $candidate->firstname = $request->first_name;
            $candidate->lastname = $request->last_name;
            $candidate->gender = $request->sex;
            $candidate->phone = $request->phone;
            $candidate->email = $request->email;
            $candidate->job_post_id = $request->job_post_id;

            //file CV
            if ($request->cv) {
                $newfile = $request->cv;
                $file_name = $newfile->getClientOriginalName();
                if (strlen($file_name) > 90) {
                    $ext = $newfile->getClientOriginalExtension();
                    $file_name = $request->lastname . date('his') . '.' . $ext;
                } else {
                    $file_name = $request->lastname . date('his') . $file_name;
                }
                $destinationPath = 'images/cv';
                $newfile->move($destinationPath, $file_name);
            }
            $candidate->cv = $file_name;
            $candidate->save();

            return redirect()->route('hr.view-web', ($request->job_post_id))->with('success', 'Job post was save successful...');
        } catch (\Exception $ex) {
            return back()->withErrors($ex->getMessage())->withInput();
        }

    }
}
