<?php

namespace App\Models\Sales;

use App\Models\Concerns\BelongsToTenant;
use App\Models\Lookups\PaymentMethod;
use App\Models\Returns\CreditNote;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * An advance taken against a sales order, before any invoice exists.
 *
 * Deliberately NOT a `transactions` row: there is nothing to settle yet. These
 * are replayed verbatim as payment splits by
 * SalesOrderService::convertToInvoice(), so the money is banked through exactly
 * the same PaymentService path as POS and invoice checkout — including credit
 * notes, which travel as a `credit` split carrying `credit_note_id` and are
 * claimed by PaymentService itself. Until conversion they only drive the
 * order's own paid/balance figures and its payment status badge.
 *
 * `method` always holds a real {@see PaymentMethod} code, never a made-up one.
 */
class SalesOrderPayment extends Model
{
    use BelongsToTenant;

    protected $fillable = [
        'sales_order_id', 'method', 'amount', 'reference',
        'cheque_number', 'cheque_bank', 'cheque_branch', 'cheque_date',
        'credit_note_id', 'received_at', 'custom_fields',
    ];

    protected function casts(): array
    {
        return [
            'amount' => 'decimal:2',
            'cheque_date' => 'date',
            'received_at' => 'date',
            'custom_fields' => 'array',
        ];
    }

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

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

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function isCreditNote(): bool
    {
        return $this->method === PaymentMethod::CREDIT && $this->credit_note_id !== null;
    }
}
