<?php

namespace App\Http\Controllers\HR;

use App\Fun\Fun;
use App\Helpers\IDate;
use App\Helpers\IString;
use App\Model\Hr\EmpLeave;
use App\Model\Hr\EmpLeaveDetail;
use App\Model\Hr\Employee;
use App\Model\Hr\EmployeeLeaveTotal;
use App\Model\Hr\LeaveType;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Yajra\DataTables\DataTables;


class TakeLeaveController extends Controller
{

    function __construct()
    {
      $this->middleware('permission:Take Leave List', ['only' => ['index']]);
      $this->middleware('permission:Take Leave Create', ['only' => ['create','store']]);
      $this->middleware('permission:Take Leave Edit', ['only' => ['edit','update']]);
      $this->middleware('permission:Take Leave Approve', ['only' => ['change_status']]);
    }
    public function index(Request $request)
    {
        $search = $request->input('search.value');
        if ($request->ajax()) {
            $count_total    = EmpLeave::count();
            $data           = EmpLeave::select('emp_leaves.*', 'users.name')
                                    ->join('users', 'users.id', 'emp_leaves.emp_id')
                                    ->where(function ($query) use ($search){
                                        $query->orWhere('users.name', 'LIKE', "%$search%");
                                    })
                                    ->orderBy('id', 'DESC');
            $count_filter = $data->count();
            return Datatables::of($data->take(20))
                ->addIndexColumn()
                ->with([
                    'recordsTotal' => $count_total,
                    'recordsFiltered' => $count_filter
                ])
                ->editColumn('emp_id',function ($d){
                    return optional(User::find($d->emp_id))->name;
                })
                ->editColumn('request_to',function ($d){
                    return optional(User::find($d->request_to))->name;
                })
                ->editColumn('from_date', function($data){
                    return $data->from_date ? date('d-m-Y', strtotime($data->from_date)) : "";
                })
                ->editColumn('to_date', function($data){
                    return $data->to_date ? date('d-m-Y', strtotime($data->to_date)) : "";
                })
                ->editColumn('leave_type', function($data){
                    return IString::getUpperCaseCharacter(optional($data->leave_typee)->name);
                })
                ->editColumn('request_date', function($data){
                    return $data->request_date ? date('d-m-Y', strtotime($data->request_date)) : "";
                })
                ->editColumn('deduct', function($data){
                    return $data->deduct ? '$ '.$data->deduct : '';
                })
                ->editColumn('review', function($data){
                    $review  = $data->review?$data->review: "";
                    if($review == 0)
                    {
                        $status = '<small class="label label-primary">pending</small>';

                    }elseif($review == 1){
                        $status = '<small class="label label-success">approved</small>';

                    }elseif($review == 2){
                        $status = '<small class="label label-danger">rejected</small>';
                    }

                    return $status;

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

                    if ($check_language == 'km') {
                        $status = "ស្ថានភាព";
                        $edit = "កែសម្រួល";
                        $view = "បង្ហាញ";
                        $delete = "លុបចោល";
                        $deduct​ = "កាត់លុយ";
                    }else{
                        $status = "Status";
                        $edit = "Edit";
                        $view = "View";
                        $delete = "Delete";
                        $deduct​ = "Deduct";
                    }
                    $btn = '';
                    if(Gate::check('Take Leave Status')){
                        /*if ($data->review == 0) {
                            $btn .= '<a class="button_primary btn_status" title="'.$status.'" data-id="'.$data->id.'"><span class="fa fa-spinner"></span></a>';
                        }elseif($data->review == 1){
                            $btn .= '<small class="label label-primary">approved</small>';
                        }elseif($data->review == 2){
                            $btn .= '<small class="label label-danger">rejected</small>';
                        }*/
                    }
                    if(Gate::check('Take Leave View')) {
                        $btn .= '<a href="' . route('take-leave-form', $data->id) . '" target="_blank" class="button_success" title="' . $view . '"><span class="fa fa-eye"></span></a>';
                    }
                    if ($data->review == 1 && $data->approve == 0) {
                        $salary = User::select('basic_salary')->where('id', $data->emp_id)->first();
                        $deduct_per_day = $salary->basic_salary ? ($salary->basic_salary / 26) : 0;
                        $btn .= '<a class="button_primary btn_deduct" title="' . $deduct​ . '" data-id="' . $data->id . '" data-salary="'.$deduct_per_day.'"><span class="fa fa-usd"></span></a>';
                    }
                    if(Gate::check('Take Leave Edit')){
                        $btn .= '<a href="'.route('take-leave.edit', $data->id).'" class="button_warning" title="'.$edit.'"><span class="fa fa-pencil-square-o"></span></a>';
                    }
                    if(Gate::check('Take Leave Delete')) {
                        $btn .= '<a class="button_danger btn_delete" title="' . $delete . '" data-id="' . $data->id . '"><span class="fa fa-trash"></span></a>';
                    }

                    return $btn;
                })
                ->rawColumns(['action' => 'action', 'review' => 'review'])
                ->make(true);
        }

        return view('hr.take-leave.index');
    }

