<?php

namespace App\Traits;

use App\Models\Document;
use Illuminate\Http\UploadedFile;

trait HasDocuments
{
    /**
     * Get all documents for this model.
     */
    public function documents()
    {
        return $this->morphMany(Document::class, 'documentable');
    }

    /**
     * Get documents of a specific type.
     */
    public function documentsOfType($type)
    {
        return $this->documents()->where('type', $type);
    }

    /**
     * Upload a document for this model.
     */
    public function uploadDocument(UploadedFile $file, $documentType = 'general', $description = null)
    {
        // Generate unique filename
        $fileName = time().'_'.$file->getClientOriginalName();

        // Store file in a folder named after the model
        $folderName = strtolower(class_basename($this));
        $filePath = $file->storeAs("documents/{$folderName}", $fileName, Document::STORAGE_DISK);

        // Create document record
        return $this->documents()->create([
            'name' => $file->getClientOriginalName(),
            'path' => $filePath,
            'file_size' => $file->getSize(),
            'mime_type' => $file->getClientMimeType(),
            'type' => $documentType,
            'description' => $description,
            'uploaded_by' => auth()->id(),
        ]);
    }

    /**
     * Delete a document by ID.
     */
    public function deleteDocument($documentId)
    {
        $document = $this->documents()->findOrFail($documentId);

        return $document->delete();
    }

    /**
     * Get documents count.
     */
    public function getDocumentsCountAttribute()
    {
        return $this->documents()->count();
    }

    /**
     * Get documents count by type.
     */
    public function getDocumentsCountByType($type)
    {
        return $this->documentsOfType($type)->count();
    }

    /**
     * Check if model has documents.
     */
    public function hasDocuments()
    {
        return $this->documents()->exists();
    }

    /**
     * Check if model has documents of specific type.
     */
    public function hasDocumentsOfType($type)
    {
        return $this->documentsOfType($type)->exists();
    }
}
