<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class SupplierCreditNote extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'supplier_id',
        'branch_id',
        'user_id',
        'supplier_invoice_id',
        'credit_note_number',
        'amount',
        'reason',
        'date',
        'notes',
    ];

    protected $casts = [
        'amount' => 'decimal:2',
        'date'   => 'date',
    ];

    public const REASON_GOODS_RETURN  = 'goods_return';
    public const REASON_DAMAGED       = 'damaged';
    public const REASON_OVERCHARGE    = 'overcharge';
    public const REASON_DISCOUNT      = 'discount';
    public const REASON_EXPIRY_RETURN = 'expiry_return';
    public const REASON_RECALL        = 'recall';
    public const REASON_OTHER         = 'other';

    public function supplier(): BelongsTo
    {
        return $this->belongsTo(Supplier::class);
    }

    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class);
    }

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

    public function invoice(): BelongsTo
    {
        return $this->belongsTo(SupplierInvoice::class, 'supplier_invoice_id');
    }

    public static function generateCreditNoteNumber(): string
    {
        $prefix = 'SCN-' . date('Ymd');
        $last   = static::where('credit_note_number', 'like', $prefix . '%')
                        ->orderBy('credit_note_number', 'desc')
                        ->first();

        $next = $last ? ((int) substr($last->credit_note_number, -4)) + 1 : 1;
        return $prefix . '-' . str_pad($next, 4, '0', STR_PAD_LEFT);
    }
}
