<?php

namespace App\Models;

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

class CreditNote extends Model
{
    use HasFactory;

    protected $fillable = [
        'credit_note_number',
        'invoice_id',
        'order_id',
        'user_id',
        'status',
        'amount',
        'reason',
        'notes',
        'issue_date',
    ];

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

    public function invoice()
    {
        return $this->belongsTo(Invoice::class);
    }

    public function order()
    {
        return $this->belongsTo(Order::class);
    }

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

    public static function generateCreditNoteNumber(): string
    {
        $prefix = 'CN';
        $date = now()->format('Ymd');
        $lastNote = self::whereDate('created_at', today())->latest()->first();
        $sequence = $lastNote ? ((int) substr($lastNote->credit_note_number, -4)) + 1 : 1;
        return $prefix . $date . str_pad($sequence, 4, '0', STR_PAD_LEFT);
    }
}
