<?php

namespace App\DataTables\Payments;

use App\Models\PaymentManagement\Payment;
use App\Models\PaymentManagement\PaymentMethod;
use App\Models\UserManagement\Customer;
use App\Models\UserManagement\User;
use Illuminate\Database\Eloquent\Builder as QueryBuilder;
use Yajra\DataTables\EloquentDataTable;
use Yajra\DataTables\Exceptions\Exception;
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\Html\Editor\Fields\Options;
use Yajra\DataTables\Services\DataTable;


class PaymentDataTable extends DataTable{

    //Export Columns with Custom Title
//    protected array|string $exportColumns = [
//        ['data' => 'name', 'title' => 'Name'],
//        ['data' => 'email', 'title' => 'Registered Email'],
//    ];
//
//    protected array $excludeFromPrint = [
//        "action"
//    ];



    /**Build DataTable class.
     * @param QueryBuilder $query Results from query() method.
     * @return EloquentDataTable
     */
    public function dataTable(QueryBuilder $query){
        return (new EloquentDataTable($query))
               // ->addColumn('action', '')
               ->addColumn('actions', function ($row){
                   $permissions = [];
                   $permissions['edit'] =  "payment-update";
                  // $permissions['remove'] =  "payment-delete";
                   return view('shared.datatable-column-actions',compact("permissions"));
               })
                ->addColumn('formated_paid_amount', function ($row){
                    return format_amount($row->paid_amount,true);
                })
                ->addColumn('formated_remaining_amount', function ($row){
                    return format_amount($row->remaining_amount,true);
                })
               ->addColumn('formated_paid_at', function ($row){
                    return format_date($row->paid_at);
                })
                ->editColumn('created_at', function ($row){
                    return format_date( $row->created_at,__("Y-m-d H:i:s"));
                })
                ->editColumn('payer', function ($row){
                    return (filled($row->payer))  ? $row->payer->only('id',"full_name","email") : [];
                })
                ->editColumn('method', function ($row){
                    return $row->method->only('id',"name","code","image");
                })
//                ->editColumn('created_by', function ($row){
//                    return $row->createdBy->fullName ?? "";
//                })
                ->setRowId('id')
            ;
    }

    /**Get query source of dataTable.
     * @param Payment $model
     * @return QueryBuilder
     */
    public function query(Payment $model){
        return $model->newQuery()
                    ->with(["method",'payer'])
                    ->when($this->request->filled("payment_method_id"),function ($query){
                        return $query->where("payment_method_id",$this->request->get("payment_method_id"));
                    })
                    ->latest();
    }


    public function html(){

        return $this->builder()
            ->setTableId('payments-table')
            ->columns($this->getColumns())
            ->select(['enable' => true,'style' => 'os' ,"selector" => 'td:first-child',"multi" => true])
            ->addTableClass('table-striped')
            ->setTableAttribute("style", "width:100%;")
            ->minifiedAjax(route("admin.payments.dt-list"))
            ->dom('Bfrtipl')
            // ->orderBy(1)
            ->buttons($this->getButtons())
            ->editor(
                Editor::make("editor")
                    ->idSrc("id")
                    ->fields([
                        Fields\Select::make('payment_method_id',__('Payment Method'))
                            ->options(PaymentMethod::all()->pluck('id',"name"))
                            ->attr("data-plugin-multiselect","")
                            ->data('payment_method_id'),

                        Fields\Text::make('provider_reference',__("Reference"))->data('provider_reference'),

//                        Fields\Image::make('image',__('Image'))->data('image'),

                       // Fields\Hidden::make('payer_type',__("Payer Type"))->data('payer_type'),
                        Fields\Select::make('payer_id',__('Payer'))
                            ->options(Customer::active()->get()->pluck('id',"full_name"))
                            ->attr("data-plugin-multiselect","")
                            ->data('payer_id'),

                        Fields\Text::make('payer_number',__("Payer Number"))->data('payer_number'),

                        Fields\DateTime::make('paid_at',__("Paid At"))
//                            ->attr("data-plugin-datepicker","")
//                            ->attr("data-plugin-options",'{ format:"dd-mm-yyyy"}')
                            ->attr("readonly","true")
                            ->data('paid_at'),
                        Fields\Number::make('paid_amount',__("Paid Amount"))->data('paid_amount'),
                        Fields\Number::make('remaining_amount',__("Remaining Amount"))->data('remaining_amount'),

                        Fields\Radio::make('visible',__('Visible By customer?'))
                            ->options(Options::yesNo())
                            ->data('visible') ,

//                        Fields\Image::make('image',__('Image'))
//                            ->defaultContent('No Image')
//                            ->upload(public_path())
//                            ->data('image') ,

                    ])
                    ->ajax([
                        "url" => route('admin.payments.dt-edit'),
                        "type" => "post"
                    ])
            );
    }

