<?php

namespace App\Datatables\Shop;

use App\Datatables\ParentDataTable as DataTable;
use App\Models\Shop\Invoice;
use App\Repositories\Shop\Invoices;
use Yajra\DataTables\Html\Column;

class InvoicesDataTable extends DataTable
{
    public $model_name = 'Invoices';

    public function query(Invoice $model)
    {
        $model = $model->with('customer');

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

    public function modifier($datatables)
    {
        $datatables
            ->editColumn('status', function (Invoice $invoice) {
                return Invoices::getStatus($invoice->status);
            })
            ->editColumn('created_at', function (Invoice $invoice) {
                return $invoice->created_at->toDateTimeString();
            })
            ->editColumn('customer.last_name', function (Invoice $invoice) {
                $customer = $invoice->customer ?? false;

                return $customer ? $customer->last_name.' '.$customer->first_name : '';
            })
            ->rawColumns(['action']);

        return parent::modifier($datatables);
    }

    protected function getColumns()
    {
        return [
            Column::make('ref')->title('Ref')->width(80),
            Column::make('status')->width(60),
            Column::make('created_at')->title('Date')->width(100),
            Column::make('customer.last_name')->title('Client')->default(''),
            Column::make('total')->addClass('text-right'),
            $this->makeColumnButtons(),
        ];
    }
}
