<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class DebitNote extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'debit_note_number',
        'purchase_id',
        'debit_note_date',
        'order_date',
        'status',
        'company_id',
        'supplier_id',
        'amount',
        'tax_amount',
        'discount_amount',
        'total',
        'payment_method',
        'notes',
        'terms',
        'signature_type',
        'signature_id',
        'created_by',
    ];

    protected function casts(): array
    {
        return [
            'debit_note_date' => 'date',
            'order_date' => 'date',
            'amount' => 'decimal:2',
            'tax_amount' => 'decimal:2',
            'discount_amount' => 'decimal:2',
            'total' => 'decimal:2',
        ];
    }

    /**
     * Generate debit note number
     */
    public static function generateDebitNoteNumber(): string
    {
        $lastNote = static::withTrashed()
            ->where('debit_note_number', 'like', 'DN-%')
            ->orderBy('id', 'desc')
            ->first();

        if ($lastNote) {
            $lastNumber = (int) substr($lastNote->debit_note_number, 3);
            $nextNumber = $lastNumber + 1;
        } else {
            $nextNumber = 1;
        }

        return 'DN-'.str_pad($nextNumber, 6, '0', STR_PAD_LEFT);
    }

    /**
     * Get the purchase this debit note belongs to
     */
    public function purchase(): BelongsTo
    {
        return $this->belongsTo(Purchase::class);
    }

    /**
     * Get the company (Bill From)
     */
    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class);
    }

    /**
     * Get the supplier (Bill To)
     */
    public function supplier(): BelongsTo
    {
        return $this->belongsTo(Supplier::class);
    }

    /**
     * Get all items for this debit note
     */
    public function items(): HasMany
    {
        return $this->hasMany(DebitNoteItem::class)->orderBy('sort_order');
    }

    /**
     * Get the signature
     */
    public function signature(): BelongsTo
    {
        return $this->belongsTo(Signature::class);
    }

    /**
     * Get the user who created the debit note
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }
}
