<?php

namespace App\DataTables\Orders;


use App\Models\OrderManagement\Order;
use App\Models\SettingManagement\Status;
use Illuminate\Database\Eloquent\Builder as QueryBuilder;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\HtmlString;
use Yajra\DataTables\DataTableAbstract;
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\QueryDataTable;
use Yajra\DataTables\Services\DataTable;


class OrderDataTable extends DataTable{

    protected $columns;
    protected $ajax;
    protected $table_id;
    public function __construct($params = [])  {
        parent::__construct();

        $this->columns = $params['columns'] ?? [];
        $this->ajax = $params['ajax'] ?? route("admin.orders.index");
        $this->table_id = $params['table_id'] ?? "table-orders";

    }


    /**Build DataTable class.
     * @param QueryBuilder $query Results from query() method.
     * @return DataTableAbstract|EloquentDataTable|QueryDataTable
     * @throws \Exception
     */
    public function dataTable(QueryBuilder $query){
        return (new EloquentDataTable($query))

                ->addColumn('status_badge', function ($row){
                    $order = $row;
                    $statusId = $order->status_code;
                    $nextStatuses = Status::where("code","<>" ,$statusId)->get();

                    $paidStatus = Status::find(Status::PAID);

                    $rejectedStatuses = Order::getStatusesNotModifiables();
                    //si "rejeté" n'est pas parmis les status
                    if(!$nextStatuses->contains("id",Status::CANCELED) and $statusId != Status::CANCELED){
                        $canceledStatus = Status::find(Status::CANCELED);
                        $nextStatuses->add($canceledStatus);
                    }
                    return view('backend.orders.blocs.dt-action-set-status',
                        compact("order","nextStatuses","rejectedStatuses","paidStatus"));
                })
                ->addColumn('link_ref_id', function ($row){
                    return new HtmlString("<span class='cursor-pointer text-underline text-success btn-action-click'>
                                                     $row->ref_id
                                                </span>");
//                    return view('backend.orders.blocs.dt-link-ref-id',compact("row"));
                })
                ->addColumn('link_customer_id', function ($row){
                    return view('backend.orders.blocs.dt-link-customer-id',['user' => $row->customer]);
                })
                ->addColumn('pos', function ($row){
                    return $row?->billingDesk?->name ?? "---";
                })
                ->editColumn('created_at', function ($row){
                    return format_date($row->created_at,__("d-m-Y H:i:s"));
                })
                ->editColumn('customer', function ($row){
                    return $row->customer->only('id',"name","fullName");
                })
//                ->editColumn('status_badge', function ($row){
//                    return $row->status->badge_label ?? "--" ;
//                })
                ->editColumn('status', fn ($row) => $row->status->only('code',"name","badge_dot","badge_label"))
                ->addColumn('formated_status', fn ($row) => new HtmlString($row->status->badge_label))
                ->editColumn('created_by', function ($row){
                    return $row->createdBy->fullName ?? "";
                })
                ->addColumn('formated_subtotal', fn ($row)=>format_amount($row->subtotal,$row->currency()) )
                ->addColumn('formated_discount', fn ($row)=>format_amount($row->discount,$row->currency()) )
                ->addColumn('formated_tax', fn ($row)=>format_amount($row->tax,$row->currency()) )
                ->addColumn('formated_shipping', fn ($row)=>format_amount($row->shipping,$row->currency()) )
                ->addColumn('formated_total', fn ($row)=>format_amount($row->total,$row->currency()) )

                ->rawColumns(['status_badge'])
                //->make(true)

            ;
    }

    /**Get query source of dataTable.
     * @param Order $model
     * @return QueryBuilder
     */
    public function query(Order $model){
        return $model->newQuery()
                    ->with(["status","customer","billingDesk","warehouse","paymentUsages","items"])
                    ->latest();
    }


    public function html(){

       // $statuses = Order::getStatuses()->pluck('code')->toArray();

//        {{--title: "<center style='text-decoration: underline'>{{__('Liste des virements à valider du :date',['date' => date('d-m-Y')])}}</center>",--}}
//        {{--exportOptions: {--}}
//            {{--columns: [ 1,2,3,4,5,8 ]--}}
//            {{--},--}}

        $d = "append_dt_footer('$this->table_id')";
        $cell = '<th class="total fs-14 border">ATSFsfs</th>';

        return $this->builder()
            ->setTableId($this->table_id)
            ->columns($this->getColumns())
            ->select(['enable' => false,'style' => 'os' ,"selector" => 'td:first-child',"multi" => false])
            ->addTableClass('table-striped')
            ->setTableAttribute("style", "width:100%;")
            ->minifiedAjax($this->ajax)
            ->dom('Bfrtipl')
            // ->orderBy(1)
            ->buttons($this->getButtons())
            ->parameters([
               "searchPane" => ['controls' => false],
               "scrollY" => 'fixedHeader',
               "fixedHeader" => ['header' => false , "footer" => true],
               "drawCallback" => "function() {

                      const api = this.api();
                      const table = api.table(); // Datatable
                      const datas = api.ajax.json().data; // les données
                      if (datas.length){
                            //addTfooter('$this->table_id')
                            const jQtable = table.tables().nodes().to$(); // converti en dom Jquery
                            jQtable.find('tfoot').show()
                            const first = datas[0];
                            const currency = (typeof first === 'object' && 'currency' in first)
                                             ? first.currency : '';
                            const totals_columns = [
                                { name : 'subtotal' , value : getSum(datas,'subtotal')},
                                { name : 'discount' , value : getSum(datas,'discount')},
                                { name : 'tax' , value : getSum(datas,'tax')},
                                { name : 'shipping' , value : getSum(datas,'shipping')},
                                { name : 'total' , value : getSum(datas,'total')},
                            ];

                            //let columnsCount = table.columns().nodes().length;
                            //let visible_columns = table.columns(':visible').nodes();
                            if(totals_columns.length && 1=== 2) {
                                totals_columns.forEach((item,i)=>{
                                    const column = table.column(item.name+':name',{page : 'current'});
                                    const cells = column.nodes().to$();
                                    //const td = jQuery(column.footer()).addClass('text-green');
                                     console.log(cells);
                                    cells.append('$cell')
                                    console.log(cells.length);
                                    const td = cells.find('th.total:first-child');

                                    td.addClass('text-green');
                                    td.text(formatNumber(arround(item.value,2),currency))
                                })
                            }

                            table.columns.adjust()

                        }else{

                        }

                }",
                "footerCallback" => "function(row, data, start, end, display) {

                 console.log('footer')
                // console.log(row,data,start,end,display)

                    let sumdef, sumcol;
                    let api = this.api();
                    let int_val = function(i) {
                        if (typeof i === 'string') {
                            return i.replace(/[\$,]/g,'') * 1;
                        }
                        if (typeof i === 'number') {
                            return i;
                        }
                        return 0;
                    };
                    let reduction = function(a,b) {
                        return int_val(a) + int_val(b);
                    };

                }",
            ])

