﻿<?php

namespace App\Models;

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


class Coupon extends Model
{
    use HasFactory, ScopeActive, ModelBoot;

    public const STATUS_ACTIVE = 'active';
    public const STATUS_INACTIVE = 'inactive';
    public const FILE_STORE_PATH = 'coupons';

    protected $fillable = [
        'organisation_id',
        'title',
        'code',
        'banner',
        'minimum_shopping',
        'maximum_discount',
        'discount_type',
        'discount',
        'status',
        'start_date',
        'end_date',
        'created_by',
        'updated_by'
    ];

    protected $appends = ['banner_url'];

    use LogsActivity;

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logAll()
            ->useLogName('Coupon')
            ->logOnlyDirty()
            ->setDescriptionForEvent(fn(string $eventName) => "{$this->title} Coupon 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;
            }
        });
    }

    public function getBannerUrlAttribute()
    {
        return getStorageImage(self::FILE_STORE_PATH, $this->banner);
    }
    public function couponProducts()
    {
        return $this->hasMany(CouponProduct::class);
    }