<?php

namespace App;

use App\Repositories\TrainingWorkoutSectionRepository;
use App\Repositories\UserBenchmarkRepository;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class UserBenchmarkSection extends Model
{
    protected $fillable = [
        'id', 'user_benchmark_id', 'training_workout_section_id', 'time', 'completed', 'rounds', 'reps', 'custom_score'
    ];

    protected $appends = [
        "score_section"
    ];

    /**
     * ATRIBUTS FICTICIS
     */
    public function getScoreSectionAttribute() {
        $training_workout_section = TrainingWorkoutSectionRepository::find($this->training_workout_section_id);
        if($training_workout_section->custom_score!=1) {
            $type = $training_workout_section->type;
            if ($type=='AMRAP') {
                $score = (int)($this->rounds . '' . $this->reps);
            } else if ($type=='Death By') {
                $score = $this->rounds;
            } else if ($type=='For Time' || $type=='Chipper') {
                $d = explode(':', $this->time);
                $score = ($d[0] * 3600) + ($d[1] * 60) + $d[2];
            } else if ($type=='EMOM' || $type=='E2MOM') {
                $score = ($this->completed) ? 100 : 0;
            } else {
                $score = 0;
            }

            $ub = UserBenchmarkRepository::find($this->user_benchmark_id);
            if ($ub->level=='RX') return $score;
            else if ($ub->level=='SC') return $score>0 ? $score/2 : 0;
            else return 0;
        } else return $this->custom_score!=null ? $this->custom_score : 0;

    }

    protected $with = ["user_benchmark_lines"];

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

    public function user_benchmark() {
        return $this->belongsTo("App\UserBenchmark", "user_benchmark_id");
    }

    public function user_benchmark_lines() {
        return $this->hasMany("App\UserBenchmarkLine", "user_benchmark_section_id", "id");
    }
}
