<?php

namespace App\Http\Controllers\HR;

use App\Fun\Fun;
use App\Model\Hr\HrEmployeeBenefitModel;
use App\Model\Hr\HrGenSalaryModel;
use App\Model\Hr\HrJobBenefitModel;
use App\Model\Hr\HrOvertimeRequestModel;
use App\Model\Hr\HrTravelRequestModel;
use App\Model\setup\BranchModel;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Hr\HrDepartmentModel;
use App\Model\Hr\HrPositionModel;
use Symfony\Component\HttpFoundation\Response;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Facades\Gate;

class HrGenSalaryController extends Controller
{

    function __construct()
    {
        $this->middleware('permission:Salary  Create', ['only' => ['create', 'store']]);
        $this->middleware('permission:Salary  List', ['only' => ['index']]);
        $this->middleware('permission:Salary  Show', ['only' => ['show']]);
        Fun::lang();
    }
    public function index()
    {
        return view('hr.generate-salary.index');
    }

    public function create()
    {

        $emp        = User::where('status',1)->pluck('name','id');
        $branch     = BranchModel::pluck('name', 'id');
        $department = HrDepartmentModel::pluck('english_name', 'id');
        $position   = HrPositionModel::pluck('english_name', 'id');
        return view('hr.generate-salary.create',compact('emp', 'branch', 'department', 'position'));
    }

    public function store(Request $request)
    {

        try{
            $emp_id_ch  = $request->emp_id_ch;

            $from_date  = $request->from_date;
            $from_date  = explode('-', $from_date);
            $from_date  = $from_date[2].'-'.$from_date[1].'-'.$from_date[0];

            $to_date    = $request->to_date;
            $to_date    = explode('-', $to_date);
            $to_date    = $to_date[2].'-'.$to_date[1].'-'.$to_date[0];

            $g_date     = date('Y-m-d', strtotime(now()));

            $m_y        = $request->month_year;
            $m_y        = explode('-',$m_y);
            $month      = isset($m_y[0])?$m_y[0]: date('m');
            $year       = isset($m_y[1])?$m_y[1]: date('Y');


            $basic_salary               = $request->basic_salary;
            $advance_salary             = $request->advance_salary;
            $take_leave                 = $request->take_leave;
            $benefit                    = $request->benefit;
            $total_ot                   = $request->total_ot;
            $exchange_rate_kh           = $request->exchange_rate_kh;
            $exchange_rate_th           = $request->exchange_rate_th;
            $exchange_rate              = $request->exchange_rate;
            $net_pay_kh                 = $request->net_pay_kh;
            $net_pay_th                 = $request->net_pay_th;
            $net_pay                    = $request->net_pay;
            $work_sun                   = $request->work_sun;


            if (is_array($emp_id_ch)) {
                if (count($emp_id_ch) > 0) {
                    foreach ($emp_id_ch as $k => $v) {
                        $m = HrGenSalaryModel::where('f_year', $year)
                            ->where('f_month', $month)
                            ->where('emp_id', $v)->first();

                        if ($m == null) {
                            $m = new HrGenSalaryModel();
                        }

                        if ($m != null) {

                            $em = User::find($v);
                            $m->branch_id                   = $em->branch_id;
                            $m->department_id               = $em->department_id;
                            $m->position_id                 = $em->position_id;
                            $m->emp_id                      = $v;

                            $m->from_date                   = $from_date;
                            $m->to_date                     = $to_date;
                            $m->g_date                      = $g_date;

                            $m->f_year                      = $year;
                            $m->f_month                     = $month;

                            $m->basic_salary                = isset($basic_salary[$k]) ? $basic_salary[$k] : 0;
                            $m->advance_salary              = isset($advance_salary[$k]) ? $advance_salary[$k] : 0;
                            $m->take_leave                  = isset($take_leave[$k]) ? $take_leave[$k] : 0;

                            $m->benefit                     = isset($benefit[$k]) ? $benefit[$k] : 0;
                            $m->total_ot                    = isset($total_ot[$k]) ? $total_ot[$k] : 0;
                            $m->working_sunday              = isset($work_sun[$k]) ? $work_sun[$k] : 0;

                            $m->exchange_rate_kh            = isset($exchange_rate_kh[$k]) ? $exchange_rate_kh[$k] : 0;
                            $m->exchange_rate_th            = isset($exchange_rate_th[$k]) ? $exchange_rate_th[$k] : 0;
                            $m->exchange_rate               = isset($exchange_rate[$k]) ? $exchange_rate[$k] : 0;

                            $m->net_pay_kh                  = isset($net_pay_kh[$k]) ? $net_pay_kh[$k] : 0;
                            $m->net_pay_th                  = isset($net_pay_th[$k]) ? $net_pay_th[$k] : 0;
                            $m->net_pay                     = isset($net_pay[$k]) ? $net_pay[$k] : 0;

                            $m->status  = 1;

                            $m->save();
                        }
                    }
                }
            }
            return redirect()->route('hr-generate-salary.index')->with('success','Salary inserted successful');
        }catch(\Exception $ex){
            return back()->withErrors($ex->getMessage())->withInput();
        }
    }

