<?php

namespace Ignite\Core\Models\Grid;

use Ignite\Core\Entities\Report;
use Yajra\DataTables\DataTables;
use Yajra\DataTables\Services\DataTable;

class ReportTable extends DataTable
{
    /** @var DataTables */
    protected $datatables;

    /** @var ReportFormatter */
    protected $formatter;

    /**
     * BlockTable constructor.
     *
     * @param DataTables      $datatables
     */
    public function __construct(DataTables $datatables)
    {
    	$this->datatables = $datatables;
        $this->formatter = new ReportFormatter();
    }

    /**
     * The columns to show.
     *
     * @return array
     */
    protected function getColumns()
    {
        return [
            'action' => [
                'title' => 'Actions',
                'searchable' => false,
                'orderable' => false,
                'exportable' => false,
                'printable' => false,
            ],
            'name' => [
                'title' => 'Name',
                'searchable' => true,
                'orderable' => true,
                'exportable' => true,
                'printable' => true,
            ],
            'status' => [
                'title' => 'Status',
                'searchable' => true,
                'orderable' => true,
                'exportable' => true,
                'printable' => true,
            ],
            'created_at' => [
                'title' => 'Created Date',
                'searchable' => true,
                'orderable' => true,
                'exportable' => true,
                'printable' => true,
            ]
        ];
    }

    /**
     * Render the table as HTML.
     *
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    {
        $columns = $this->getColumns();

        if (auth()->user()->cannot('core.report.view')) {
            unset($columns['action']);
        }

        return $this->builder()->columns($columns);
    }

    /**
     * Get the table data.
     *
     * @return \Yajra\DataTables\DataTableAbstract|\Yajra\DataTables\EloquentDataTable
     */
    public function dataTable()
    {
        $table = $this->datatables->eloquent($this->query());

        if (auth()->user()->can('core.report.view')) {
            $table->addColumn('action', [$this->formatter, 'actions'], 0);
        }

        $table->editColumn('status', [$this->formatter, 'status'])
            ->editColumn('created_at', [$this->formatter, 'createdAt'])
            ->editColumn('published_at', [$this->formatter, 'publishedAt']);

        return $table;
    }

    /**
     * The table query.
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query()
    {
        return $this->applyScopes(
            Report::query()
        );
    }
}
