<?php
namespace ModulesGarden\ProxmoxAddon\App\UI\IpLog\Pages;

use ModulesGarden\ProxmoxAddon\App\Models\IpLog;
use ModulesGarden\ProxmoxAddon\App\UI\IpLog\Buttons\DeleteButton;
use ModulesGarden\ProxmoxAddon\App\UI\IpLog\Buttons\DeleteMassButton;
use ModulesGarden\ProxmoxAddon\Core\Models\Whmcs\Client;
use ModulesGarden\ProxmoxAddon\Core\Models\Whmcs\Hosting;
use ModulesGarden\ProxmoxAddon\Core\UI\Interfaces\AdminArea;
use ModulesGarden\ProxmoxAddon\Core\UI\Widget\DataTable\Column;
use ModulesGarden\ProxmoxAddon\Core\UI\Widget\DataTable\DataProviders\Providers\QueryDataProvider;
use ModulesGarden\ProxmoxAddon\Core\UI\Widget\DataTable\DataTable;

/**
 * Description of ServersDataTable
 *
 * @author Pawel Kopec <pawelk@modulesgardne.com>
 */
class IpLogDataTable extends DataTable implements AdminArea
{

    public function initContent()
    {
        $this->initIds('ipLog');
        $this->title = null;
        $this->addActionButton(new DeleteButton());
        $this->addMassActionButton(new DeleteMassButton);
    }

    protected function loadHtml()
    {
        $i = (new IpLog())->getTable();
        $h = (new Hosting)->getTable();
        $c = (new Client())->getTable();
        $this->addColumn((new Column('id', $i))->setSearchable(true, Column::TYPE_INT)->setOrderable('DESC'))
            ->addColumn((new Column('message', $i))->setSearchable(true, Column::TYPE_STRING)->setOrderable())
            ->addColumn((new Column('domain', $h))->setSearchable(true, Column::TYPE_STRING)->setOrderable())
            ->addColumn((new Column('firstname', $c))->setSearchable(true, Column::TYPE_STRING)->setOrderable())
            ->addColumn((new Column('created_at', $i))->setSearchable(true, Column::TYPE_DATE)->setOrderable());
    }

    public function replaceFieldDomain($key, $row)
    {
        if ($row->domain)
        {
            return sprintf('<a href="clientsservices.php?userid=%s&id=%s"> %s</a>', $row->userid, $row->hosting_id, $row->domain);
        }
        return sprintf('<a href="clientsservices.php?userid=%s&id=%s"> %s</a>', $row->userid, $row->hosting_id, $row->hosting_id);
    }

    public function replaceFieldFirstname($key, $row)
    {
        return sprintf('<a href="clientssummary.php?userid=%s">%s %s</a>', $row->userid, $row->firstname, $row->lastname);
    }

    protected function loadData()
    {
        $i = (new IpLog())->getTable();
        $h = (new Hosting)->getTable();
        $c = (new Client())->getTable();
        $query    = (new IpLog())
            ->query()
            ->getQuery()
            ->leftJoin($h, "{$i}.hosting_id", '=', "{$h}.id")
            ->leftJoin($c, "{$h}.userid", '=', "{$c}.id")
            ->select("{$i}.*", "{$h}.domain", "{$h}.userid",  "{$c}.firstname", "{$c}.lastname");
        $dataProv = new QueryDataProvider();
        $dataProv->setDefaultSorting("id", 'DESC');
        $dataProv->setData($query);
        $this->setDataProvider($dataProv);
    }
}
