<?php

namespace Mtc\Modules\B2B\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Mtc\Modules\B2B\Enums\AccountOrderStatus;
use Mtc\Shop\Order;

class AccountOrder extends Model
{
    protected $table = 'b2b_account_orders';

    protected $fillable = [
        'order_id',
        'trade_customer_id',
        'po_number',
        'amount_due',
        'status',
        'paid_at',
        'paid_by',
        'payment_reference',
        'marked_paid_by',
        'last_reminder_sent_at',
    ];

    protected $casts = [
        'paid_at'               => 'datetime',
        'last_reminder_sent_at' => 'datetime',
        'amount_due'            => 'decimal:2',
        'status'                => AccountOrderStatus::class,
    ];

    public function order(): BelongsTo
    {
        return $this->belongsTo(Order::class, 'order_id');
    }

    public function tradeCustomer(): BelongsTo
    {
        return $this->belongsTo(TradeCustomer::class, 'trade_customer_id');
    }

    public function scopeUnpaid(Builder $query): Builder
    {
        return $query->where('status', AccountOrderStatus::Unpaid->value);
    }

    public function scopePaid(Builder $query): Builder
    {
        return $query->where('status', AccountOrderStatus::Paid->value);
    }

    public function markPaid(string $paidBy, ?string $paymentReference = null, ?int $markedPaidBy = null): void
    {
        $this->update([
            'status'            => AccountOrderStatus::Paid->value,
            'paid_at'           => now(),
            'paid_by'           => $paidBy,
            'payment_reference' => $paymentReference,
            'marked_paid_by'    => $markedPaidBy,
        ]);
    }
}
