<?php

namespace App\Models;

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

class CustomerAccount extends Model
{
    use HasFactory;

    protected $table = "customer_accounts";
    protected $fillable = [
        'account_type',
        'customer_code',
        'customer_account',
        'contact_person',
        'contact_1',
        'contact_2',
        'email',
        'address',
        'category_id',
        'sales_rep_id',
        'age_analysis_id',
        'terms',
        'area_id',
        'vat',
        'tin',
        'city',
        'province',
        'is_foreign_currency',
        'foreign_currency_id'
    ];

    protected $attributes = [
        'account_type' => '',
    ];

    public function category()
    {
        return $this->belongsTo(CustomerCategory::class, 'category_id');
    }

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

    public function ageAnalysis()
    {
        return $this->belongsTo(Ageing::class, 'age_analysis_id');
    }

    public function area()
    {
        return $this->belongsTo(Area::class, 'area_id');
    }

    public function foreignCurrency()
    {
        return $this->belongsTo(Currency::class, 'foreign_currency_id');
    }

    /**
     * All DocumentHeader records (orders, invoices, etc.) for this customer.
     */
    public function documentHeaders(): HasMany
    {
        return $this->hasMany(\App\Models\DocumentHeader::class, 'customer_account_id');
    }

    /**
     * Only the invoices (DocumentHeader with type = 'invoice') for this customer.
     */
    public function invoices(): HasMany
    {
        return $this->documentHeaders()
                    ->where('type', 'invoice');
    }

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

}
