<?php

namespace App\Http\Controllers\HR;

use App\Fun\Fun;
use App\HrEmployeeBenefitModel;
use App\HrEmployeeBenefitModel as AppHrEmployeeBenefitModel;
use App\HrGenSalaryModel;
use App\HrJobBenefitModel;
use App\HrOvertimeRequestModel;
use App\HrTravelRequestModel;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Symfony\Component\HttpFoundation\Response;
use Yajra\DataTables\DataTables;

class HrGenSalaryController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:Generate-Salary-List');
        $this->middleware('permission:Generate-Salary-Create', ['only' => ['create','store']]);
        $this->middleware('permission:Generate-Salary-Edit', ['only' => ['edit','update']]);
        $this->middleware('permission:Generate-Salary-Show', ['only' => ['show']]);
    }
    public function index()
    {
        return view('hr.generate-salary.index');
    }

    public function create()
    {
        
        $emp = User::where('status',1)->pluck('name','id');
        return view('hr.generate-salary.create',compact('emp'));
    }

    public function store(Request $request)
    { 
        $this->validate($request,[
            'chk.*'=>'required',
            'date'=>'required',
            'emp_id.*'=>'required',
        ]);
        
        $ot = $request->ot;
        $check = $request->chk;
        $emp_id = $request->emp_id;
        $date = $request->date;
        $net_payment = $request->net_payment;
        $benefit = $request->benefit;
        
        $date = explode('-', $date);
        $month = $date[0];
        $year = $date[1];
        
        if($check){
            foreach($check as $key => $row){

                $emp                = User::find($emp_id[$row]);

                $gen                = new HrGenSalaryModel();
                $gen->emp_id        = $emp_id[$row];
                $gen->code          = $emp->code;
                $gen->name          = $emp->name;
                $gen->email         = $emp->email;
                $gen->phone         = $emp->phone;
                $gen->month         = $month;
                $gen->year          = $year;
                $gen->joined_date   = $emp->joined_date;
                $gen->leader_id     = $emp->leader_id;
                $gen->department_id = $emp->department_id;
                $gen->group_id      = $emp->group_id;
                $gen->employment_id = $emp->employment_id;
                $gen->id_card       = $emp->id_card;
                $gen->job_id        = $emp->job_id;
                $gen->marital_status = $emp->marital_status;
                $gen->nationality   = $emp->nationality;
                $gen->date_of_birth = $emp->date_of_birth;
                $gen->address       = $emp->address;
                $gen->gender        = $emp->gender;
                $gen->ot            = $ot[$row];
                $gen->benefit       = $benefit[$row];
                $gen->basic_salary  = $emp->basic_salary;
                $gen->place_of_birth = $emp->place_of_birth;
                $gen->net_payment   = $net_payment[$row];
                $gen->save();
                           
            }
        }
        else{
            return redirect()->route('hr-generate-salary.create');
        }
        return redirect()->route('hr-generate-salary.index')->with('success','Salary inserted successful');
    }

    public function show($id)
    {
        
        $id = decrypt($id);
        $emp = HrGenSalaryModel::find($id);

        $year = $emp->year;
        $month = $emp->month;
        $s_date = $year.'-'.$month.'-01';
        $e_date = $year.'-'.$month.'-'.date('t',strtotime( $year.'-'.$month.'-01'));

        $benefit = HrEmployeeBenefitModel::where('emp_id', $emp->emp_id)->get();
        $ot = HrOvertimeRequestModel::where('emp_id',$emp->emp_id)
                                    ->where('date','>=',$s_date)
                                    ->where('date','<=',$e_date)
                                    ->where('status',1)
                                    ->get();
        // dd($id, $emp, $emp->id, $ot);
        return view('hr.generate-salary.view-payslip', compact('emp','benefit','ot') );
    }


    public function update(Request $request, $id)
    {
        
    }

    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 generate_payroll(Request $request)
    {
        
        $emp_id =  $request->emp_id;
        $emp_id = explode(',',$emp_id);
        $date  = $request->date;

        $date = explode('-', $date);
        $month = $date[0];
        $year = $date[1];
        
        if ($emp_id[0] != "") 
        {
            $row = User::where('status', '=', '1')->where(function ($q) use ($emp_id) {
                if (count($emp_id) > 0) 
                {
                    foreach ($emp_id as $row) 
                    {
                        $q->orwhere('id', $row);
                    }
                } 
            })->get();
        }else
        {
            $row = User::where('status', '=', '1')->get();
        }
        $payroll = [];
        foreach($row as $data)
        {
            $check_exist = HrGenSalaryModel::where('month', $month)
                ->where('year', $year)
                ->where('emp_id', $data->id)
                ->count();
                if($check_exist == 0)
                {
                    $hour = 0;
                    $emp_benefit = 0;
                    // add more function calculate payroll
                    $s_date = $year.'-'.$month.'-01';
                    $e_date = $year.'-'.$month.'-'.date('t',strtotime( $year.'-'.$month.'-01'));
                   
                    $overtime = HrOvertimeRequestModel::where('emp_id',$data->id)
                                                        ->where('status',1)
                                                        ->where('date','>=',$s_date)
                                                        ->where('date','<=',$e_date)
                                                        ->get();
                    $benefit = HrEmployeeBenefitModel::where('emp_id', $data->id)->get();
                    
                    foreach($benefit as $ben)
                    {
                        $emp_benefit += $ben->amount;
                        
                    }
                    foreach($overtime as $ovt)
                    {
                        $hour += $ovt->hours;
                    }
                    
                    $payroll[] = [
                        "id"=>$data->id,
                        "code"=>$data->code,
                        "name"=>$data->name,
                        "date"=>date('M',strtotime('01-'.$request->date)),
                        "basic_salary"=>$data->basic_salary,
                        "ot" => $hour,
                        "benefit" => $emp_benefit,
                        "net_payment" => ($emp_benefit + ($hour * 5) + $data->basic_salary),
                    ];
                }
        }
       
        echo json_encode($payroll);
        
    }
    public function get_gen_salary()
    {
        
        $gen_salary = HrGenSalaryModel::where('status',1)->get();
        return DataTables::of($gen_salary)
            ->addIndexColumn()
            ->editColumn('gender', function ($data) {
                return ucfirst($data->gender);
            })
            ->addColumn('action', function ($data) {
                $check_language = Fun::lang();

                if ($check_language == 'km') {
                    $view = "មើល";
                    $delete = "លុបចោល";
                    $action = "សកម្មភាព";
                    
                } else {
                    $view = "View";
                    $delete = "Delete";
                    $action = 'Action';
                    
                }
                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><a href="' . route('hr-generate-salary.show', encrypt($data->id)) . '" class="" target="blank">' . $view . '</a></li>
                          <li><a href="' . route('hr-generate-salary.destroy', encrypt($data->id)) . '" class="">' . $delete . '</a></li>
                        </div>';
            })
            ->rawColumns(['action' => 'action', 'status' => 'status'])
            ->make(true);
            
    }
    
}