<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Bundle extends Model
{
    public $fillable = [
        'capacity',
        'cost',
        'price',
        'network_id',
        'status',
    ];

    public function network()
    {
        return $this->belongsTo(Network::class, 'network_id');
    }

    public function pricing()
    {
        return $this->hasMany(AgentPricing::class);
    }

    public function realPricing()
    {
        return $this->hasMany(Pricing::class, 'bundle_id');
    }

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

    public function scopeWithAgentPricing($query, $agentId)
    {
        return $query->active()
            ->whereHas('pricing', function ($priceQuery) use ($agentId) {
                $priceQuery->where('user_id', $agentId)
                    ->where('status', true);
            });
    }

    public function scopeWithAgentPricingOrCustomerPricing($query, $agentId)
    {
        return $query->active()
            ->whereHas('pricing', function ($priceQuery) use ($agentId) {
                $priceQuery->where('user_id', $agentId)
                    ->where('status', true);
            })
            ->orWhereHas('realPricing', function ($priceQuery) {
                $priceQuery->whereHas('role', function ($query) {
                    $query->where('name', 'Customer');
                });
            });
    }

    public function levyOnBundle($price)
    {
        $levyWallet = SLWallet::first();
        $levy = $levyWallet->levy ?? 1;
        return ($price * $levy) / 100;
    }

    public function customerPricing()
    {
        return $this->realPricing()
            ->whereHas('role', function ($query) {
                $query->where('name', 'Customer');
            })
            ->value('price') ?? $this->price;
    }

    public function maxPrice()
    {
        return $this->realPricing()
            ->whereHas('role', function ($query) {
                $query->where('name', 'Customer');
            })
            ->value('price') ?? $this->price;
    }

    public function minPrice($agent)
    {
        return $this->realPricing()
            ->where('role_id', $agent->userRole())
            ->value('price') ?? $this->price;
    }
}