<?php

namespace App\Datatables\Shop;

use Yajra\DataTables\Html\Column;
use App\Datatables\ParentDataTable as DataTable;
use App\Models\Shop\Offer;
use App\Repositories\Shop\Offers;

class OffersDataTable extends DataTable
{
    public $model_name = 'offers';
    public $sortedColumn = 1;

    public function query(Offer $model)
    {
        $model = $model->with(['article.article_nature', 'variation', 'tariff'])->select($model->getTable() . '.*');
        $model = self::filterByArticleNature($model);
        $model = self::filterByPackage($model);
        return $this->buildQuery($model);
    }

    public static function filterByArticleNature($model, $article_nature_id = false)
    {
        $article_nature_id = $article_nature_id ? $article_nature_id : self::isFilteredByField('article_nature_id');
        return $article_nature_id ? $model->byArticleNature($article_nature_id) : $model;
    }

    public static function filterByPackage($model, $package_id = false)
    {
        $package_id = $package_id ? $package_id : self::isFilteredByField('package_id');
        return $package_id ? $model->byPackage($package_id) : $model;
    }

    public function modifier($datatables)
    {
        $datatables
            ->editColumn('thumb', function (Offer $offer) {
                return '<img src="' . Offers::getThumbSrc($offer) . '">';
            })
            ->editColumn('status_id', function (Offer $offer) {
                return view("components.form.toggle", [
                    'name' => 'status_id',
                    'value' => $offer->status_id,
                    'on' => __('active'),
                    'off' => __('inactive'),
                    'meta' => 'data-id='.$offer->id,
                    'size' => 'sm',
                ]);
            })
            ->editColumn('stock_delayed', function (Offer $offer) {
                return $offer->stock_delayed . ' - ' . $offer->delay_type;
            })
            ->rawColumns(['active', 'thumb', 'action']);
        return parent::modifier($datatables);
    }

    protected function getColumns()
    {
        return [
            Column::make('status_id')->title('')->width(40),
            Column::make('article.article_nature.name')->title('Nature')->defaultContent(''),
            Column::make('thumb')->title('')->width(40)->searchable(false)->order(false),
            Column::make('article.name')->title('Article')->defaultContent(''),
            Column::make('variation.name')->title('Déclinaison')->defaultContent(''),
            Column::make('tariff.name')->title('Tarif')->defaultContent(''),
            Column::make('stock_current')->title('Appro im')->searchable(false),
            Column::make('stock_delayed')->title('Appro délai')->searchable(false),
            Column::make('stock_ondemand')->title('Dmde')->searchable(false),
            $this->makeColumnButtons(),
        ];
    }
}
