<?php

namespace App\Datatables\Shop;

use App\Datatables\ParentDataTable as DataTable;
use App\Models\Shop\Invoice;
use App\Repositories\Shop\Customers;
use App\Repositories\Shop\InvoicePayments;
use App\Repositories\Shop\Invoices;
use Illuminate\Support\Facades\Auth;
use Yajra\DataTables\Html\Column;

class CustomerInvoicesDataTable extends DataTable
{
    public $model_name = 'invoices';

    public $sortedColumn = 1;

    public $sortedOrder = 'desc';

    public $stateSave = true;

    public $url = null;

    public function __construct()
    {
        $this->url = route('Shop.Invoices.index');
    }

    public function query(Invoice $model)
    {
        $customerId = Customers::getId();
        $model = $model->byCustomer($customerId)->with(['address']);

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

    public function getHtmlButtons()
    {
        $buttons = view('components.form.button', [
            'dataId' => '{{$uuid}}',
            'class' => 'btn-sm btn-secondary btn-invoice mr-2',
            'icon' => 'fa-file-pdf',
            'title' => 'Télécharger la facture',
            'url' => route('Shop.Invoices.pdf').'/{{$uuid}}',
        ]);

        $buttons .= self::getButtonShow('uuid', 'Voir la facture');

        return $buttons;
    }

    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->isoFormat('DD/MM/YY HH:mm');
            })
            ->editColumn('payment_type', function (Invoice $invoice) {
                return InvoicePayments::getPaymentType($invoice->payment_type);
            })
            ->rawColumns(['action']);

        return parent::modifier($datatables);
    }

    protected function getColumns()
    {
        return [
            Column::make('created_at')->title('Date'),
            Column::make('ref')->title('Ref'),
            Column::make('payment_type')->title('Règlement'),
            Column::make('total_shipped')->title('Montant')->class('text-right'),
            Column::make('status')->title('Statut'),
            $this->makeColumnButtons(),
        ];
    }
}
