<?php

namespace App\Models;

use App\Http\Controllers\ResellerRechargeReportController;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Reseller extends Model
{
    use HasFactory;

    protected $guarded = [
        'id'
    ];



    public function balance()
    {
        return $this->hasMany(Balance::class, 'type_id', 'id')->whereType('reseller');
    }



    public function commission()
    {
        return $this->hasMany(ResellerCommissionReference::class, 'reseller_id', 'id');
    }

    public function pops()
    {
        return $this->hasMany(Pop::class, 'reseller_id', 'id');
    }


    public function reseller_user()
    {
        return $this->hasMany(ResellerUser::class);
    }

    static function list()
    {

        $resellers = Reseller::with('pops', 'pops.balance', 'balance', 'reseller_user')->selectRaw('id,name,billable,package_list,reseller_type,remark,address,contact');

        if (auth()->user()->hasRole(['Reseller Admin', 'Reseller', 'Reseller Technician', 'Sub Reseller', 'Sub Reseller Technician'])) {
            $resellers->whereHas('reseller_user', function ($q) {
                return $q->where('user_id', auth()->user()->id);
            });
        }

        $reseller =    $resellers->orderBy('name', 'asc')->get();


        return $reseller;
    }


    static function resellerList()
    {

        $resellers = Reseller::with('balance', 'reseller_user')->selectRaw('id,name,billable,package_list,reseller_type,remark,status,address,contact,manager_unique_code,enable_online_recharge,vat,commission_percentage,sms_gateway_type');

        if (auth()->user()->hasRole(['Reseller Admin', 'Reseller', 'Reseller Technician', 'Sub Reseller', 'Sub Reseller Technician'])) {
            $resellers->whereHas('reseller_user', function ($q) {
                return $q->where('user_id', auth()->user()->id);
            });
        }

        return $resellers->orderBy('name', 'asc');
    }

    public function resellerSmsGateway()
    {
        return $this->hasOne(ResellerSmsGetway::class, 'reseller_id');
    }
}