    public function create()
    {
        $emp        = Employee::where('status', 1)->pluck('name', 'id');
        $leave_type = LeaveType::pluck('name','id');
        return view('hr.take-leave.create', compact('emp','leave_type'));


    }

    public function store(Request $r)
    {

        $this->validate($r,[
            'emp_id'        => 'required',
            'leave_type'    => 'required',
            'from_date'     => 'required',
            'to_date'       => 'required'
        ]);

        try{
            $emp_id             = $r->emp_id;
            $employee           = User::find($emp_id);
            $from_date          = IDate::dateYMD($r->from_date);
            $to_date            = IDate::dateYMD($r->to_date);
            $date_range         = IDate::createDateRange($from_date, $to_date);
            $leave_id           = $r->leave_type;
            $request_to         = $r->request_to;
            $request_date       = IDate::dateYMD($r->request_date);
            $leave_year         = date('Y', strtotime(now()));
            $reason             = $r->reason;
            $num_take_leave     = count($date_range)?count($date_range):0;

            $emp_leave                  = new EmpLeave();
            $emp_leave->emp_id          = $emp_id;
            $emp_leave->branch_id       = $employee->branch_id;
            $emp_leave->department_id   = $employee->department_id;
            $emp_leave->position_id     = $employee->position_id;
            $emp_leave->from_date       = $from_date;
            $emp_leave->to_date         = $to_date;
            $emp_leave->leave_type      = $leave_id;
            $emp_leave->request_to      = $request_to;
            $emp_leave->request_date    = $request_date;
            $emp_leave->reason          = $reason;
            $emp_leave->num_take_leave  = $num_take_leave;
            $emp_leave->review          = 1;
            $emp_leave->save();

            $total_leave            = EmpLeave::select(DB::raw('SUM(num_take_leave) AS total'))
                ->where('emp_id', $emp_id)
                ->where('leave_type', $leave_id)
                ->where('leave_year', $leave_year)
                ->first();

            $emp_leave_total        = EmployeeLeaveTotal::where('emp_id', $emp_id)
                ->where('leave_year', $leave_year)
                ->first();

            $total                  = $num_take_leave + ($total_leave->total ? $total_leave->total : 0);

            if($emp_leave_total != '')
            {
                $total_special_leave    = $emp_leave_total->special_leave ? $emp_leave_total->special_leave : 0;
                $total_annual_leave     = $emp_leave_total->annual_leave ? $emp_leave_total->annual_leave : 0;
                $total_sick_leave       = $emp_leave_total->sick_leave ? $emp_leave_total->sick_leave : 0;
                $total_maternity_leave  = $emp_leave_total->maternity_leave ? $emp_leave_total->maternity_leave : 0;
                $total_unpaid_leave     = $emp_leave_total->unpaid_leave ? $emp_leave_total->unpaid_leave : 0;
                $total_other_leave      = $emp_leave_total->other_leave ? $emp_leave_total->other_leave : 0;

                if($leave_id == 1)
                {
                    EmployeeLeaveTotal::where('emp_id', $emp_id)
                        ->where('leave_year', $leave_year)
                        ->update([
                            'special_leave_use' => $total ,
                            'special_leave_bal' => $total_special_leave - $total,
                        ]);
                }

                if($leave_id == 2)
                {
                    EmployeeLeaveTotal::where('emp_id', $emp_id)
                        ->where('leave_year', $leave_year)
                        ->update([
                            'sick_leave_use' => $total ,
                            'sick_leave_bal' => $total_sick_leave - $total,
                        ]);
                }

                if($leave_id == 3)
                {
                    EmployeeLeaveTotal::where('emp_id', $emp_id)
                        ->where('leave_year', $leave_year)
                        ->update([
                            'maternity_leave_use' => $total,
                            'maternity_leave_bal' => $total_maternity_leave - $total,
                        ]);
                }

                if($leave_id == 4)
                {
                    EmployeeLeaveTotal::where('emp_id', $emp_id)
                        ->where('leave_year', $leave_year)
                        ->update([
                            'annual_leave_use' => $total,
                            'annual_leave_bal' => $total_annual_leave - $total,
                        ]);
                }

                if($leave_id == 5)
                {
                    EmployeeLeaveTotal::where('emp_id', $emp_id)
                        ->where('leave_year', $leave_year)
                        ->update([
                            'unpaid_leave_use' => $total,
                            'unpaid_leave_bal' => $total_unpaid_leave - $total,
                        ]);
                }

                if($leave_id == 6)
                {
                    EmployeeLeaveTotal::where('emp_id', $emp_id)
                        ->where('leave_year', $leave_year)
                        ->update([
                            'other_leave_use' => $total,
                            'other_leave_bal' => $total_other_leave - $total,
                        ]);
                }

            }

            if(is_array($date_range)){
                if(count($date_range) > 0){
                    foreach ($date_range as $k => $v){

                        $m = new EmpLeaveDetail();
                        $m->emp_id = $emp_id;
                        $m->emp_leave_id = $emp_leave->id;
                        $m->leave_date = $date_range[$k];
                        $m->leave_type = $leave_id;
                        $m->save();

                    }
                }
            }


            return redirect('take-leave')->with('success', 'Added employee leave success full');
        }catch(\Exception $ex){
            return back()->withErrors($ex->getMessage())->withInput();
        }

    }

