<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ProjectTeamMemberWorkHour extends Model
{
    use HasFactory;

    protected $fillable = [
        'project_team_member_id',
        'date',
        'hours',
        'description',
        'project_phase_id',
        'project_task_id',
        'approved',
        'approved_by',
        'approved_at',
        'notes',
    ];

    protected $casts = [
        'date' => 'date',
        'hours' => 'decimal:2',
        'approved' => 'boolean',
        'approved_at' => 'datetime',
    ];

    // العلاقات
    public function teamMember()
    {
        return $this->belongsTo(ProjectTeamMember::class, 'project_team_member_id');
    }

    public function phase()
    {
        return $this->belongsTo(ProjectPhase::class, 'project_phase_id');
    }

    public function task()
    {
        return $this->belongsTo(ProjectTask::class, 'project_task_id');
    }

    public function approvedByUser()
    {
        return $this->belongsTo(User::class, 'approved_by');
    }

    // الدوال المساعدة
    public function approve($userId)
    {
        $this->approved = true;
        $this->approved_by = $userId;
        $this->approved_at = now();
        $this->save();

        return true;
    }

    public function unapprove()
    {
        $this->approved = false;
        $this->approved_by = null;
        $this->approved_at = null;
        $this->save();

        return true;
    }

    public function getCost()
    {
        return $this->hours * $this->teamMember->hourly_rate;
    }
}
