<?php

namespace App\Models;

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

class DocumentHeader extends Model
{
    protected $fillable = [
        'type',
        'document_number',
        'parent_document_id',
        'parent_document_type',
        'customer_account_id',
        'contact_person',
        'document_date',
        'due_date',
        'delivery_date',
        'order_number',
        'project_id',
        'representative_id',
        'settlement_term',
        'currency_code',
        'allow_negative',
        'sales_representative_id',
        'status',
        'processed_at',
        'processed_by',
        'exclusive_total',
        'tax_amount',
        'discount_total',
        'inclusive_total',
        'pricing_type',
        'notes',
        'addedby',
    ];

    protected $casts = [
        'document_date' => 'date',
        'due_date' => 'date',
        'delivery_date' => 'date',
        'created_at'    => 'datetime',
        'updated_at'    => 'datetime',
    ];

    public function customer(): BelongsTo
    {
        return $this->belongsTo(CustomerAccount::class, 'customer_account_id');
    }

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

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

    public function salesRep(): BelongsTo
    {
        return $this->belongsTo(SalesRep::class, 'sales_representative_id');
    }

    // public function lines(): HasMany
    // {
    //     return $this->hasMany(DocumentLine::class, 'document_header_id');
    // }

    public function getDocumentTypeAttribute(): string
    {
        return ucwords(str_replace('_', ' ', $this->type));
    }


public function receipts()
{
    return $this->hasMany(Receipt::class, 'customer_id', 'customer_account_id')
                ->where('receipt_date', '>=', $this->document_date);
}

public function lines()
{
    return $this->hasMany(DocumentLine::class, 'document_header_id', 'id');
}

public function addedByUser()
{
    return $this->belongsTo(User::class, 'addedby', 'id');
}

public function item()
{
    return $this->hasMany(PriceListingSetup::class, 'id');
}

}
