<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Storage;

class BookkeepingDocument extends Model
{
    use HasFactory;

    public const PATH_PREFIX = 'public/bookkeeping';
    
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'company_id',
        'user_id',
        'batch_name',
        'remark',
        'file_name',
        'bookkeeping_document_category_id',
        'status',
        'data_molino_status',
        'data_molino_return_status',
        'xero_status',
        'xero_amount',
        'url',
        'name',
        'description',
        'file_size',
    ];

    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function category()
    {
        return $this->belongsTo(BookkeepingDocumentCategory::class, 'bookkeeping_document_category_id', 'id');
    }

    public function getFolderPathAttribute()
    {
        return self::PATH_PREFIX . '/' . $this->id;
    }

    public function getFilePathAttribute()
    {
        return ! $this->file_name ? null : $this->getFolderPathAttribute() . "/{$this->file_name}";
    }

    public function getFileUrlAttribute()
    {
        $path = $this->getFilePathAttribute();

        if ($path && Storage::exists($path)) {
            return env('AWS_ENDPOINT') . env('AWS_BUCKET') . '/' . $path;
        }

        return '#';
    }
}
