<?php

namespace App\Model\Hr;

use App\Helpers\dev1776_;
use App\Helpers\Helper;
use App\Model\setup\BranchModel;
use App\Model\setup\MemberTypeModel;
use function GuzzleHttp\Promise\all;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;


class EmpLeave extends Model
{

    /*
    |--------------------------------------------------------------------------
    | GLOBAL VARIABLES
    |--------------------------------------------------------------------------
    */

    protected $table = 'emp_leaves';
    // protected $primaryKey = 'id';
    // public $timestamps = false;
    // protected $guarded = ['id'];
    protected $fillable = ['emp_id', 'leave_type', 'from_date', 'to_date',
        'request_date', 'reason', 'approve', 'review', 'review_by', 'approve_by', 'request_to',
        'attach_document', 'hr_approve_id', 'num_take_leave' . 'reason'
    ];

    // protected $hidden = [];
    protected $dates = ['from_date', 'to_date', 'request_date'];

    // declare column to array
    protected $casts = [
        'attach_document' => 'array',
    ];

    /*
    |--------------------------------------------------------------------------
    | FUNCTIONS
    |--------------------------------------------------------------------------
    */
    public function getShowUpdateAttribute()
    {

        $review = $this->attributes['review'];
        $approve = $this->attributes['approve'];


        if ($review == 1 && $approve == 1) {

            return true;
        }
        return null;
    }

    function getTotalLeaveAttribute()
    {
        return "{$this->num_take_leave} day(s)";
    }


    /*
    |--------------------------------------------------------------------------
    | RELATIONS
    |--------------------------------------------------------------------------
    */

    public function request_to()
    {
        return $this->belongsTo(Employee::class, 'request_to');
    }

    public function employee()
    {
        return $this->belongsTo(Employee::class, 'emp_id');
    }

    public function empLeave_detail()
    {
        return $this->hasMany('App\Models\EmpLeaveDetail', 'emp_leave_id');
    }

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

    function leave_type()
    {
        return $this->belongsTo(LeaveType::class, 'leave_type');
    }

    function leave_typee()
    {
        return $this->belongsTo(LeaveType::class, 'leave_type');
    }

    public function get_branch_employee()
    {
        return $this->belongsTo(BranchModel::class, 'branch_id');
    }
    public function get_department_employee()
    {
        return $this->belongsTo(HrDepartmentModel::class, 'department_id');
    }
    public function get_position_employee()
    {
        return $this->belongsTo(HrPositionModel::class, 'position_id');
    }
    /*
    |--------------------------------------------------------------------------
    | SCOPES
    |--------------------------------------------------------------------------
    */

    /*
    |--------------------------------------------------------------------------
    | ACCESORS
    |--------------------------------------------------------------------------
    */

    /*
    |--------------------------------------------------------------------------
    | MUTATORS
    |--------------------------------------------------------------------------
    */



    public function setAttachDocumentAttribute($value)
    {
        $attribute_name = "attach_document";
        $disk = "uploads";
        $destination_path = "document_leave";

        $this->uploadMultipleFilesToDisk($value, $attribute_name, $disk, $destination_path);
    }

    public static function boot()
    {
        parent::boot();
        static::deleting(function ($obj) {
            if (count((array)$obj->attach_document) && $obj->forceDeleting === true) {
                foreach ($obj->attach_document as $file_path) {
                    Storage::disk('uploads/document_leave')->delete($file_path);
                }
            }
        });

    }

    public static function saveDetail($eid = null, $r = null)
    {
        $from_date      = date('Y-m-d', strtotime($r->from_date));
        $to_date        = date('Y-m-d', strtotime($r->to_date));
        $emp_id         = $r->select2_ajax_emp_id;
        $request_date   = date('Y-m-d', strtotime($r->request_date));
        $leave_type     = $r->leave_type;
        $request_to     = $r->request_to;
        $reason         = $r->reason;
        $m = null;
        if ($eid != null) {
            $m = EmpLeave::find($eid);
        }
        if ($m == null) {
            $m = new EmpLeave();
        }
        $m->from_date       = $from_date;
        $m->to_date         = $to_date;
        $m->emp_id          = $emp_id;
        $m->request_date    = $request_date;
        $m->leave_type      = $leave_type;
        $m->request_to      = $request_to;
        $m->reason          = $reason;

        $createDateRange = /*IDate::createDateRange($from_date, $to_date);*/
            dev1776_::DatePeriod($from_date, $to_date);
        $m->num_take_leave = $from_date == $to_date ? 1 : count($createDateRange) + 1;
        if ($m->save()) {
            EmpLeaveDetail::where('emp_leave_id', $eid)->delete();
            if (is_array($createDateRange)) {
                if (count($createDateRange) > 0) {
                    foreach ($createDateRange as $k => $value) {
                        $t = New EmpLeaveDetail();

                        $t->emp_leave_id    = $m->id;
                        $t->emp_id          = $emp_id;
                        $t->leave_date      = $value;
                        $t->save();
                    }
                }
            }
            self::authorize($eid, $r);
        }
    }