    protected function getColumns() :array {
        return [
            Column::computed("")
                ->title("<input type='checkbox' class='dt-checkbox-all' onclick='select_all_td()'/>")
                ->exportable(false)
                ->printable(false)
                ->className("select-checkbox")
                ->content("")
                ->width(10)
                ->data(""),

            Column::make('payment_method')
                ->title(__("Payment Method"))
                ->data('method.name')
                ->searchable(false)
                ->orderable(true)
                ->footer(__("Payment Method")),

            Column::make('provider_reference')
                ->title(__("Reference"))
                ->data('provider_reference')
                ->searchable(true)
                ->orderable(true)
                ->footer(__("Reference")),


            Column::make("payer_id")
                ->title(__('Payer'))
                ->data("payer.full_name")
                ->searchable(false)
                ->orderable(false)
                ->footer(__("Payer")) ,

            Column::make("payer_number")
                ->title(__('Payer Number'))
                ->data("payer_number")
                ->addClass("right")
                ->searchable(true)
                ->orderable(false)
                ->footer(__("Payer Number")) ,

            Column::make("paid_amount")
                ->title(__('Paid Amount'))
                ->data("formated_paid_amount")
                ->addClass("right")
                ->searchable(true)
                ->orderable(false)
                ->footer(__("Paid Amount")) ,

            Column::make("remaining_amount")
                ->title(__('Remaining Amount'))
                ->data("formated_remaining_amount")
                ->addClass("right")
                ->searchable(true)
                ->orderable(false)
                ->footer(__("Remaining Amount")) ,

            Column::make("paid_at")
                ->title(__('Paid At'))
//                ->data("formated_paid_at")
                ->data("paid_at")
                ->footer(__('Paid At')),

            Column::make(__('Created At'),"created_at")
                   ->data("created_at")
                   ->footer(__('Created At')),

//            Column::make(__('Par'),"created_by")
//                   ->data("created_by")
//                   ->footer(__('Par')),

            Column::computed('actions')
                ->exportable(false)
                ->printable(false)
                ->width(60)
                ->addClass('text-center'),

//            [
//                'defaultContent' => '',
//                'data'           => 'action',
//                'name'           => 'action',
//                'title'          => __("Action"),
//                'render'         => null,
//                'orderable'      => false,
//                'searchable'     => false,
//                'exportable'     => false,
//                'printable'      => false,
//                'footer'         => __("Action"),
//            ]
        ];
    }

    protected function getButtons(){
        $user = auth(activeGuard())->user();
        $buttons = [];

        if ($user->can('payment-create')){
            $buttons[] = Button::make('create')->editor("editor");
        }
        $buttons[] = Button::make('reload');
        $buttons[] = Button::make('export');

        return $buttons;
    }
    /**
     * Get filename for export.
     *
     * @return string
     */
    protected function filename() : string{
        return 'Role_file' . date('d-m-Y-H-i-s');
    }

    /**
     * @inheritDoc
     */
    public function excel(){

    }

    /**
     * @inheritDoc
     */
    public function csv(){

    }

    /**
     * @inheritDoc
     */
    public function pdf(){

    }
}
