<?php

namespace App\Models;

use App\Helpers\dev1776_;
use App\Helpers\Helper;
use App\Helpers\IDate;
use function GuzzleHttp\Promise\all;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;

/**
 * App\Models\EmpLeave
 *
 * @property int $id
 * @property int|null $emp_id
 * @property string|null $leave_type
 * @property \Carbon\Carbon|null $from_date
 * @property \Carbon\Carbon|null $to_date
 * @property \Carbon\Carbon|null $request_date
 * @property string|null $reason
 * @property int|null $approve
 * @property \Carbon\Carbon|null $created_at
 * @property \Carbon\Carbon|null $updated_at
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\EmpLeaveDetail[] $empLeave_detail
 * @property-read \App\Models\Employee|null $employee
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\EmpLeave whereApprove($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\EmpLeave whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\EmpLeave whereEmpId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\EmpLeave whereFromDate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\EmpLeave whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\EmpLeave whereLeaveType($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\EmpLeave whereReason($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\EmpLeave whereRequestDate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\EmpLeave whereToDate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\EmpLeave whereUpdatedAt($value)
 * @mixin \Eloquent
 * @property int|null $review
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\EmpLeave whereReview($value)
 */
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'];
    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');
    }
    /*
    |--------------------------------------------------------------------------
    | SCOPES
    |--------------------------------------------------------------------------
    */

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

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

    public function addButtonCustom()
    {
        $mm = self::find($this->id);

        if ($mm->approve == 1) {

            return '

              <a   href="' . url("admin/emp-leave-approve/do-approve-cancel?id=" . $this->id) . '" class="btn btn-xs btn-danger">Cancel</a>
              <!--<a   href="' . url("report/take-leave-request-form?id=" . $this->id) . '" class="btn btn-xs  btn-info">View</a>-->
              <a   href="' . url("report/take-leave-request-form?id=" . $this->id) . '"target="_blank" class="btn btn-xs  btn-info aa">View</a>
                ';
        } else {
            return '
               <a   href="' . url("admin/emp-leave-approve/do-approve?id=" . $this->id) . '" class="btn btn-xs btn-primary">Approve</a>
               <!--<a   href="' . url("report/take-leave-request-form?id=" . $this->id) . '"  class="btn btn-xs btn-info">View</a>-->
               <a   href="' . url("report/take-leave-request-form?id=" . $this->id) . '" target="_blank" class="btn btn-xs  btn-info">View</a>
                ';
        }

    }

    public function viewForm()
    {
        return '<a   href="' . url("report/take-leave-request-form?id=" . $this->id) . '"target="_blank" class="btn btn-xs  btn-info">View</a> ';

    }

    public function addButtonCustomReview()
    {
        $mm = self::find($this->id);
        if ($mm->review == 1) {
            return '

                    <a href="' . url("admin/emp-leave-review/do-approve-cancel?id=" . $this->id) . '" class="btn btn-xs btn-danger">Cancel</a>
                ';
        } else {
            return '
                    <a href="' . url("admin/emp-leave-review/do-approve?id=" . $this->id) . '" class="btn btn-xs btn-primary">Review</a>
                ';
        }


    }


    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);
                }
            }
        });


//        if (!_can('list-role')) {
//
//            static::addGlobalScope('emp_id', function (Builder $builder) {
//                // $builder->where('request_to', auth()->user()->id);
//                $builder->where('emp_id', auth()->user()->id)->orWhere('request_to', auth()->user()->id);
//            });
//        }


    }

    public function addButtonCustomHRM()
    {

        $mm = self::find($this->id);
        if ($mm->approve == 1) {
            return '

              <a target="_blank" href="' . url("hrm/take-leave-request-form?id=" . $this->id) . '" class="btn btn-xs  btn-info">View</a>
                ';
        } else {
            return '
               <a target="_blank"  href="' . url("hrm/take-leave-request-form?id=" . $this->id) . '" class="btn btn-xs btn-info">View</a>
                ';
        }
    }

    public function addButtonCustomReviewHRM()
    {

        $mm = self::find($this->id);
        if ($mm->review == 1) {
            return '
                    <a href="' . url("hrm/emp-leave-review/do-approve-cancel?id=" . $this->id) . '" class="btn btn-xs btn-danger">Cancel</a>
                      <a target="_blank" href="' . url("hrm/take-leave-request-form?id=" . $this->id) . '" class="btn btn-xs  btn-info">View</a>
                ';
        } else {
            return '
                    <a href="' . url("hrm/emp-leave-review/do-approve?id=" . $this->id) . '" class="btn btn-xs btn-primary">Review</a>
                    <a target="_blank" href="' . url("hrm/take-leave-request-form?id=" . $this->id) . '" class="btn btn-xs  btn-info">View</a>
                ';
        }
    }

    public function addButtonCustomApprove()
    {

        $mm = self::find($this->id);
        if ($mm->approve == 1) {
            return '
                    <a href="' . url("hrm/emp-leave-approve/do-approve-cancel?id=" . $this->id) . '" class="btn btn-xs btn-danger">Cancel</a>
                      <a target="_blank" href="' . url("hrm/take-leave-request-form?id=" . $this->id) . '" class="btn btn-xs  btn-info">View</a>
                ';
        } else {
            return '
                    <a href="' . url("hrm/emp-leave-approve/do-approve?id=" . $this->id) . '" class="btn btn-xs btn-primary">Approved</a>
                    <a target="_blank" href="' . url("hrm/take-leave-request-form?id=" . $this->id) . '" class="btn btn-xs  btn-info">View</a>
                ';
        }
    }


    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()) {
            // dd($m->id);
            EmpLeaveDetail::where('emp_leave_id', $eid)->delete();
            if (is_array($createDateRange)) {
                if (count($createDateRange) > 0) {
                    foreach ($createDateRange as $k => $value) {
                        $t = New EmpLeaveDetail();
                        //dd($eid);
                        $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();
        }
    }


}
