<?php

namespace App\Models;

use App\Models\Packages;
use App\Models\Reseller;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class SubPackage extends Model
{
    use HasFactory;
    protected $fillable = [
        'reseller_id',
        'package_id',
        'name',
        'rate',
        'commission',
        'client_payment_amount'

    ];
    public function reseller()
    {
        return $this->belongsTo(Reseller::class, 'reseller_id');
    }
    public function package()
    {
        return $this->belongsTo(Packages::class, 'package_id');
    }




    static function conditionalList()
    {
        $id = auth()->id();



        if (auth()->user()->hasRole('Admin') || auth()->user()->hasRole('Administer Sub Reseller') || auth()->user()->hasPermissionTo('specific_management_services')) {

            $list = SubPackage::with('package','reseller')->get();

        } elseif (auth()->user()->hasRole('Reseller Admin')) {

            $reseller_ids = DB::table('reseller_user')->where('user_id', $id)->pluck('reseller_id')->toArray();

            $reseller_packages = Reseller::whereIn('id', $reseller_ids)->pluck('package_list')->toArray();
            // dd($resellers);

            $plist =  array_unique(explode(',', implode(',', $reseller_packages)));


            $list = SubPackage::whereIn('package_id', $plist)->whereIn('reseller_id',$reseller_ids)->get();
            // dd($plist);

        } elseif (auth()->user()->hasRole('Sub Reseller')) {

            $pop_ids = DB::table('pop_user')->where('user_id', $id)->pluck('pop_id')->toArray();
            $pop = Pop::with('nas')->whereIn('id', $pop_ids)->pluck('sub_package_list')->toArray();
            $plist =  array_unique(explode(',', implode(',', $pop)));

            // dd($plist);
            $list = SubPackage::whereIn('id', $plist)->get();
        } else {
            $plist = [];
            $list = SubPackage::whereIn('id', $plist)->get();
        }

        return $list;
    }
}