    public function show($id)
    {

    }

    public function edit($id)
    {
        $emp_leave  = EmpLeave::find($id);
        $emp        = Employee::where('status', 1)->pluck('name', 'id');
        $leave_type = LeaveType::pluck('name','id');

        return view('hr.take-leave.edit', compact('emp_leave','emp','leave_type'));
    }

    public function update(Request $r, $id)
    {
        $this->validate($r,[
            'emp_id'        => 'required',
            'leave_type'    => 'required',
            'from_date'     => 'required',
            'to_date'       => 'required'
        ]);

        try{
            $emp_id             = $r->emp_id;
            $employee           = User::find($emp_id);
            $from_date          = IDate::dateYMD($r->from_date);
            $to_date            = IDate::dateYMD($r->to_date);
            $date_range         = IDate::createDateRange($from_date, $to_date);
            $leave_id           = $r->leave_type;
            $request_to         = $r->request_to;
            $request_date       = IDate::dateYMD($r->request_date);
            $leave_year         = date('Y', strtotime(now()));
            $reason             = $r->reason;
            $num_take_leave     = count($date_range)?count($date_range):0;

            $emp_leave                  = EmpLeave::find($id);
            $emp_leave->emp_id          = $emp_id;
            $emp_leave->branch_id       = $employee->branch_id;
            $emp_leave->department_id   = $employee->department_id;
            $emp_leave->position_id     = $employee->position_id;
            $emp_leave->from_date       = $from_date;
            $emp_leave->to_date         = $to_date;
            $emp_leave->leave_type      = $leave_id;
            $emp_leave->request_to      = $request_to;
            $emp_leave->request_date    = $request_date;
            $emp_leave->reason          = $reason;
            $emp_leave->num_take_leave  = $num_take_leave;
            $emp_leave->review          = 1;
            $emp_leave->update();

            $total_leave            = EmpLeave::select(DB::raw('SUM(num_take_leave) AS total'))
                ->where('emp_id', $emp_id)
                ->where('leave_type', $leave_id)
                ->where('leave_year', $leave_year)
                ->first();

            $emp_leave_total        = EmployeeLeaveTotal::where('emp_id', $emp_id)
                ->where('leave_year', $leave_year)
                ->first();

            $total                  = $num_take_leave + ($total_leave->total ? $total_leave->total : 0);

            if($emp_leave_total != '')
            {
                $total_special_leave    = $emp_leave_total->special_leave ? $emp_leave_total->special_leave : 0;
                $total_annual_leave     = $emp_leave_total->annual_leave ? $emp_leave_total->annual_leave : 0;
                $total_sick_leave       = $emp_leave_total->sick_leave ? $emp_leave_total->sick_leave : 0;
                $total_maternity_leave  = $emp_leave_total->maternity_leave ? $emp_leave_total->maternity_leave : 0;
                $total_unpaid_leave     = $emp_leave_total->unpaid_leave ? $emp_leave_total->unpaid_leave : 0;
                $total_other_leave      = $emp_leave_total->other_leave ? $emp_leave_total->other_leave : 0;

                if($leave_id == 1)
                {
                    EmployeeLeaveTotal::where('emp_id', $emp_id)
                        ->where('leave_year', $leave_year)
                        ->update([
                            'special_leave_use' => $total ,
                            'special_leave_bal' => $total_special_leave - $total,
                        ]);
                }

                if($leave_id == 2)
                {
                    EmployeeLeaveTotal::where('emp_id', $emp_id)
                        ->where('leave_year', $leave_year)
                        ->update([
                            'sick_leave_use' => $total ,
                            'sick_leave_bal' => $total_sick_leave - $total,
                        ]);
                }

                if($leave_id == 3)
                {
                    EmployeeLeaveTotal::where('emp_id', $emp_id)
                        ->where('leave_year', $leave_year)
                        ->update([
                            'maternity_leave_use' => $total,
                            'maternity_leave_bal' => $total_maternity_leave - $total,
                        ]);
                }

                if($leave_id == 4)
                {
                    EmployeeLeaveTotal::where('emp_id', $emp_id)
                        ->where('leave_year', $leave_year)
                        ->update([
                            'annual_leave_use' => $total,
                            'annual_leave_bal' => $total_annual_leave - $total,
                        ]);
                }

                if($leave_id == 5)
                {
                    EmployeeLeaveTotal::where('emp_id', $emp_id)
                        ->where('leave_year', $leave_year)
                        ->update([
                            'unpaid_leave_use' => $total,
                            'unpaid_leave_bal' => $total_unpaid_leave - $total,
                        ]);
                }

                if($leave_id == 6)
                {
                    EmployeeLeaveTotal::where('emp_id', $emp_id)
                        ->where('leave_year', $leave_year)
                        ->update([
                            'other_leave_use' => $total,
                            'other_leave_bal' => $total_other_leave - $total,
                        ]);
                }

            }

            EmpLeaveDetail::where('emp_leave_id', $id)->delete();

            if(is_array($date_range)){
                if(count($date_range) > 0){
                    foreach ($date_range as $k => $v){

                        $m = new EmpLeaveDetail();
                        $m->emp_id = $emp_id;
                        $m->emp_leave_id = $emp_leave->id;
                        $m->leave_date = $date_range[$k];
                        $m->leave_type = $leave_id;
                        $m->save();

                    }
                }
            }

            return redirect('take-leave')->with('success', 'Update successful!');
        }catch(\Exception $ex){
            return back()->withErrors($ex->getMessage())->withInput();
        }
    }

