<?php

namespace App\Http\Controllers\HR;

use App\Model\Hr\EmployeeLeaveTotal;
use App\Model\Hr\EmployeeLeaveTotalDetail;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Hr\Employee;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Facades\Gate;

class LeaveTotalController extends Controller
{

    function __construct()
    {
      $this->middleware('permission:Total Leave  List', ['only' => ['index']]);
      $this->middleware('permission:Total Leave  Edit', ['only' => ['edit','update']]);
      $this->middleware('permission:Take Leave Approve', ['only' => ['change_status']]);
      $this->middleware('permission:Take Leave Show', ['only' => ['review']]);
    }
    public function index(Request $request)
    {
        $search         = $request->input('search.value');
        if ($request->ajax()) {

            $count_total    = EmployeeLeaveTotal::count();
            $data           = EmployeeLeaveTotal::select('emp_leave_total.*','users.name')
                            ->join('users', 'users.id', 'emp_leave_total.emp_id')
                            ->where(function ($q) use ($search){
                                $q->orWhere('users.name', 'LIKE', "%$search%");
                            })
                            ->orderBy('leave_year','DESC');
            $count_filter   = $data->count();

            return Datatables::of($data->take(20))
                ->addIndexColumn()
                ->with([
                    'recordsTotal' => $count_total,
                    'recordsFiltered' => $count_filter
                ])
                ->addColumn('employee', function($data){
                    return optional($data->employee)->name;
                })
                ->addColumn('action', function ($data) {
                    if (Gate::check('Total Leave  Edit')) {
                        $btn_edit = '<a href="'.route('leave-total.edit', $data->id).'" class="button_warning" title="edit"><span class="fa fa-pencil-square-o"></span></a>';
                    }else{
                        $btn_edit = '';
                    }
                    return $btn_edit;
                })
                ->rawColumns(['action' => 'action'])
                ->make(true);
        }

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

    public function create()
    {
        //
    }

    public function store(Request $request)
    {
        //
    }

    public function show($id)
    {
        //
    }

    public function edit($id)
    {
        $data       = EmployeeLeaveTotal::findOrFail($id);
        $emp        = User::where('status', 1)->pluck('name','id');

        return view('hr.total-leave.edit', compact('data', 'emp'));
    }

    public function update(Request $request, $id)
    {
        EmployeeLeaveTotal::where('id', $id)->update([
            'special_leave'     => $request->special_leave,
            'sick_leave'        => $request->sick_leave,
            'maternity_leave'   => $request->maternity_leave,
            'annual_leave'      => $request->annual_leave,
            'unpaid_leave'      => $request->unpaid_leave,
        ]);

        return redirect()->route('leave-total.index')->with('success', 'Updated Successful!...');
    }

    public function destroy($id)
    {
        //
    }

    function generate(){
        $c_year     = date("Y");
        $c_month    = date("m");
        $c_day      = date("d");

        $emp = User::selectRaw('id, joined_date as effect_d,
                                YEAR(joined_date) as y,
                                MONTH(joined_date) as m, DAY(joined_date) as d,
                                DATEDIFF( NOW(),joined_date) as t_day')
                                ->get();

        foreach ($emp as $row) {
            $k = 0;
            $m = $row->m;
            $d = $row->d;
            $y = $row->y;

            if ($y > 0) {
                if ($y > 0 || $y >= 2001) {
                    for ($i = $y; $i <= $c_year; $i++) {
                        /*================ process save =============*/
                        $d          = null;
                        $sick       = 0;
                        $special    = 0;
                        $unpaid     = 0;
                        $annual     = 0;
                        $other      = 0;
                        $mat        = 0;
                        $d = EmployeeLeaveTotalDetail::/*where('leave_year', $i) ->*/
                            selectRaw('sum(special_leave) as special,
                                    sum(sick_leave) as sick,
                                    sum(maternity_leave) as mat,
                                    sum(annual_leave) as annual,
                                    sum(unpaid_leave) as  un,
                                    sum(other_leave) other')
                            ->where('emp_id', $row->id)->first();

                        $sick       = $d->sick;
                        $special    = $d->special;
                        $other      = $d->other;
                        $annual     = $d->annual;
                        $mat        = $d->mat;
                        $unpaid     = $d->un;

                        $m = EmployeeLeaveTotal::where('emp_id', $row->id)
                                        ->where('leave_year', $i)
                                        ->first();
                        if ($m == null) {
                            $m = new EmployeeLeaveTotal();
                        }
                        if ($m != null && $i != $m->leave_year) {

                            $special_leave      = 5 + $special;
                            $sick_leave         = 60 + $sick;
                            $maternity_leave    = 90 + $mat;
                            $annual_leave       = 18 + $annual;
                            $unpaid_leave       = 180 + $unpaid;
                            $other_leave        = 180 + $other;

                            $m->emp_id          = $row->id;
                            $m->leave_year      = $i;
                            $m->special_leave   = $special_leave;
                            $m->sick_leave      = $sick_leave;
                            $m->maternity_leave = $maternity_leave;
                            $m->annual_leave    = $annual_leave;
                            $m->unpaid_leave    = $unpaid_leave;
                            $m->other_leave     = $other_leave;
                            $m->save();
                        }
                    }
                }
            }
        }
        return redirect()->back()->with(['success'=>'Success Generate Leave Total']);

    }

}
