<?php

namespace Modules\Admin\Http\Livewire;

use Livewire\Component;
use Modules\Main\Models\Company\Company;
use Modules\Main\Models\Complex;
use Modules\Main\Models\Agent\Agent;
class Payments extends Component
{
    public $newValue;
    public $companyId;
    public function mount()
    {

    }

    public function setCompany(Company $company)
    {
        $this->companyId = $company->id;
    }

    public function back()
    {
        $this->companyId = null;
    }

    public function setPaymentValueForCompany(Company $company, Complex $complex)
    {
        $company->setPayment($complex, $this->newValue);
        $this->newValue = null;
    }

    public function unsetPaymentForCompany(Company $company, Complex $complex)
    {
        $company->unsetPayment($complex);
    }

    public function setPaymentValueForAgent(Agent $agent, Complex $complex)
    {
        $agent->setPayment($complex, $this->newValue);
        $this->newValue = null;
    }

    public function setPaymentAsParentForAgent(Agent $agent, Complex $complex)
    {
        $agent->setAsParentPayment($complex);
        $this->newValue = null;
    }

    public function unsetPaymentForAgent(Agent $agent, Complex $complex)
    {
        $agent->unsetPayment($complex);
    }

    public function setPaymentForAllAgentOfCompany(Company $company, Complex $complex)
    {
        $compPayment = $company->getPaymentable($complex);
        $compPayment = $compPayment->value;
        if ($compPayment == null || $compPayment == -1)
        {
            return false;
        }
        $agents = Agent::where('company_id', $company->id)->get();
        foreach ($agents as $agent)
        {
            $agent->setPayment($complex, $compPayment);
        }
    }

    public function render()
    {
        if ($this->companyId)
        {
            return view('admin::payments.agents', [
                'company'   => Company::find($this->companyId),
                'complexes' => Complex::orderBy('name')->get(),
                'agents'    => Agent::where('company_id', $this->companyId)->
                    with([
                        'user' => function ($query)
                        {
                            $query->orderBy('name', 'desc');
                        }
                    ])->get()
            ]);
        }
        else
        {
            return view('admin::payments.companies', [
                'companies' => Company::orderBy('name')->get(),
                'complexes' => Complex::orderBy('name')->get(),
            ]);
        }
    }
}