<?php

namespace App\Models\gerai;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\gerai\GeraiItem;
use App\Models\gerai\GeraiArPayment;
use App\Models\gerai\GeraiDeposit;
use App\Models\invoice\Status;
use Laravel\Scout\Searchable;

class GeraiInvoice extends Model
{
    use HasFactory;
    use Searchable;

    public $table = 'gerai_invoice';

    protected $fillable = [
        'invoiceNo',
        'parentInvoiceNo',
        'date',
        'debtorCode',
        'debtorName',
        'transporterCode',
        'transporterName',
        'vehicleNo',
        'phoneNo',
        'totalQuantity',
        'totalAmount',
        'grandQuantity',
        'grandTotal',
        'statusID'
    ];

    /**
     * Accessor for parentInvoiceNo with 'KPBIV-' prefix
     * (You can change prefix in config later)
     */
    public function getInvoiceNameAttribute()
    {
        return 'KPBIV-' . $this->attributes['invoiceNo'];
    }

    public function getParentInvoiceNameAttribute()
    {
        return 'KPBIV-' . $this->attributes['parentInvoiceNo'];
    }

    /**
     * Define relationship with Status Model
     */
    public function status()
    {
        return $this->belongsTo(Status::class, 'statusID');
    }

    /**
     * Define relationship with GeraiArPayment Model
     */
    public function arPayment()
    {
        return $this->hasMany(GeraiArPayment::class, 'geraiInvoiceID');
    }

    /**
     * Define relationship with GeraiDeposit Model
     */
    public function deposit()
    {
        return $this->hasMany(GeraiDeposit::class, 'geraiInvoiceID');
    }

    /**
     * Define relationship with GeraiItem Model
     */
    public function items()
    {
        return $this->hasMany(GeraiItem::class, 'geraiInvoiceID');
    }

    /**
     * Get all invoices from the same batch (same parentInvoiceNo)
     * Example: Get all gerais from invoice 00044 (00044-1, 00044-2, 00044-3)
     */
    public function batchInvoices()
    {
        return self::where('parentInvoiceNo', $this->parentInvoiceNo)
            ->orderBy('invoiceNo')
            ->get();
    }

    /**
     * Searchable array for Laravel Scout
     */
    public function toSearchableArray()
    {
        return [
            'invoiceNo' => $this->invoiceNo,
            'parentInvoiceNo' => $this->parentInvoiceNo,
            'debtorCode' => $this->debtorCode,
            'debtorName' => $this->debtorName,
            'transporterCode' => $this->transporterCode,
            'transporterName' => $this->transporterName,
            'vehicleNo' => $this->vehicleNo,
        ];
    }
}