<?php

namespace App\Modules\Hr;

use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use App\Models\ValidationModel;
use App\Modules\Hr\Employee;
use App\Models\User;

class Holiday extends ValidationModel
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'hr_holidays';

    /**
     * The number of models to return for pagination.
     *
     * @var int
     */
    protected $perPage = 50;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['user_id', 'description', 'start_date', 'end_date', 'paid', 'status'];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['title', 'start', 'end'];

    /**
     * The "booting" method of the model.
     *
     * @return void
     */
    public static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (! $model->user_id) {
                $model->user_id = Auth::user()->id;
            }
            $model->ip_address = Request::getClientIp();
            $model->created_by = Auth::user()->id;
            $model->updated_by = Auth::user()->id;

            // Calculate total days
//            $model->total_days = Carbon::parse($model->start_date)->diffInDays(Carbon::parse($model->end_date)) + 1;
            
            $myStartDate = Carbon::parse($model->start_date);
            $myEndDate = Carbon::parse($model->end_date);
            
            $totalDays = $myStartDate->diffInDays($myEndDate);
            $model->total_days = $myStartDate->diffInDays($myEndDate);
                
            $totalHolidays = 0;
            $totalDaysRequested = 0;
            
            while($myStartDate <= $myEndDate)
            {
                if($myStartDate->isWeekday()) 
                {
                    $totalHolidays++;
                }
                $myStartDate->addDay();
                $totalDaysRequested ++;
            }
            
//            $model->total_days = $myStartDate->diffInDaysFiltered(function (Carbon $date) {
//                return $date->isWeekend();
//            }, $myEndDate);
            
            $model->total_days = $totalHolidays;
            
        });

        static::updating(function ($model) {
            $model->updated_by = Auth::user()->id;
        });
    }

    /**
     * Returns the title that will be displayed in the calendar.
     *
     * @return string
     */
    public function getTitleAttribute()
    {
        return $this->user->name.': '.$this->description.'  -> [Ends: '.Carbon::parse($this->attributes['end_date'])->format('d/m/Y').']';
    }

    /**
     * Formats the start date to be recognizable by the fullCalendar plugin.
     *
     * @return string
     */
    public function getStartAttribute()
    {
        return $this->attributes['start_date'];
    }

    /**
     * Formats the end date to be recognizable by the fullCalendar plugin.
     *
     * @return string
     */
    public function getEndAttribute()
    {
        return $this->attributes['end_date'];
    }

    /**
     * Defines the relationship with the user model.
     *
     * @return \User
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * Restrict the query to a given time interval.
     *
     * @param  \Illuminate\Database\Query\Builder $query
     * @param  int 	$startDate
     * @param  int 	$endDate
     *
     * @return \Illuminate\Database\Query\Builder
     */
    public function scopePeriod($query, $startDate = null, $endDate = null)
    {
        $startDate = (! $startDate) ? Carbon::now()->subMonths(1)->day(28)->hour(0)->minute(0)->second(0)->toDateTimeString() : Carbon::createFromTimeStamp($startDate)->toDateTimeString();
        $endDate = (! $endDate) ?  Carbon::now()->day(27)->hour(0)->minute(0)->second(0)->toDateTimeString() : Carbon::createFromTimeStamp($endDate)->toDateTimeString();

        return $query->where('start_date', '>=', $startDate)->where('start_date', '<=', $endDate);
    }

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