<?php

namespace App\Modules\Gamification;

use App\Facades\DBconfig;
use Carbon\Carbon;

trait PointsTrait
{
    /**
     * Calculates the points earned for this task.
     *
     * @return int
     */
    public function getPointsAttribute($value = null)
    {
        // Handle null values gracefully
        if ($value === null && !isset($this->attributes['points'])) {
            return 0;
        }
        
        $poundToPointRatio = DBconfig::get('gamification.ratio', 1);
        $pointsPerMinute = DBconfig::get('gamification.points_per_minute', 1.13);

        switch ($this->type) {
            case 'repair':

                if ($this->labour) {
                    return $this->labour * $poundToPointRatio;
                }

                $standard_price = $this->standard_price;
                $standard_price = ($standard_price) ? $standard_price->price : 0;

                return $standard_price * $poundToPointRatio;

            case 'support':
                $timeSpent = $this->time_spent ?? 0;
                $labour = $this->labour ?? 0;
                return ($labour) ? $labour * $poundToPointRatio : round($timeSpent * $pointsPerMinute);

            case 'onsite':
                $labour = $this->labour ?? 0;
                if ($labour) {
                    return $labour * $poundToPointRatio;
                }
                
                if ($this->onsite_start && $this->onsite_end) {
                    return round(ceil(abs(Carbon::parse($this->onsite_start)->diffInMinutes(Carbon::parse($this->onsite_end)))) * $pointsPerMinute);
                }
                
                return 0;
        }

        return 0;
    }
}
