<?php

namespace App\Models;

use App\Service\Transfer\MobileBank;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class CustomerPaymentCollection extends BaseModel
{
    use HasFactory;

    protected $guarded = [];

    protected $appends = ['account'];
    public function customer()
    {
        return $this->hasOne(Client::class, 'id', 'client_id');
    }

    public function supplier()
    {
        return $this->hasOne(Supplier::class, 'id', 'supplier_id');
    }

    public function invoice()
    {
        return $this->hasOne(SalesMaster::class, 'id', 'invoice_id');
    }

    protected static function boot()
    {
        parent::boot(); // always call the parent boot
        static::addGlobalScope('typeScope', function ($builder) {
            if (auth()->check() && auth()->user()->shop_id != null) {
                $shopId = auth()->user()->shop_id;
                $builder->Where(function ($query) use ($shopId) {
                    $query->where('customer_payment_collections.transition_location_id', $shopId)
                        ->orWhere('customer_payment_collections.warehouse_id', $shopId);
                });
            }
        });
        static::creating(function ($model) {
            if (auth()->check()) {
                $user = auth()->user();
                $model->transition_location_id = $user->shop_id;
                $model->transition_create_by = $user->id;
            }
        });

        static::updating(function ($model) {
            if (auth()->check()) {
                $model->transition_update_by = auth()->id(); // use user ID here
            }
        });
    }

    public function location()
    {
        return $this->hasOne(Warehouse::class, 'id', 'warehouse_id');
    }
    public function bank()
    {
        return $this->hasOne(Bank::class, 'id', 'payment_id');
    }

    public function mobileBank()
    {
        return $this->hasOne(MobileBanking::class, 'id', 'payment_id');
    }


    public function getAccountAttribute()
    {
        if ($this->payment_type === 'Bank' && $this->bank) {
            return 'Bank ' . $this->bank->bank_name . ' - ' . $this->bank->account_number;
        }

        if ($this->payment_type === 'Mobile Bank' && $this->mobileBank) {
            return 'Mobile Bank ' .  $this->mobileBank->account_name . ' - ' . $this->mobileBank->account_number . ' - ' . $this->mobileBank->account_type;
        }

        return 'Cash';
    }

    public function getFormattedCreatedAtAttribute()
    {
        return $this->created_at->format('d M Y, h:i A');
    }

    public function salesPerson()
    {
        return $this->hasOne(SalesPerson::class, 'id', 'sales_person_id');
    }

    public function advancePaymentMaster()
    {
        return $this->belongsTo(CustomerAdvancePaymentMaster::class, 'advance_payment_master_id', 'id');
    }
}
