<?php

/**
 * Created by Reliese Model.
 */

namespace App\Models;

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

/**
 * Class ProjectTask
 * 
 * @property int $id
 * @property int $project_phase_id
 * @property string $name
 * @property string|null $description
 * @property Carbon $start_date
 * @property Carbon $due_date
 * @property int $order_number
 * @property string $priority
 * @property string $status
 * @property int $completion_percentage
 * @property int|null $assigned_to
 * @property string|null $notes
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * 
 * @property User|null $user
 * @property ProjectPhase $project_phase
 * @property Collection|ProjectIssue[] $project_issues
 * @property Collection|ProjectResourceAllocation[] $project_resource_allocations
 * @property Collection|ProjectTaskDependency[] $project_task_dependencies
 *
 * @package App\Models
 */
class ProjectTask extends Model
{
	protected $table = 'project_tasks';

	protected $casts = [
		'project_phase_id' => 'int',
		'start_date' => 'datetime',
		'due_date' => 'datetime',
		'order_number' => 'int',
		'completion_percentage' => 'int',
		'assigned_to' => 'int'
	];

	protected $fillable = [
		'project_phase_id',
		'name',
		'description',
		'start_date',
		'due_date',
		'order_number',
		'priority',
		'status',
		'completion_percentage',
		'assigned_to',
		'notes'
	];

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

	public function project_phase()
	{
		return $this->belongsTo(ProjectPhase::class);
	}

	public function project_issues()
	{
		return $this->hasMany(ProjectIssue::class);
	}

	public function project_resource_allocations()
	{
		return $this->hasMany(ProjectResourceAllocation::class, 'task_id');
	}

	public function project_task_dependencies()
	{
		return $this->hasMany(ProjectTaskDependency::class, 'task_id');
	}

	// العلاقات المختصرة
	public function phase()
	{
		return $this->belongsTo(ProjectPhase::class, 'project_phase_id');
	}

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

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

	public function issues()
	{
		return $this->hasMany(ProjectIssue::class);
	}

	public function resourceAllocations()
	{
		return $this->hasMany(ProjectResourceAllocation::class, 'task_id');
	}

	public function dependencies()
	{
		return $this->hasMany(ProjectTaskDependency::class, 'task_id');
	}

	/**
	 * تحديد ما إذا كانت المهمة متأخرة
	 * 
	 * @return bool
	 */
	public function isOverdue()
	{
		// المهمة متأخرة إذا كان تاريخ الاستحقاق قبل اليوم الحالي وحالة المهمة ليست مكتملة
		return $this->due_date < now() && $this->status !== 'completed';
	}
}
