<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PaymentMethod extends Model
{
    use HasFactory;

    protected $fillable = [
        'company_id', 'name', 'driver',
        'is_active', 'is_test_mode',
        'credentials', 'settings', 'sort_order',
    ];

    protected function casts(): array
    {
        return [
            'is_active'    => 'boolean',
            'is_test_mode' => 'boolean',
            'credentials'  => 'encrypted:array',
            'settings'     => 'array',
        ];
    }

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

    public function scopeActive(Builder $q): Builder
    {
        return $q->where('is_active', true);
    }

    public function scopeGlobal(Builder $q): Builder
    {
        return $q->whereNull('company_id');
    }

    public function scopeForCompany(Builder $q, int $companyId): Builder
    {
        return $q->where(function ($q2) use ($companyId) {
            $q2->whereNull('company_id')->orWhere('company_id', $companyId);
        });
    }
}
