<?php

namespace App;

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

class PlanDetail extends Model
{
	use HasFactory;
	
	protected $fillable = [
		'plan_id',
		'project_id',
		'customer_id',
		'charge_id',
		'type',
		'time_start',
		'time_end',
		'time_range'
	];
	
	protected $casts = [
		'plan_id'     => 'integer',
		'project_id'  => 'integer',
		'customer_id' => 'integer',
		'charge_id'   => 'integer',
		'type'        => 'integer',
		'time_start'  => 'datetime:H:i',
		'time_end'    => 'datetime:H:i',
		'time_range'  => 'float'
	];
	
	// Relationships
	public function plan()
	{
		return $this->belongsTo(Plan::class);
	}
	
	public function project()
	{
		return $this->belongsTo(Project::class);
	}
	
	public function customer()
	{
		return $this->belongsTo(Customer::class);
	}
	
	public function charge()
	{
		return $this->belongsTo(Charge::class);
	}
	
	public function users()
	{
		return $this->belongsToMany(User::class, 'plan_detail_users', 'plan_detail_id', 'user_id')
			->withTimestamps();
	}
	
	public function reports()
	{
		return $this->hasMany(Report::class);
	}
	
	// Scopes
	public function scopeByPlan($query, $planId)
	{
		return $query->where('plan_id', $planId);
	}
	
	public function scopeByCustomer($query, $customerId)
	{
		return $query->where('customer_id', $customerId);
	}
	
	public function scopeByType($query, $type)
	{
		return $query->where('type', $type);
	}
	
	// Type constants
	const TYPE_NORMAL = 0;
	const TYPE_SPECIAL = 1;
	
	public static function getTypeLabels()
	{
		return [
			self::TYPE_NORMAL  => 'Normal',
			self::TYPE_SPECIAL => 'Special'
		];
	}
	
	public function getTypeLabelAttribute()
	{
		$labels = self::getTypeLabels();
		return $labels[$this->type] ?? 'Unknown';
	}
	
	// Accessor for formatted time range
	public function getFormattedTimeRangeAttribute()
	{
		if ($this->time_start && $this->time_end) {
			return $this->time_start->format('H:i') . ' - ' . $this->time_end->format('H:i');
		}
		return null;
	}
}