    public function destroy($id)
    {

    }
    function delete($id)
    {
        EmpLeave::find($id)->empLeave_detail()->delete();
        EmpLeave::find($id)->delete();
        return redirect('take-leave')->with('success','Employee leave is successfully deleted');
    }


    public function get_take_leave_form($id)
    {
        $take_leave = EmpLeave::findOrFail($id);
        return view('hr.take-leave.form-take-leave', compact('take_leave'));
    }

    public function change_status(Request $request)
    {
        $id         = $request->id;
        $status     = $request->status;
        EmpLeave::where('id', $id)->update(['review' => $status]);
        return redirect('take-leave')->with('success','Employee Leave is change successfully');
    }

    public function delete_take_leave(Request $request)
    {
        $id = $request->delete_id;
        EmpLeave::where('id', $id)->delete();
        return redirect('take-leave')->with('success','Employee Leave is change successfully');
    }


    //deduct money
    public function deduct_money(Request $request)
    {
        $id             = $request->ids;
        $deduct         = $request->deduct;
        //$deduct         = AbsentPolicyModel::where('id', $deduct_id)->first();
        EmpLeave::where('id', $id)->update(['deduct' => $deduct, 'approve' => 1]);
        //EmpLeaveDetail::where('emp_leave_id',$id)->update(['deduct' => $deduct]);
        return redirect('take-leave')->with('success', 'Employee updated successfully');
    }
}
