<?php

namespace App\Http\Controllers;

use App\Models\SerialNumberCheck;
use App\Traits\HasFilterRequest;
use App\Traits\HasOrderByRequest;
use App\Traits\HasSearchRequest;
use App\Traits\IsDatatableRequest;
use Illuminate\Http\Request;

class HistorySNCheckController extends Controller
{
    use IsDatatableRequest;
    use HasOrderByRequest;
    use HasFilterRequest;
    use HasSearchRequest;

    public function __construct()
    {
        return $this->middleware([
            'auth'
        ]);
    }

    protected function _columns()
    {
        return [
            [
                'label' => '#',
                'name' => 'id',
                'visible' => false,
                'type' => self::DATATABLE_NUMBER,
            ],
            [
                'label' => 'Keyword',
                'name' => 'keyword',
                'type' => self::DATATABLE_ARRAY,
                'visible' => true
            ],
            [
                'label' => 'Response',
                'name' => 'response',
                'type' => self::DATATABLE_DETAIL_CONTROL,
                'visible' => true,
            ],
            [
                'label' => 'Date',
                'name' => 'created_at',
                'type' => self::DATATABLE_DATETIME,
                'visible' => true,
                'orderable' => true,
            ],
            [
                'label' => 'Status',
                'name' => 'status',
                'type' => self::DATATABLE_STATUS,
                'visible' => true,
            ],
            [
                'label' => 'Action',
                'name' => 'action',
                'className' => self::DATATABLE_CENTER,
                'type' => self::DATATABLE_ACTION,
                'visible' => true,
            ],
        ];
    }

    public function index()
    {
        return view('client.pages.user.history_sn_check', [
            'columns' => $this->_columns()
        ]);
    }

    public function get(Request $request)
    {
        $histories = SerialNumberCheck::where('user_id', auth()->id())
            ->orderByDesc('id');

        $this->filterRequest($histories, $request, [
            'from_date' => [
                'type' => self::F_THAN_EQ_DATETIME,
                'column' => 'created_at',
            ],
            'to_date' => [
                'type' => self::F_LESS_EQ_DATETIME,
                'column' => 'created_at',
            ],
        ]);

        $this->searchRequest(
            builder: $histories,
            value: $request->input('search.value'),
            fields: [
                'keyword'
            ]
        );

        return response()->json(
            $this->paginateWithDatatable(
                builder: $histories,
                request: $request
            )
        );
    }
}
