<?php

namespace App\Datatables\Admin\Shop;

use App\Datatables\ParentDataTable as DataTable;
use App\Models\Shop\Delivery;
use Yajra\DataTables\Html\Column;

class DeliveriesDataTable extends DataTable
{
    public $model_name = 'deliveries';

    public function query(Delivery $model)
    {
        $model = $model->with('sale_channel');
        $model = self::filterBySaleChannel($model);

        return $this->buildQuery($model);
    }

    public static function filterBySaleChannel($model, $sale_channel_id = false)
    {
        $sale_channel_id = $sale_channel_id ? $sale_channel_id : self::isFilteredByField('sale_channel_id');

        return $sale_channel_id ? $model->bySaleChannel($sale_channel_id) : $model;
    }

    public function modifier($datatables)
    {
        $datatables
            ->editColumn('active', function (Delivery $delivery) {
                return view('components.form.toggle', [
                    'value' => $delivery->active,
                    'on' => __('active'),
                    'off' => __('inactive'),
                    'meta' => 'data-id='.$delivery->id,
                    'size' => 'xs',
                ]);
            })
            ->editColumn('is_public', function (Delivery $delivery) {
                return $delivery->is_public ? "<i class='fa fa-check secondary'></i>" : '';
            })
            ->editColumn('at_house', function (Delivery $delivery) {
                return $delivery->at_house ? "<i class='fa fa-check secondary'></i>" : '';
            })
            ->editColumn('address', function (Delivery $delivery) {
                return $delivery->address.' '.$delivery->zipcode.' '.$delivery->city;
            })
            ->rawColumns(['active', 'is_public', 'at_house', 'address', 'action']);

        return parent::modifier($datatables);
    }

    protected function getColumns()
    {
        return [
            Column::make('active')->title(__('active'))->width(60)->class('text-center'),
            Column::make('is_public')->title(__('Public'))->width(60)->class('text-center'),
            Column::make('at_house')->title(__('Défaut'))->width(60)->class('text-center'),
            Column::make('name')->title('Nom'),
            Column::make('sale_channel.name')->title(__('shop.sale_channels.name')),
            Column::make('address')->title('Adresse')->searchable(false),
            $this->makeColumnButtons(),
        ];
    }
}
