<?php

namespace App\Livewire;

use Livewire\Component;
use Livewire\WithPagination;
use Livewire\WithoutUrlPagination;

use Modules\Main\Models\Agent\Agent;
use Modules\Main\Models\Company\CompanyAdmin;
use App\Models\Deal\Deal;

use App\Models\Deal\DealStatus;

class ContractsTable extends Component
{
    use WithPagination, WithoutUrlPagination;

    public $status;
    public $count;
    public $mode;//short || full

    public function mount($status = null, $count = 10, $mode = 'full')
    {
        $this->status = $status;
        $this->count = $count;
        $this->mode = $mode;
    }

    public function getContracts()
    {
        $deals = false;
        $user = auth()->user();
        if ($agent = Agent::where('user_id', $user->id)->first())
        {
            $deals = Deal::where('agent_id', $agent->id);
        }
        elseif ($admin = CompanyAdmin::where('user_id', $user->id)->first())
        {
            $deals = Deal::whereIn('agent_id', function ($query) use ($admin)
            {
                $query->select('id');
                $query->from('agents');
                $query->where('company_id', $admin->company_id);
            });
        }
        return $deals;
    }
    public function render()
    {
        $deals = $this->getDeals();
        if ($this->status && $this->status == DealStatus::UNIQUE)
        {
            $deals = $deals
                ->whereIn('status', [DealStatus::UNIQUE])
                ->orderBy('id', 'desc')->paginate($this->count, ['*'], 'unique_clients');
        }
        elseif ($this->status && $this->status == DealStatus::NOT_UNIQUE)
        {
            $deals = $deals
                ->whereIn('status', [DealStatus::MODERATION, DealStatus::NEW , DealStatus::NOT_UNIQUE])
                ->orderBy('id', 'desc')->paginate($this->count, ['*'], 'not_unique_clients');
        }
        else
        {
            $deals = $deals->orderBy('id', 'desc')->paginate($this->count, ['*'], 'all_clients');
        }
        ;

        return view(
            'livewire.clients-table',
            [
                'deals'    => $deals,
                'statuses' => DealStatus::class
            ]
        );
    }
}
