<?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\MobileServicePolicy;

class MobileServicePolicyDataTable extends DataTable
{
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        $rowColumn = ['response_time', 'resolution_time', 'description'];

        $dataTable = (new EloquentDataTable($query))
            ->addIndexColumn()
            ->editColumn('response_time', function (MobileServicePolicy $mobileservice_policy) {
                return company_Time_formate($mobileservice_policy->response_time);
            })
            ->editColumn('resolution_time', function (MobileServicePolicy $mobileservice_policy) {
                return company_Time_formate($mobileservice_policy->resolution_time);
            })
            ->editColumn('description', function (MobileServicePolicy $mobileservice_policy) {
                $url  = route('mobileservice-policy.description', $mobileservice_policy->id);
                $html = '<a class="action-item" data-url="' . $url . '" data-ajax-popup="true" data-bs-toggle="tooltip" title="' . __('Description') . '" data-title="' . __('Description') . '"><i class="fa fa-comment"></i></a>';
                return $html;
            })
            ->filterColumn('response_time', function ($query, $keyword) {
                try {
                    $timeWithoutPeriod = preg_replace('/\s?(AM|PM)/i', '', $keyword);

                    if (preg_match('/^\d{1,2}:\d{2}$/', $timeWithoutPeriod)) {
                        return $query->whereRaw("DATE_FORMAT(response_time, '%h:%i') LIKE ?", ["%$timeWithoutPeriod%"]);
                    } elseif (preg_match('/^\d{1,2}$/', $timeWithoutPeriod)) {
                        return $query->whereRaw("DATE_FORMAT(response_time, '%h') LIKE ?", ["%$timeWithoutPeriod%"]);
                    } elseif (preg_match('/^\d{1,2}:\d{2}\s?(AM|PM)$/i', $keyword)) {
                        return $query->whereRaw("DATE_FORMAT(response_time, '%h:%i %p') LIKE ?", ["%$keyword%"]);
                    }
                } catch (\Exception $e) {
                    \Log::error('Invalid time format: ' . $keyword);
                }
            })
            ->filterColumn('resolution_time', function ($query, $keyword) {
                try {
                    $timeWithoutPeriod = preg_replace('/\s?(AM|PM)/i', '', $keyword);

                    if (preg_match('/^\d{1,2}:\d{2}$/', $timeWithoutPeriod)) {
                        return $query->whereRaw("DATE_FORMAT(resolution_time, '%h:%i') LIKE ?", ["%$timeWithoutPeriod%"]);
                    } elseif (preg_match('/^\d{1,2}$/', $timeWithoutPeriod)) {
                        return $query->whereRaw("DATE_FORMAT(resolution_time, '%h') LIKE ?", ["%$timeWithoutPeriod%"]);
                    } elseif (preg_match('/^\d{1,2}:\d{2}\s?(AM|PM)$/i', $keyword)) {
                        return $query->whereRaw("DATE_FORMAT(resolution_time, '%h:%i %p') LIKE ?", ["%$keyword%"]);
                    }
                } catch (\Exception $e) {
                    \Log::error('Invalid time format: ' . $keyword);
                }
            });

        if (
            \Laratrust::hasPermission('mobileservice_policy edit') ||
            \Laratrust::hasPermission('mobileservice_policy delete')
        ) {

            $dataTable->addColumn('action', function (MobileServicePolicy $mobileservice_policy) {
                return view('mobile-service-management::mobileservice-policy.action', compact('mobileservice_policy'));
            });
            $rowColumn[] = 'action';
        }
        return $dataTable->rawColumns($rowColumn);
    }

    /**
     * Get the query source of dataTable.
     */
    public function query(MobileServicePolicy $model): QueryBuilder
    {
        $mobileservice_policy = $model->where('workspace', getActiveWorkSpace())->where('created_by', creatorId());
        return $mobileservice_policy;
    }

    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        $dataTable = $this->builder()
            ->setTableId('mobile_service_policies-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 = array_merge([
            $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;
    }

    /**
     * Get the dataTable columns definition.
     */
    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('policy_name')->title(__('Policy Name')),
            Column::make('response_time')->title(__('Response Time')),
            Column::make('resolution_time')->title(__('Resolution Time')),
            Column::make('description')->title(__('Description')),

        ];
        if (
            \Laratrust::hasPermission('mobileservice_policy edit') ||
            \Laratrust::hasPermission('mobileservice_policy 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 'MobileService_Policies_' . date('YmdHis');
    }
}
