<?php
class Activity extends BaseModel
{
	protected $guarded = array();

	public static $rules = array(
		'name' => 'required',
		'description' => 'required',
		'starts_at' => 'required',
		'ends_at' => 'required',
		'con_event_id' => 'required',
        'capacity' => 'required|integer|min:0',
	);

    public function event()
    {
        return $this->belongsTo('ConEvent', 'con_event_id');
    }

    public function category()
    {
        return $this->belongsTo('ActivityCategory', 'activity_category_id');
    }

    public function room()
    {
        return $this->belongsTo('Room');
    }

    public function participants()
    {
        // $participants = $this->belongsToMany('User')->with('host')->get();
        // return $this->belongsToMany('User')->withPivot('host');
        return $participants = $this->belongsToMany('User');
    }

    public function hosts()
    {
        return $this->belongsToMany('User')->withPivot('host');
    }

    public function getDuration($human = true)
    {
        $diff = $this->starts_at->diffInMinutes($this->ends_at);
        if ($diff % 15 !== 0) {
            // $diff = round($diff/10)*10;
            $diff = ceil($diff / 15)*15;
            // dd($diff);
        }
        if (!$human) {
            return $diff;
        }
        $readable = array();
        if ($diff >= 60) {
            $readable[] = floor($diff / 60) . 'h';
        }
        if ($diff % 60) {
            $readable[] = $diff % 60 . 'min';
        }

        return implode(' ', $readable);
    }
    public function getRoomName()
    {
        if ($this->all_rooms)
        {
            $room_name = strtolower(Lang::get('labels.all_rooms'));
        }
        elseif($this->room)
        {
            $room_name = $this->room->name;
        }
        else
        {
            $room_name = '';
        }
        return $room_name;
    }

    public function signupCapacity()
    {
        return floor($this->event->signup_limit * $this->capacity);
    }


    public function getPlacesLeft()
    {
        return $this->capacity - $this->participants->count();
    }
    public function hasPlacesLeft()
    {
        return $this->signupCapacity() - $this->participants->count();
    }

    static function getForDate($date, $event)
    {
        $activities = Activity::where('starts_at', '>=', $date->format('Y-m-d 00:00:00'))
            ->where('starts_at', '<', $date->copy()->addDay()->format('Y-m-d 00:00:00'))
            ->where('con_event_id', '=', $event->id)
            ->orderBy('starts_at', 'asc')
            ->orderBy('room_id', 'asc')
            ->get();
        return $activities;
    }

    public function getStartsAtAttribute($value)
    {
        return \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $value);
    }

    public function getEndsAtAttribute($value)
    {
        return \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $value);
    }


}

