<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreMafOrderRequest;
use App\Models\MafOrder;
use Illuminate\Http\Request;

class MafOrderController extends Controller
{
    protected array $data = [
        'active'    => 'maf_order',
        'title'     => 'Заказы МАФ',
        'id'        => 'maf_order',
        'header'    => [
            'product-image'                     => 'Картинка',
            'id'                                => 'ID',
            'order_number'                      => '№ заказа',
            'status'                            => 'Статус',
            'user_id'                           => 'Менеджер',
            'product-article'                   => 'Артикул',
            'product-nomenclature_number'       => 'Номер номенклатуры',
            'product-common_name'               => 'МАФ',
            'quantity'                          => 'Заказано',
            'in_stock'                          => 'Остаток',
            'created_at'                        => 'Дата создания',

        ],
        'searchFields' =>  [
            'order_number',
            'product-nomenclature_number',
            'product-article',
        ],
    ];

    public function index(Request $request)
    {
        $model = new MafOrder;

        $this->createDateFilters($model, 'created_at');
        $this->createFilters($model, 'user_id', 'quantity');
        $this->createRangeFilters($model, 'in_stock', 'quantity');

        $q = $model::query();

        $this->acceptFilters($q, $request);
        $this->acceptSearch($q, $request);
        $this->setSortAndOrderBy($model, $request);

        $q->orderBy($this->data['sortBy'], $this->data['orderBy']);

        $this->data['maf_orders'] = $q->paginate(session('per_page', config('pagination.per_page')))->withQueryString();
        return view('maf_orders.index', $this->data);
    }

    public function store(StoreMafOrderRequest $request)
    {
        MafOrder::query()->create($request->validated() + ['user_id' => $request->user()->id, 'in_stock' => 0]);
        return redirect()->route('maf_order.index');
    }

    public function show(MafOrder $maf_order)
    {
        $this->data['maf_order'] = $maf_order;
        return view('maf_orders.edit', $this->data);
    }

    public function update(StoreMafOrderRequest $request, MafOrder $maf_order)
    {
        MafOrder::query()->where('id', $maf_order->id)->update($request->validated());
        return redirect()->route('maf_order.index');
    }

    public function destroy(MafOrder $maf_order)
    {
        $maf_order->delete();
        return redirect()->route('maf_order.index');
    }

    public function setInStock(MafOrder $maf_order)
    {
        $maf_order->update(['in_stock' => $maf_order->quantity, 'status' => 'на складе']);
        return redirect()->route('maf_order.show', $maf_order);
    }
}
