<?php

namespace App;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class TrainingSession extends Model {
    protected $fillable = [
        "box_id", "coach_id", "training_room_id", "training_workout_id", "training_type_id", "capacity", "credits",
        "date_start", "date_end", "day", "start_time", "end_time"
    ];

    protected $casts = [
        "day" => "date",
        "credits" => "boolean"
    ];

    protected $appends = ["date_start", "date_end"];

    protected $hidden = ["day", "start_time", "end_time"];

    protected $with = ["trainingType", "coach", "users", "trainingRoom", "trainingWorkout"];

    /**
     * EVENTS FIRED WHEN CREATING
     */
    public static function boot() {
        parent::boot();

        static::creating(function(TrainingSession $s) { //Quan es crei una nova instancia de session, agafa capacity per defecte
            if(!isset($s->attributes["capacity"])) {
                $s->attributes["capacity"] = TrainingRoom::findOrFail($s->training_room_id)->capacity;
            }
        });
    }

    public function getDateStartAttribute() {
        return $this->day->setTimeFromTimeString($this->start_time);
    }

    public function setDateStartAttribute($val) {
        $carbon = Carbon::parse($val)->setTimezone('UTC');
        $this->attributes["day"] = $carbon;
        $this->attributes["start_time"] = $carbon->format("H:i:s");
    }

    public function getDateEndAttribute() {
        return $this->day->setTimeFromTimeString($this->end_time);
    }

    public function setDateEndAttribute($val) {
        $carbon = Carbon::parse($val)->setTimezone('UTC');
        $this->attributes["day"] = $carbon;
        $this->attributes["end_time"] = $carbon->format("H:i:s");
    }

    /**
     * RELATIONSHIPS
     */

    public function trainingWorkout() {
        return $this->belongsTo("App\TrainingWorkout");
    }

    public function trainingType() {
        return $this->belongsTo("App\TrainingType");
    }

    public function trainingRoom() {
        return $this->belongsTo("App\TrainingRoom", "training_room_id");
    }

    public function users() { //users inscrits
        return $this->belongsToMany("App\User", "user_training_sessions", "training_session_id", "user_id")
                    ->withPivot("type")
                    ->withTimestamps();
    }

    public function usersToNotify() { //users esperant
        return $this->belongsToMany("App\User", "notify_user_training_sessions", "training_session_id", "user_id")
            ->withTimestamps();
    }

    public function coach() {
        return $this->belongsTo("App\User", "coach_id");
    }

    public function box(){
        return $this->belongsTo("App\Box");
    }

    public function capacity(){
        return $this->capacity - $this->users()->count();
    }

    public function userBenchmarks() {
        return $this->hasMany("App\UserBenchmark");
    }

}