    public function show($id)
    {
        $id = decrypt($id);
        $payroll = HrGenSalaryModel::find($id);
        return view('hr.generate-salary.view-payslip', compact('payroll') );
    }


    public function update(Request $request)
    {

    }

    public function destroy($id)
    {
        $id = decrypt($id);
        HrGenSalaryModel::find($id)->delete();
        return redirect()->route('hr-generate-salary.index')->with('success','Record has been deleted...');

    }
    public function delete_generate(Request $request)
    {
        $id = $request->delete_id;
        HrGenSalaryModel::find($id)->update(['status', 0]);
        return redirect()->route('hr-generate-salary.index')->with('success','Record has been deleted...');
    }
    public function generate_payroll(Request $request)
    {

        $emp_id         = $request->emp_id;
        $branch_id      = $request->branch_id;
        $department_id  = $request->department_id;
        $position_id    = $request->position_id;
        $from_date      = $request->from_date;
        $to_date        = $request->to_date;
        $month          = $request->month_year;

        $emp = User::where(function ($q) use ($emp_id)
        {
            if($emp_id != null){
                if(is_array($emp_id)){
                    if(count($emp_id) > 0){
                        $q->whereIn('id', $emp_id);
                    }
                }else{
                    $q->whereIn('id', $emp_id);
                }
            }
        })
        ->where(function ($q) use ($branch_id){
            if(is_array($branch_id)){
                if(count($branch_id)>0){
                    $q->whereIn('branch_id', $branch_id);
                }
            }
        })
        ->where(function ($q) use ($department_id){
            if(is_array($department_id)){
                if(count($department_id)>0){
                    $q->whereIn('department_id', $department_id);
                }
            }
        })
        ->where(function ($q) use ($position_id){
            if(is_array($position_id)){
                if(count($position_id)>0){
                    $q->whereIn('position_id', $position_id);
                }
            }
        })
        ->where('user_type', '<>', 'seller')
        ->where('status', 1)
        ->get();

        return view('hr.generate-salary.show',compact('emp','from_date','to_date', 'month', 'emp_id'));

    }
    public function get_gen_salary(Request $request)
    {
        $search         = $request->input('search.value');
        $count_total    = HrGenSalaryModel::where('status', 1)->count();

        $gen_salary     = HrGenSalaryModel::select('nso007_hr_gen_salaries.*', 'users.name')
                                        ->join('users', 'users.id', 'nso007_hr_gen_salaries.emp_id')
                                        ->where(function ($query) use ($search){
                                            $query->orWhere('users.name', 'LIKE',"%$search%");
                                        })
                                        ->where('nso007_hr_gen_salaries.status',1);

        $count_filter = $gen_salary->count();
        return DataTables::of($gen_salary->take(20))
            ->addIndexColumn()
            ->with([
                'recordsTotal' => $count_total,
                'recordsFiltered' => $count_filter
            ])
            ->editColumn('emp_id', function ($gen_salary) {
                return optional($gen_salary->employee)->name;
            })
            ->editColumn('basic_salary', function($data){
                return $data->basic_salary ? '$ '.number_format($data->basic_salary, 2) : 0;
            })
            ->editColumn('advance_salary', function($data){
                return $data->advance_salary ? '$ '.number_format($data->advance_salary, 2) : 0;
            })
            ->editColumn('take_leave', function($data){
                return $data->take_leave ? '$ '.number_format($data->take_leave, 2) : 0;
            })
            ->editColumn('benefit', function($data){
                return $data->benefit ? '$ '.number_format($data->benefit, 2) : 0;
            })
            ->editColumn('total_ot', function($data){
                return $data->total_ot ? '$ '.number_format($data->total_ot, 2) : 0;
            })
            ->editColumn('net_pay_kh', function($data){
                return $data->net_pay_kh ? '៛ '.number_format($data->net_pay_kh, 2) : 0;
            })
            ->editColumn('net_pay_th', function($data){
                return $data->net_pay_th ? '฿ '.number_format($data->net_pay_th, 2) : 0;
            })
            ->editColumn('net_pay', function($data){
                return $data->net_pay ? '$ '.number_format($data->net_pay, 2) : 0;
            })
            ->addColumn('action', function ($data) {
                $btn = '';
                if(Gate::Check('Salary  Delete'))
                {
                    $btn .=' <li><a class="button_danger btn-delete-gen" data-id="'.$data->id.'" title="Delete"><span class="fa fa-trash"></span></a></li>';
                }
                return $btn;
            })
            ->rawColumns(['action' => 'action'])
            ->make(true);

    }

}
