<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Auth;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class ProjectCharterFile extends Model implements HasMedia
{
    use HasFactory, InteractsWithMedia;

    protected $fillable = [
        'name',
        'project_charter_id',
        'created_by',
    ];

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

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

    public function projectCharter(): BelongsTo
    {
        return $this->belongsTo(ProjectCharter::class);
    }

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

    /**
     * Register media collections
     */
    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('charter_files')
            ->acceptsMimeTypes([
                'application/pdf',
                'image/jpeg',
                'image/png',
            ])
            ->singleFile();
    }

    /**
     * Register media conversions
     */
    public function registerMediaConversions(?Media $media = null): void
    {
        // Add thumbnail generation for images if needed
        $this->addMediaConversion('thumb')
            ->width(300)
            ->height(300)
            ->sharpen(10)
            ->performOnCollections('charter_files')
            ->nonQueued();
    }

    /**
     * Check if the file has media attached
     */
    public function hasFile(): bool
    {
        return $this->getFirstMedia('charter_files') !== null;
    }

    /**
     * Get the file media
     */
    public function getFile()
    {
        return $this->getFirstMedia('charter_files');
    }

    /**
     * Get file size in human readable format
     */
    public function getFileSizeAttribute(): ?string
    {
        $file = $this->getFile();
        if (! $file) {
            return null;
        }

        $bytes = $file->size;
        $units = ['B', 'KB', 'MB', 'GB'];
        $power = $bytes > 0 ? floor(log($bytes, 1024)) : 0;

        return number_format($bytes / pow(1024, $power), 2, '.', ',').' '.$units[$power];
    }
}