            ;
    }

    protected function getColumns() :array {
        return [

            Column::make('ref_id')
                ->title(__("Id"))
                ->data('link_ref_id')
                ->searchable(true)
//                ->printable(true)
                ->orderable(false)
                ->footer(__("Id")),

            Column::make("customer")
                ->title(__('Customer'))
                ->data("link_customer_id")
                ->searchable(false)
                ->orderable(false)
                ->footer(__("Customer")) ,

            Column::make("subtotal")
                ->title(__('SubTotal'))
                ->data("formated_subtotal")
                ->searchable(true)
                ->orderable(false)
                ->visible(false)
                ->footer(__("SubTotal"))
            ,

            Column::make(__('Discount Code'),"discount_code")
                ->searchable(true)
                ->orderable(false)
                ->visible(false)
                ->data("discount_code")
                ->footer(__('Discount Code')),

              Column::make("discount")
                  ->title(__('Discount'))
                  ->data("formated_discount")
                  ->searchable(true)
                  ->orderable(true)
                  ->visible(false)
                  ->footer(__("Discount"))
            ,

            Column::make("tax")
                  ->title(__('Tax'))
                  ->data("formated_tax")
                  ->searchable(true)
                  ->orderable(true)
                  ->visible(false)
                  ->footer(__("Tax"))
            ,
            Column::make("shipping")
                  ->title(__('Shipping'))
                  ->data("formated_shipping")
                  ->searchable(true)
                  ->orderable(true)
                  ->visible(false)
                  ->footer(__("Shipping"))
            ,
            Column::make("total")
                ->title(__('Total'))
                ->data("formated_total")
                ->searchable(true)
                ->orderable(false)
                ->footer(__("Total"))
            ,
            Column::make("status")
                ->title(__('Status'))
                ->data("formated_status")
                ->searchable(false)
                ->orderable(false)
                ->footer(__("Status")),

            Column::make("status_code")
                ->title(__('Status Code'))
                ->data("status_code")
                ->searchable(true)
                ->orderable(false)
                ->visible(false)
                ->footer(__("Status Code")),

            Column::make("billing_desk")
                ->title(__('Billing Desk'))
                ->data("pos")
                ->searchable(false)
                ->orderable(false)
                ->footer(__("Point Of Sale")),

            Column::make(__('Period'),"period")
                ->searchable(true)
                ->orderable(true)
                ->visible(false)
                ->data("period")
                ->footer(__('Period')),

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

            Column::make(__('By'),"created_by")
                    ->searchable(false)
                    ->orderable(false)
                    ->visible(false)
                    ->data("created_by")
                    ->footer(__('By')),

//            Column::computed('action')
//                ->searchable(false)
//                ->exportable(false)
//                ->printable(false)
//                ->width(60)
//                ->addClass('text-center'),
        ];
    }

    protected function getButtons(){
        $user = auth(activeGuard())->user();
        $buttons = [];
        $buttons[] = Button::make('reload');
        $buttons[] = Button::make('filters');
        $buttons[] = Button::make('export');
        $buttons[] = Button::make('colvis');

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

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

    }

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

    }

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

    }
}
