<?php
// app/Models/Stage.php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Stage extends Model
{
    use HasFactory;

    protected $table = 'stages';

    protected $fillable = [
        'name',
        'description',
        'created_by',
        'updated_by',
        'active'
    ];

    protected $casts = [
        'active' => 'boolean',
    ];

    /**
     * Get the user who created this stage
     */
    public function createdBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Get the user who last updated this stage
     */
    public function updatedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    /**
     * Get the files in this stage
     */
    public function files(): HasMany
    {
        return $this->hasMany(File::class, 'stage_id');
    }

    /**
     * Get the count of files in this stage
     */
    // public function getFilesCountAttribute(): int
    // {
    //     return $this->files()->count();
    // }

    /**
     * Scope a query to only include active stages
     */
    public function scopeActive($query)
    {
        return $query->where('active', true);
    }

    /**
     * Scope a query to order by name
     */
    public function scopeOrdered($query)
    {
        return $query->orderBy('name');
    }
    // In app/Models/Stage.php

/**
 * Get all file assignments for this stage
 */
    public function fileAssignments()
    {
        return $this->hasMany(FileStage::class, 'stage_id')
            ->with('file')
            ->orderBy('created_at', 'desc');
    }

    /**
     * Get all files currently in this stage
     */
    public function currentFiles()
    {
        return $this->belongsToMany(File::class, 'file_stages')
            ->wherePivot('active', true)
            ->withPivot(['comment', 'created_by'])
            ->withTimestamps();
    }

    /**
     * Get count of files currently in this stage
     */
    public function getCurrentFilesCountAttribute(): int
    {
        return $this->fileAssignments()->where('active', true)->count();
    }

    /**
     * Get total files count (including inactive)
     */
    public function getTotalFilesCountAttribute(): int
    {
        return $this->fileAssignments()->count();
    }
    
}