<?php

namespace App\Models;

use App\Traits\BelongsToOrg;
use Database\Factories\ProjectCharterDeliverableFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class ProjectCharterDeliverable extends Model implements HasMedia
{
    /** @use HasFactory<ProjectCharterDeliverableFactory> */
    use BelongsToOrg, HasFactory, InteractsWithMedia, SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'project_charter_id',
        'name',
        'description',
        'delivery_date',
        'weight',
        'cost',
        'created_by',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'delivery_date' => 'date',
            'weight' => 'decimal:2',
            'cost' => 'decimal:2',
        ];
    }

    /**
     * Get the project charter that this deliverable belongs to.
     */
    public function projectCharter(): BelongsTo
    {
        return $this->belongsTo(ProjectCharter::class);
    }

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

    /**
     * Get the tasks for this deliverable.
     */
    public function tasks(): HasMany
    {
        return $this->hasMany(ProjectCharterDeliverableTask::class);
    }

    /**
     * Get the completion reports for this deliverable.
     */
    public function completionReports(): HasMany
    {
        return $this->hasMany(CompletionReport::class);
    }

    /**
     * Calculate the overall progress percentage based on associated tasks.
     */
    public function getProgressPercentageAttribute(): float
    {
        $tasks = $this->tasks;

        if ($tasks->isEmpty()) {
            return 0.00;
        }

        $totalProgress = $tasks->sum('progress_percentage');
        $percentage = $totalProgress / $tasks->count();

        return round($percentage, 2);
    }

    /**
     * Check if deliverable has a file
     */
    public function hasFile(): bool
    {
        return $this->getFirstMedia('deliverable_file') !== null;
    }

    /**
     * Register media collections.
     */
    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('deliverable_file')
            ->singleFile()
            ->acceptsMimeTypes(['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'image/jpeg', 'image/png']);
    }

    /**
     * Register media conversions.
     */
    public function registerMediaConversions(?Media $media = null): void
    {
        $this->addMediaConversion('thumb')
            ->width(300)
            ->height(300)
            ->sharpen(10);
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (Auth::check() && ! $model->created_by) {
                $model->created_by = Auth::id();
            }
        });
    }
}
