<?php

namespace Workdo\MobileServiceManagement\DataTables;

use Illuminate\Database\Eloquent\Builder as QueryBuilder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Yajra\DataTables\EloquentDataTable;
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;

use Workdo\MobileServiceManagement\Entities\MobileService;

class MobileServiceDataTable extends DataTable
{
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        $rowColumn = ['icon', 'category', 'expected_price', 'expected_duration', 'is_active', 'show_in_expertise', 'show_in_footer'];

        $dataTable = (new EloquentDataTable($query))
            ->addIndexColumn()
            ->editColumn('icon', function (MobileService $data) {
                return '<i class="' . $data->icon . ' fs-4"></i>';
            })
            ->editColumn('category', function (MobileService $data) {
                return $data->category ? $data->category->category_name : '-';
            })
            ->editColumn('expected_price', function (MobileService $data) {
                return currency_format_with_sym($data->expected_price);
            })
            ->editColumn('is_active', function (MobileService $data) {
                $class  = $data->is_active ? 'bg-success' : 'bg-danger';
                $status = $data->is_active ? 'Active' : 'Inactive';
                return '<span class="badge fix_badge ' . $class . ' p-2 px-3">' . $status . '</span>';
            })
            ->filterColumn('is_active', function ($query, $keyword) {
                if (stripos('Inactive', $keyword) !== false) {
                    $query->where('is_active', false);
                } elseif (stripos('Active', $keyword) !== false) {
                    $query->orWhere('is_active', true);
                }
            })
            ->editColumn('show_in_expertise', function (MobileService $data) {
                $class  = $data->show_in_expertise ? 'bg-success' : 'bg-secondary';
                $status = $data->show_in_expertise ? 'Yes' : 'No';
                return '<span class="badge fix_badge ' . $class . ' p-2 px-3">' . $status . '</span>';
            })
            ->filterColumn('show_in_expertise', function ($query, $keyword) {
                if (stripos('No', $keyword) !== false) {
                    $query->where('show_in_expertise', false);
                } elseif (stripos('Yes', $keyword) !== false) {
                    $query->orWhere('show_in_expertise', true);
                }
            })
            ->editColumn('show_in_footer', function (MobileService $data) {
                $class  = $data->show_in_footer ? 'bg-success' : 'bg-secondary';
                $status = $data->show_in_footer ? 'Yes' : 'No';
                return '<span class="badge fix_badge ' . $class . ' p-2 px-3">' . $status . '</span>';
            })
            ->filterColumn('show_in_footer', function ($query, $keyword) {
                if (stripos('No', $keyword) !== false) {
                    $query->where('show_in_footer', false);
                } elseif (stripos('Yes', $keyword) !== false) {
                    $query->orWhere('show_in_footer', true);
                }
            });

        if (
            \Laratrust::hasPermission('mobileservice_service show') ||
            \Laratrust::hasPermission('mobileservice_service edit') ||
            \Laratrust::hasPermission('mobileservice_service delete')
        ) {
            $dataTable->addColumn('action', function (MobileService $data) {
                return view('mobile-service-management::services.action', compact('data'));
            });
            $rowColumn[] = 'action';
        }

