<?php

namespace App\DataTables\Admin;

use App\Helper\Util;
use App\Models\QaLead;
use Yajra\DataTables\Services\DataTable;
use Yajra\DataTables\EloquentDataTable;

/**
 * Class QaLeadDataTable
 * @package App\DataTables\Admin
 */
class QaLeadDataTable extends DataTable
{
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable($query)
    {
        $dataTable = new EloquentDataTable($query);

        return $dataTable->addColumn('action', 'admin.qa_leads.datatables_actions');
    }

    /**
     * Get query source of dataTable.
     *
     * @param \App\Models\QaLead $model
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query(QaLead $model)
    {
        $model = $model->newQuery();
        if (request()->month != null && request()->month > 0) {
            $month = request()->month;
            $model = $model->whereMonth('created_at', $month);
        }
        if (request()->year != null && request()->year > 0) {
            $model = $model->whereYear('created_at', request()->year);
        }

//        \Log::info("Generated SQL: " . $model->toSql());
        return $model;
    }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    {
        $buttons = [];
        if (\Entrust::can('qa-leads.create') || \Entrust::hasRole('super-admin')) {
            $buttons = ['create'];
        }
        $buttons = array_merge($buttons, [
//            'export',
//            'print',
            'reset',
            'reload',
        ], Util::getFilterByMonth(), Util::getFilterByYear());
        return $this->builder()
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->addAction(['width' => '80px', 'printable' => false])
            ->parameters(array_merge(Util::getDataTableParams(), [
                'dom'     => 'Blfrtip',
                'order'   => [[0, 'desc']],
                'buttons' => $buttons,
            ]));
    }

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {
        return [
            'id',
            'lead_id',
            'payment_id',
            'comments',
            'status',
            'created_at',
            'updated_at'
        ];
    }

    /**
     * Get filename for export.
     *
     * @return string
     */
    protected function filename()
    {
        return 'qa_leadsdatatable_' . time();
    }
}