<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ServiceVoucher extends Model
{


    protected $fillable = [
        'voucher_no',
        'voucher_date',
        'truck_no',
        'bill_no',
        'party_type',
        'party_id',
        'total_amount',
        'supplier_id',
        'description'
    ];

    public function details()
    {
        return $this->hasMany(ServiceVoucherDetail::class);
    }
    public function supplier()
    {
        return $this->belongsTo(Suppliers::class, 'supplier_id', 'id_supplier');
    }
    public function party()
    {
        if (!$this->party_type || !$this->party_id) return null;

        $modelMap = [
            'Supplier'  => \App\Suppliers::class,
            'Purchaser' => \App\Purchaser::class,
        ];

        $modelClass = $modelMap[$this->party_type] ?? null;
        if (!$modelClass) return null;

        return $modelClass::find($this->party_id);
    }

    /**
     * Handy accessor: $voucher->party_name
     */
    public function getPartyNameAttribute(): string
    {
        $party = $this->party();
        if (!$party) return 'N/A';

        return match ($this->party_type) {
            'Supplier'  => $party->supplier_name_urdu  ?? $party->supplier_name  ?? 'N/A',
            'Purchaser' => $party->purchaser_name_urdu ?? $party->purchaser_name ?? 'N/A',
            default     => 'N/A',
        };
    }
}
