<?php

namespace App\Models;

use App\Events\ProjectMailingStatus;
use App\Traits\HasStatus;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class ProjectMailing extends Model
{
    use HasFactory;
    use HasStatus;

    protected $fillable = [
        'subject',
        'message',
        'status',
        'report_id',
    ];

    public function addAttachment($name, UploadedFile $file)
    {
        $prefix = Str::random(10);
        $originalFileName = $file->getClientOriginalName();
        $extension = pathinfo($originalFileName, PATHINFO_EXTENSION);
        $newFileName = $prefix.'_'.pathinfo($originalFileName, PATHINFO_FILENAME).'.'.$extension;

        $path = Storage::disk('local')->putFileAs(
            $this->project->attachmentPath, $file, $newFileName
        );

        $this->attachments()->save(new ProjectMailingAttachment([
            'name' => $name,
            'path' => $path
        ]));
    }
    public function report()
    {
        return $this->belongsTo(ProjectReport::class, 'report_id', 'id');
    }

    public function project()
    {
        return $this->belongsTo(Project::class, 'project_id', 'id');
    }

    public function recipients()
    {
        return $this->hasMany(ProjectMailingRecipient::class);
    }

    public function attachments()
    {
        return $this->hasMany(ProjectMailingAttachment::class);
    }

    protected function subject(): Attribute
    {
        return Attribute::make(
            set: function ($value) {
                return str_replace(['{date}'], [now()->toDateString()], $value);
            }
        );
    }

    protected static function booted(): void
    {
        parent::booted();
        static::updated(function (ProjectMailing $projectMailing) {
            event(new ProjectMailingStatus($projectMailing));
        });
    }
}