        return $dataTable->rawColumns($rowColumn);
    }

    public function query(MobileService $model): QueryBuilder
    {
        return $model->with('category')
            ->where('mobile_services.created_by', creatorId())
            ->where('mobile_services.workspace', getActiveWorkSpace());
    }

    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        $dataTable = $this->builder()
            ->setTableId('mobile-service-table')
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->orderBy(0)
            ->language([
                "paginate"          => [
                    "next"     => '<i class="ti ti-chevron-right"></i>',
                    "previous" => '<i class="ti ti-chevron-left"></i>'
                ],
                'lengthMenu'        => "_MENU_" . __('Entries Per Page'),
                "searchPlaceholder" => __('Search...'),
                "search"            => "",
                "info"              => __('Showing _START_ to _END_ of _TOTAL_ entries')
            ])
            ->initComplete('function() {
                var table = this;
                var searchInput = $(\'#\'+table.api().table().container().id+\' label input[type="search"]\');
                searchInput.removeClass(\'form-control form-control-sm\');
                searchInput.addClass(\'dataTable-input\');
                var select = $(table.api().table().container()).find(".dataTables_length select").removeClass(\'custom-select custom-select-sm form-control form-control-sm\').addClass(\'dataTable-selector\');
            }');

        $exportButtonConfig = [
            'extend'    => 'collection',
            'className' => 'btn btn-light-secondary dropdown-toggle',
            'text'      => '<i class="ti ti-download me-2" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Export"></i>',
            'buttons'   => [
                [
                    'extend'        => 'print',
                    'text'          => '<i class="fas fa-print me-2"></i> ' . __('Print'),
                    'className'     => 'btn btn-light text-primary dropdown-item',
                    'exportOptions' => ['columns' => [0, 1, 3]],
                ],
                [
                    'extend'        => 'csv',
                    'text'          => '<i class="fas fa-file-csv me-2"></i> ' . __('CSV'),
                    'className'     => 'btn btn-light text-primary dropdown-item',
                    'exportOptions' => ['columns' => [0, 1, 3]],
                ],
                [
                    'extend'        => 'excel',
                    'text'          => '<i class="fas fa-file-excel me-2"></i> ' . __('Excel'),
                    'className'     => 'btn btn-light text-primary dropdown-item',
                    'exportOptions' => ['columns' => [0, 1, 3]],
                ],
            ],
        ];

        $buttonsConfig = [
            $exportButtonConfig,
            [
                'extend'    => 'reset',
                'className' => 'btn btn-light-danger',
            ],
            [
                'extend'    => 'reload',
                'className' => 'btn btn-light-warning',
            ],
        ];

        $dataTable->parameters([
            "dom"          => "
        <'dataTable-top'<'dataTable-dropdown page-dropdown'l><'dataTable-botton table-btn dataTable-search tb-search  d-flex justify-content-end gap-2'Bf>>
        <'dataTable-container'<'col-sm-12'tr>>
        <'dataTable-bottom row'<'col-5'i><'col-7'p>>",
            'buttons'      => $buttonsConfig,
            "drawCallback" => 'function( settings ) {
                var tooltipTriggerList = [].slice.call(
                    document.querySelectorAll("[data-bs-toggle=tooltip]")
                );
                var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                    return new bootstrap.Tooltip(tooltipTriggerEl);
                });
                var popoverTriggerList = [].slice.call(
                    document.querySelectorAll("[data-bs-toggle=popover]")
                );
                var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
                    return new bootstrap.Popover(popoverTriggerEl);
                });
                var toastElList = [].slice.call(document.querySelectorAll(".toast"));
                var toastList = toastElList.map(function (toastEl) {
                    return new bootstrap.Toast(toastEl);
                });
            }'
        ]);

        $dataTable->language([
            'buttons' => [
                'create' => __('Create'),
                'export' => __('Export'),
                'print'  => __('Print'),
                'reset'  => __('Reset'),
                'reload' => __('Reload'),
                'excel'  => __('Excel'),
                'csv'    => __('CSV'),
            ]
        ]);

        return $dataTable;
    }

    public function getColumns(): array
    {
        $column = [
            Column::make('id')->searchable(false)->visible(false)->exportable(false)->printable(false),
            Column::make('No')->title(__('No'))->data('DT_RowIndex')->name('DT_RowIndex')->searchable(false)->orderable(false),
            Column::make('icon')->title(__('Icon'))->orderable(false)->width(60),
            Column::make('name')->title(__('Name')),
            Column::make('category')->title(__('Category'))->name('category.category_name'),
            Column::make('expected_price')->title(__('Expected Price')),
            Column::make('expected_duration')->title(__('Expected Duration'))->orderable(false),
            Column::make('is_active')->title(__('Status')),
            Column::make('show_in_expertise')->title(__('Expertise')),
            Column::make('show_in_footer')->title(__('Footer')),
        ];

        if (
            \Laratrust::hasPermission('mobileservice_service show') ||
            \Laratrust::hasPermission('mobileservice_service edit') ||
            \Laratrust::hasPermission('mobileservice_service delete')
        ) {
            $action = [
                Column::computed('action')
                    ->title(__('Action'))
                    ->exportable(false)
                    ->printable(false)
                    ->addClass('text-end')
                    ->width(60),
            ];
            $column = array_merge($column, $action);
        }

        return $column;
    }

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