﻿<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Scopes\OrganisationScope;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

/**
 * Expenses
 */
class Expenses extends Model
{
    use HasFactory;

    /**
     * fillable
     *
     * @var array
     */
    protected $fillable = [
        'organisation_id',
        'category_id',
        'title',
        'date',
        'total',
        'notes',
        'expense_by',
        'created_by',
        'updated_by'
    ];


    use LogsActivity;

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logAll()
            ->useLogName('Expenses')
            ->logOnlyDirty()
            ->setDescriptionForEvent(fn(string $eventName) => "{$this->title} Expense record has been {$eventName}")
            ->dontSubmitEmptyLogs();
    }

    protected static function booted()
    {
        static::addGlobalScope(new OrganisationScope);

        // Automatically set the organisation_id before creating the model
        static::creating(function ($model) {
            if (auth()->check()) {
                $model->organisation_id = auth()->user()->organisation_id;
            }
        });
    }

    // CONST
    public const FILE_STORE_PATH = 'expenses';


    // RELATIONS

    /**
     * category
     *
     * @return void
     */
    public function category()
    {
        return $this->belongsTo(ExpensesCategory::class, 'category_id');
    }

    /**
     * items
     *
     * @return void
     */
    public function items()
    {
        return $this->hasMany(ExpensesItem::class, 'expenses_id');
    }

    /**
     * files
     *
     * @return void
     */
    public function files()
    {
        return $this->hasMany(ExpensesFile::class, 'expenses_id');
    }

    /**
     * expense by
     *
     * @return void
     */
    public function expenseBy()
    {
        return $this->belongsTo(User::class, 'expense_by', 'id');
    }