<?php

namespace App\Http\Controllers\HR;

use App\Fun\Fun;
use App\Helpers\IDate;
use App\Helpers\ITime;
use App\Helpers\IString;
use App\Model\Hr\HrOvertimeRequestModel;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Facades\Gate;

class HrOvertimeRequestController extends Controller
{

    function __construct()
    {
       $this->middleware('permission:Overtime List', ['only' => ['index', 'get_overtime']]);
       $this->middleware('permission:Overtime Create', ['only' => ['create','store']]);
       $this->middleware('permission:Overtime Show', ['only' => ['view_overtime']]);
       $this->middleware('permission:Overtime Edit', ['only' => ['edit','update']]);
       $this->middleware('permission:Overtime Approve', ['only' => ['overtime_status']]);
    }
    public function index()
    {
        return view('hr.overtime-request.index');
    }
    public function get_overtime()
    {
        $count_total    = HrOvertimeRequestModel::count();
        $count_filter   = HrOvertimeRequestModel::count();
        $data           = HrOvertimeRequestModel::orderBy('id', 'DESC')->get();
        return DataTables::of($data)
            ->addIndexColumn()
            ->with([
                'recordsTotal' => $count_total,
                'recordsFiltered' => $count_filter
            ])
            ->addColumn('action', function ($data) {
                $check_language = Fun::lang();
                if ($check_language == 'km') {
                    $edit = "កែសម្រួល";
                    $view = "បង្ហាញ";
                    $delete = "លុបចោល";
                } else {
                    $edit = "Edit";
                    $view = "View";
                    $delete = "Delete";
                }
                $bedit = '';
                $bview  = "";
                $bdelete = "";
                if(Gate::check('Overtime Edit')) {
                    if ($data->status == 0) {
                        $bedit .= '<a href="' . route('hr-overtime-request.edit', encrypt($data->id)) . '" class="button_warning"><span class="fa fa-pencil-square-o"></span></a>';
                    }
                }
                if(Gate::check('Overtime Show')) {
                    $bview .= '<a class="button_success viewot" role="button" data-id="' . $data->id . '" data-toggle="modal tooltip" data-target="#viewModal" data-placement="top" title="' . $view . '"><span class="fa fa-eye"></span></a>';
                }
                if(Gate::check('Overtime Delete')) {
                    $bdelete .= '<a class="button_danger delete-overtime" role="button" data-id="' . $data->id . '" data-toggle="modal tooltip" data-target="" title="' . $delete . '"><span class="fa fa-trash"></span></a>';
                }
                return  $bview.$bedit.$bdelete;
            })
            ->editColumn('status', function ($data) {
                $status = '';
                $label = '';
                $check_language = Fun::lang();
                if ($check_language == 'km') {
                    $pending = "រង់ចាំ";
                    $approve = "ទទួលយកសំណើរ";
                    $reject = "បដិសេធសំណើរ";
                } else {
                    $pending = "Pending";
                    $reject = "Rejected";
                    $approve = "Approved";
                }
                if($data->status == 0){
                    $status = $pending;
                    $label = 'warning';
                }
                if($data->status == 1){
                    $status = $approve;
                    $label = 'success';
                }
                if($data->status == 2){
                    $status = $reject;
                    $label = 'danger';
                }
                return ' <a class="viewPopLink label label-'.$label.'" role="button" data-id="' . $data->id . '" data-status="' . $data->status . '"  data-toggle="modal tooltip" data-target="#myModal" data-placement="top" title="'.$status.'">'.$status.'</a>';

            })
            ->editColumn('emp_id', function ($data) {
                return optional($data->employee)->name;
            })
            ->editColumn('ot_date' , function ($data){
                return $data->date ? date('d-m-Y', strtotime($data->date)) : "";
            })
            ->editColumn('start', function ($data) {
                return $data->start ? $data->start : "";
            })
            ->editColumn('end', function ($data) {
                return $data->end ? $data->end : "";
            })
            ->editColumn('total_hour', function($data){
                return $data->total_hour ? $data->total_hour." h" : "";
            })
            ->editColumn('ot_rate', function($data){
                return $data->ot_rate ? ($data->ot_rate * 100)." %" : "";
            })

            ->editColumn('ot_type', function($data){
                return $data->ot_type ? IString::getUpperCaseCharacter($data->ot_type) : "";
            })
            ->rawColumns(['action' => 'action', 'status' => 'status'])
            ->make(true);
    }
    public function create()
    {
        $employee = User::where('status',1)->pluck('name','id');
        return view('hr.overtime-request.create',compact('employee'));
    }
    public function store(Request $request)
    {

        $this->validate($request,[
            'emp_id'        => 'required',
            'project'       => 'required',
            'date'          => 'required',
            'ot_rate'       => 'required',
            'ot_type'       => 'required'
        ]);
        try{
            $ot             = new HrOvertimeRequestModel();
            $ot->emp_id     = $request->emp_id;
            $ot->project    = $request->project;
            $ot->date       = date('Y-m-d',strtotime($request->date));
            $ot->note       = $request->note;
            $ot->reason     = $request->reason;

            $t_start        = $request->time_in;
            $t_end          = $request->time_out;
            $ot->start      = $t_start;
            $ot->end        = $t_end;

            $ot->hours      = $request->hour;
            $ot->ot_rate    = $request->ot_rate;
            $ot->ot_type    = $request->ot_type;

            //calculate time in & time out
            $t_in   = date("H:i:s", strtotime($t_start));
            $t_out  = date("H:i:s", strtotime($t_end));
            $total_hour = round((ITime::getTimeDiffMinute($t_in, $t_out)) / 60, 2);
            if($total_hour < 0){
                $ot->total_hour = (24 + $total_hour);
            }else{
                $ot->total_hour = $total_hour;
            }

            $ot->save();

            return redirect()->route('hr-overtime-request.index')->with('success','Overtime request was submit successful...');
        }catch(\Exception $ex){
            return back()->withErrors($ex->getMessage())->withErrors();
        }
    }
    public function show($id)
    {
        //
    }
    public function edit($id)
    {
        $overtime       = HrOvertimeRequestModel::find(decrypt($id));
        $employee       = User::where('status',1)->pluck('name','id');
        $start[]        = explode(':',$overtime->start);
        $end[]          = explode(':',$overtime->end);
        $ot_type        = $overtime->ot_type;
        $ot_rate        = $overtime->ot_rate;
        $hour           = $overtime->hours;

        return view('hr.overtime-request.edit',compact('overtime','employee','start','end','ot_type','ot_rate','hour'));
    }
    public function update(Request $request, $id)
    {
        $this->validate($request,[
            'emp_id'    =>'required',
            'project'   =>'required',
            'date'      =>'required',
        ]);
        try{
            $ot             = HrOvertimeRequestModel::find($id);
            $ot->emp_id     = $request->emp_id;
            $ot->project    = $request->project;
            $ot->date       = date('Y-m-d',strtotime($request->date));
            $ot->note       = $request->note;
            $ot->reason     = $request->reason;

            $t_start        = $request->start;
            $t_end          = $request->end;
            $ot->start      = $t_start;
            $ot->end        = $t_end;
            $ot->hours      = $request->hours;

            //calculate time in & time out
            $t_in           = date("H:i:s", strtotime($t_start));
            $t_out          = date("H:i:s", strtotime($t_end));
            $total_hour     = round((ITime::getTimeDiffMinute($t_in, $t_out)) / 60, 2);
            if($total_hour < 0){
                $ot->total_hour = (24 + $total_hour);
            }else{
                $ot->total_hour = $total_hour;
            }

            $ot->update();

            return redirect()->route('hr-overtime-request.index')->with('success','Overtime request was updated successful...');
        }catch(\Exception $ex){
            return back()->withErrors($ex->getMessage())->withInput();
        }
    }
    public function destroy($id)
    {
        //
    }
    public function view_overtime(){
        $overtime = HrOvertimeRequestModel::find($_GET['id']);
        $employee = optional($overtime->employee);
        $status = '';
        $check_language = Fun::lang();
        if ($check_language == 'km') {
            $pending = "រង់ចាំ";
            $approve = "ទទួលយកសំណើរ";
            $reject = "បដិសេធសំណើរ";
        } else {
            $pending = "Pending";
            $reject = "Rejected";
            $approve = "Approved";
        }

        if($overtime->status == 1)
        {
            $status = '<span class="label label-success">'.$approve.'</span>';
        }

        if($overtime->status == 0)
        {
            $status = '<span class="label label-warning">'.$pending.'</span>';
        }

        if($overtime->status == 2)
        {
            $status = '<span class="label label-danger">'.$reject.'</span>';
        }
        $start          = substr_replace($overtime->start,' ',5,1);
        $end            = substr_replace($overtime->end,' ',5,1);
        $data = [
            'employee'  =>$employee->name,
            'project'   =>$overtime->project,
            'dates'     =>$overtime->date,
            'starts'    =>$start,
            'ends'      =>$end,
            'note'      =>$overtime->note,
            'statuss'   =>$status,
        ];

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

    public function overtime_status(Request $request)
    {
        $id                 = $_GET['id'];
        $overtime           = HrOvertimeRequestModel::find($id);
        $overtime->status   = $request->status;
        $overtime->update();
        return redirect()->route('hr-overtime-request.index')->with('success', 'Overtime status was changed ...');
    }

    //delete overtime
    public function delete_overtime(Request $request)
    {
        $id = $request->delete_id;
        HrOvertimeRequestModel::where('id', $id)->delete();

        return redirect()->route('hr-overtime-request.index')->with('success', 'Deleted Successful!.');
    }
}