    public static function authorize($id, $r)
    {
        $authorize = $r->authorize;
        $m = EmpLeave::find($id);
        if ($m != null) {
            if ($authorize != null) {
                $m->approve = $authorize > 0 ? 1 : 0;
            } else {
                $m->approve = 0;
            }
            $m->save();
        }
    }

    public static function getTotalAuthorizeTakeLeaveOfEmployeeByIdType($emp_id = null, $leave_type_id = null, $leave_type_name = null)
    {
        if ($emp_id && $leave_type_id) {
            return self::where(function ($q) use ($emp_id, $leave_type_id) {
                if (!is_array($emp_id) && !is_array($leave_type_id)) {
                    $q->where('emp_id', $emp_id)->where('leave_type', $leave_type_id);
                }
            })->where('review', 1)->where('approve', 1)->sum('num_take_leave');
        }
        return null;
    }
    public static function getTotalTakeLeaveOfEmployeeByIdType($emp_id = null, $leave_type_id = null, $leave_type_name = null)
    {
        if ($emp_id && $leave_type_id) {
            return self::where(function ($q) use ($emp_id, $leave_type_id) {
                if (!is_array($emp_id) && !is_array($leave_type_id)) {
                    $q->where('emp_id', $emp_id)->where('leave_type', $leave_type_id);
                }
            })->sum('num_take_leave');
        }
        return null;
    }


    Public static function saveReview($take_leave_id = null)
    {
        if ($take_leave_id) {
            $m = self::find($take_leave_id);
            $m->review = 1;
            $m->save();
        }
    }

    public static function getLeaveByMonth($emp_id, $end_date, $y)
    {
        $all_date       = self::getTotalMonth("$y/01/01", $end_date);
        $leave          = 0;
        $total_leave    = 0;
        $getYearLeave   = self::getLeaveTotal($emp_id, $y);
        if ($all_date > 0) {
            $i = 0;

            for ($kk = 1; $kk <= $all_date; $kk++) {

                $i++;
                $total_ = 0;
                if ($i < 10) {
                    $i = "0$i";
                }
                $leaves = EmpLeaveDetail::where('emp_id', $emp_id)
                                        ->where(DB::raw("DATE_FORMAT(leave_date ,'%Y/%m')"), "$y/$i")
                                        ->where('leave_type', "4")
                                        ->select(DB::raw('SUM(day_num) as num_leave'))
                                        ->first();

                if ($i == 01) {
                    if ($getYearLeave != null) {
                        $getYearLeave = $getYearLeave->annual_leave > 18 ? $getYearLeave->annual_leave - 18 : 0;
                    }
                }
                if ($i > 01) {
                    if ($getYearLeave > 0) {
                        $total_leave = $total_leave - $getYearLeave;
                    }
                }
                if ($leaves != null) {
                    $leave = $leaves->num_leave;
                    if ($leave > 0) {
                        $total_ = 1.5 + $getYearLeave - $leave;
                    } else {
                        $total_ = 1.5 + $getYearLeave;
                    }
                    $total_leave = $total_leave + $total_;
                }
            }
        }
        return $total_leave > 0 ? $total_leave : 0;
    }

    public static function getTotalMonth($from_date, $to_date)
    {
        // SELECT TIMESTAMPDIFF(MONTH, '2015-12-20', '2015-12-25') + 1 as t_m
        $sql = "SELECT TIMESTAMPDIFF(MONTH,'{$from_date}','{$to_date}') + 1 as d";
        $d = DB::select($sql);
        if (count($d) > 0) {
            return $d[0]->d;
        } else {
            return null;
        }
    }
    public static function getLeaveTotal($emp_id, $year)
    {
        $leaveTotal = DB::table('emp_leave_total')
            ->select('*')
            ->where('emp_id', $emp_id)
            ->where('leave_year', $year)
            ->first();
        return $leaveTotal ? $leaveTotal : 0;
    }




}
