<?php

namespace App\Model\Hr;

use App\Model\Hr\Employee;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class EmpLeaveDetail extends Model
{
    protected $table = 'emp_leave_details';


    function getTotalLeaveAttribute()
    {
        return "{$this->is_half} day";
    }
    public function emp_leave()
    {
        return $this->belongsTo('App\Models\EmpLeave', 'emp_leave_id');
    }

    public function employee()
    {
        return $this->belongsTo('App\Models\Employee', 'emp_id');
    }

    public static function getEmp($request)
    {

        $from_date = $request->from_date;
        $to_date = $request->to_date;

        $emp_id = $request->emp_id;

        $em = Employee::where(function ($q) use ($from_date, $to_date) {

            })
            ->where(function ($q) use ($emp_id) {
                if (is_array($emp_id)) {
                    if (count($emp_id) > 0) {
                        $q->whereIn('id', $emp_id);
                    }
                } else {
                    $q->where('id', $emp_id);
                }
            })->get();

        $id = [];
        if (count($em) > 0) {
            foreach ($em as $row) {
                $id[] = $row->id;
            }

        }
      //  dd($request->all(),$em, $emp_id);

        return ['em_id' => $id, 'rows' => $em];
    }


    public static function getLeaveByType($emp_id)
    {
        $m = null;
        if (is_array($emp_id)) {
            if (count($emp_id) > 0) {
                $m = self::select(DB::raw('emp_id,leave_type,sum(day_num) as t_day_num'))
                    ->whereIn('emp_id', $emp_id)
                    ->groupBy(DB::raw('emp_id,leave_type'))
                    ->get();
            }
        } else {
            $m = self::select(DB::raw('emp_id,leave_type,sum(day_num) as t_day_num'))
                    ->where('emp_id', $emp_id)
                    ->groupBy(DB::raw('emp_id,leave_type'))
                    ->get();
        }

        return $m;
    }

    public static function getLeaveByType_($emp_id)
    {
        $y = Carbon::now()->format('Y');
        $m_y = Carbon::now()->format('Y-m-d');

        $m = self::select(DB::raw('emp_id,leave_type,leave_date,sum(day_num) as t_day_num'))
            ->where('emp_id', $emp_id)
            ->whereDate('leave_date', '<=', $m_y)
            ->whereYear('leave_date', '=', $y)
            ->groupBy(DB::raw('emp_id,leave_type'))
            ->get();

        return $m;
    }

    public static function getAnnualLeaveByMonth($emp_id, $date)
    {
        $annual_leave_by_month = EmpLeaveDetail::where('emp_id', $emp_id)
            ->where(DB::raw("DATE_FORMAT(leave_date ,'%Y/%m')"), $date)
            ->where('leave_type', "annual_leave")
            ->select(DB::raw('SUM(day_num) as num_leave'))
            ->first();
        return $annual_leave_by_month?$annual_leave_by_month:0;
    }


}
