<?php

namespace Mtc\Modules\B2B\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Mtc\Modules\B2B\Enums\TradeCustomerStatus;
use Mtc\Modules\Members\Models\Member;

class TradeCustomer extends Model
{
    protected $table = 'b2b_trade_customers';

    protected $fillable = [
        'member_id',
        'tier_id',
        'company_name',
        'phone',
        'message',
        'status',
        'approved_at',
        'approved_by',
        'rejected_at',
    ];

    protected $casts = [
        'approved_at' => 'datetime',
        'rejected_at' => 'datetime',
    ];

    public function member(): BelongsTo
    {
        return $this->belongsTo(Member::class, 'member_id');
    }

    public function tier(): BelongsTo
    {
        return $this->belongsTo(TradeTier::class, 'tier_id');
    }

    public function address(): HasOne
    {
        return $this->hasOne(TradeAddress::class, 'trade_customer_id');
    }

    public function accountOrders(): HasMany
    {
        return $this->hasMany(AccountOrder::class, 'trade_customer_id');
    }

    public function scopePending(Builder $query): Builder
    {
        return $query->where('status', TradeCustomerStatus::Pending->value);
    }

    public function scopeApproved(Builder $query): Builder
    {
        return $query->where('status', TradeCustomerStatus::Approved->value);
    }

    public function isApproved(): bool
    {
        return $this->status === TradeCustomerStatus::Approved->value;
    }

    public function isPending(): bool
    {
        return $this->status === TradeCustomerStatus::Pending->value;
    }
}
