<?php

namespace App\Models\Agency;

use App\Models\Product\ProductType;
use Illuminate\Database\Eloquent\Relations\Pivot;

class AgencyProductType extends Pivot
{
    protected $table = 'agency_product_types';

    protected $fillable = [
        'agency_id',
        'product_type_id',
        'is_active',
        'settings',
        'activated_at',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'settings' => 'array',
        'activated_at' => 'datetime',
    ];

    public $timestamps = true;

    // Relationships
    public function agency()
    {
        return $this->belongsTo(Agency::class);
    }

    public function productType()
    {
        return $this->belongsTo(ProductType::class);
    }

    // Helper methods
    public function isActive(): bool
    {
        return $this->is_active;
    }

    public function activate(): void
    {
        $this->update([
            'is_active' => true,
            'activated_at' => now(),
        ]);
    }

    public function deactivate(): void
    {
        $this->update([
            'is_active' => false,
        ]);
    }

    public function getSetting(string $key, $default = null)
    {
        return data_get($this->settings, $key, $default);
    }

    public function setSetting(string $key, $value): void
    {
        $settings = $this->settings ?? [];
        data_set($settings, $key, $value);
        $this->update(['settings' => $settings]);
    }

    public function updateSettings(array $settings): void
    {
        $this->update([
            'settings' => array_merge($this->settings ?? [], $settings),
        ]);
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeInactive($query)
    {
        return $query->where('is_active', false);
    }
}
