<?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 DeliveryChallan extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'challan_number',
        'invoice_id',
        'customer_id',
        'bill_from_user_id',
        'delivery_date',
        'status',
        'subtotal',
        'tax_amount',
        'discount_amount',
        'total',
        'currency',
        'notes',
        'terms',
        'payment_method',
        'bank_account_id',
        'signature_id',
        'signature_type',
        'created_by',
    ];

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

    /**
     * Get the invoice that owns the delivery challan
     */
    public function invoice(): BelongsTo
    {
        return $this->belongsTo(Invoice::class);
    }

    /**
     * Get the customer that owns the delivery challan
     */
    public function customer(): BelongsTo
    {
        return $this->belongsTo(Customer::class);
    }

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

    /**
     * Get the user for bill from
     */
    public function billFromUser(): BelongsTo
    {
        return $this->belongsTo(User::class, 'bill_from_user_id');
    }

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

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

    /**
     * Get all items for this delivery challan
     */
    public function items(): HasMany
    {
        return $this->hasMany(DeliveryChallanItem::class);
    }

    /**
     * Generate challan number
     */
    public static function generateChallanNumber(): string
    {
        $lastChallan = static::withTrashed()
            ->orderBy('id', 'desc')
            ->first();

        $nextNumber = $lastChallan ? $lastChallan->id + 1 : 1;

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