<?php

namespace App\Modules\Bookings;

use App\Models\ValidationModel;
use App\Models\User;
use App\Modules\Bookings\Task;

class TimeTracking extends \Eloquent
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['user_id', 'task_id', 'started_at', 'ended_at'];

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'time_tracking';

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['active', 'duration', 'duration_formatted'];

    /**
     * Defines a relationship that points to the user that created the timer.
     *
     * @return \User
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * Defines a relationship that points to the task associated with
     * the timer.
     *
     * @return \App\Modules\Bookings\Task
     */
    public function task()
    {
        return $this->belongsTo(Task::class, 'task_id');
    }

    /**
     * Determines if the timer is still counting or not.
     *
     * @return bool
     */
    public function getActiveAttribute()
    {
        return ! $this->ended_at && $this->user_id == getAuthUserId();
    }

    /**
     * Get the duration in seconds.
     *
     * @return int
     */
    public function getDurationAttribute()
    {
        return $this->ended_at ? strtotime($this->ended_at) - strtotime($this->started_at) : time() - strtotime($this->started_at);
    }

    /**
     * Gets the duration formatted as hours:minutes:seconds.
     *
     * @return string
     */
    public function getDurationFormattedAttribute()
    {
        return gmdate('H:i:s', $this->duration);
    }
}
