<?php

namespace App\DataTables;

use App\Models\Area;
use Illuminate\Database\Eloquent\Builder as QueryBuilder;
use Illuminate\Support\Facades\Gate;
use Yajra\DataTables\Html\Builder as HtmlBuilder;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;

class AreaDataTable extends DataTable
{
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query)
    {
        return datatables()
        ->eloquent($query)
            ->addIndexColumn()
            ->editColumn('address',function($row){
                return $row->address ?? "";
            })
            ->editColumn('customers_count',function($row){
                return $row->customer_count;
            })
            ->editColumn('created_at', function ($row) {
                return $row->created_at->format('d-m-Y h:i A');
            })
            ->addColumn('action',function($row){
                $action='<div>';
                    if (Gate::check('area_edit')) {
                        $editIcon = view('components.svg-icon', ['icon' => 'edit'])->render();
                        $action .= '<a href="javascript:void(0)" title="Edit" class="btn btn-icon btn-info edit_area" data-id="'.encrypt($row->id).'" data-address="'.$row->address.'">'.$editIcon.'</a>';
                    }
                    if (Gate::check('area_delete')) {
                        if($row->customer_count == 0){
                            $deleteIcon = view('components.svg-icon', ['icon' => 'delete'])->render();
                            $action .= '<a href="javascript:void(0)" title="Delete" class="btn btn-icon btn-danger delete_area" data-id="'.encrypt($row->id).'">  '.$deleteIcon.'</a>';
                        }
                    }
                $action .='</div>';
                return $action;
            })
            ->filterColumn('created_at', function ($query, $keyword) {
                $query->whereRaw("DATE_FORMAT(areas.created_at,'%d-%M-%Y') like ?", ["%$keyword%"]); //date_format when searching using date
            })
            ->filterColumn('customers_count', function ($query, $keyword) {                
                $keyword = intval($keyword);
                $query->havingRaw('customers_count = ?', [$keyword]);
            })
            ->rawColumns(['action','customers_count']);
    }

    /**
     * Get the query source of dataTable.
     */
    public function query(Area $model): QueryBuilder
    {
        //return $model->newQuery();
        $query = $model->newQuery()->select(['areas.*'])->with(['customers']);
        return $this->applyScopes($query);
    }

    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        return $this->builder()
                    ->setTableId('area-table')
                    ->parameters([
                        'responsive' => false,
                        'pageLength' => 50,
                    ])
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->dom('Bfrtip')
                    ->orderBy(3,'desc')
                    // ->selectStyleSingle()
                    ->buttons([
                        // Button::make('excel'),
                        // Button::make('csv'),
                        // Button::make('pdf'),
                        // Button::make('print'),
                    ]);
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        return [
            Column::make('DT_RowIndex')->title(trans('quickadmin.qa_sn'))->orderable(false)->searchable(false),
            Column::make('address')->title(trans('quickadmin.area_master.fields.name')),
            Column::make('customers_count')->title(trans('quickadmin.area_master.fields.no_of_customer'))->orderable(false),
            Column::make('created_at')->title(trans('quickadmin.order.fields.created_at')),
            Column::computed('action')
            ->exportable(false)
            ->printable(false)
            ->width(60)
            ->addClass('text-center')->title(trans('quickadmin.qa_action')),
        ];
    }

    /**
     * Get the filename for export.
     */
    protected function filename(): string
    {
        return 'Area_' . date('YmdHis');
    }
}
