<?php

namespace Modules\Contracts\Http\Livewire;

use Livewire\Component;
use Modules\Main\Models\Agent\Agent;
use Modules\Contracts\Models\Contract;
use Modules\Contracts\Models\ContractStatus;
use Modules\User\Models\UserRole;
use Modules\User\Models\Role;
use Modules\CityManager\Models\CityManager;
use Modules\Main\Models\Company\CompanyAdmin;

class ContractsTableLivewire extends Component
{
    public $mode = false;
    public $filter = [];
    public function mount()
    {

    }
    /**
     * Get array of available agents ids
     * @return array
     */
    function getSelectingAgents()
    {
        if($cityManager = CityManager::where('user_id', auth()->id())->first()) {
            return $agentsIds = Agent::whereIn('company_id',$cityManager->city->companies->pluck('id'))->pluck('id');
        }
        elseif ($company = AdminCompanyOfUser())
        {
            $companyAdmin = CompanyAdmin::where('user_id', auth()->id())->first();
            return $agentsIds = Agent::where('company_id',$company->id)->pluck('id');
        }
        elseif ($agent = Agent::where('user_id', auth()->id())->first())
        {
            return [$agent->id];
        }
        return [];
    }

    private function getContracts()
    {
        $contracts = Contract::whereHas('deal', function ($dealSubQuery)
        {
            $dealSubQuery->with('deals')
                ->whereIn('agent_id', $this->getSelectingAgents());
        });
        $this->appendMode($contracts);
        $this->appendFilter($contracts);

        return $contracts->get();
    }

    public function render()
    {
        return view('contracts::livewire.table.index', [
            'contracts' => $this->getContracts(),
            'statuses'  => ContractStatus::class
        ]);
    }

    /* ДАЛЕЕ - методы для применения всяких фильтров */
    private function appendMode(&$query)
    {
        if ($this->mode == 'active')
        {
            $query->whereIn('status', [
                ContractStatus::NEW ,
                ContractStatus::IN_WORK,
                ContractStatus::RESERVATION,
                //ContractStatus::SUCCESS,
            ]);
        }
        if ($this->mode == 'successed')
        {
            $query->whereIn('status', [
                ContractStatus::SUCCESS,
                ContractStatus::TREATY
            ]);
        }
        if ($this->mode == 'declined')
        {
            $query->whereIn('status', [
                ContractStatus::DECLINE
            ]);
        }
    }
    private function appendFilter(&$query)
    {
        foreach ($this->filter as $fKey => $fValue)
        {
            if (is_array($fValue))
            {
                $query->whereIn($fKey, $fValue);
            }
            else
            {
                $query->where($fKey, $fValue);
            }
        }
    }

}