<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreContractRequest;
use App\Models\Contract;
use Illuminate\Http\Request;

class ContractController extends Controller
{
    protected array $data = [
        'active'    => 'contracts',
        'title'     => 'Договоры',
        'id'        => 'contracts',
        'header'    => [
            'id'                        => 'ID',
            'contract_number'           => 'Номер договора',
            'contract_date'             => 'Дата договора',
            'year'                      => 'Год',
        ],
        'searchFields' => [
            'contract_number',
        ],
    ];


    public function index(Request $request)
    {
        $model = new Contract();
        // fill filters
        $this->createFilters($model, 'year');
        $this->data['ranges'] = [];
        $this->createDateFilters($model, 'contract_date');

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

        $q->orderBy($this->data['sortBy'], $this->data['orderBy']);
        $this->data['contracts'] = $q->paginate(session('per_page', config('pagination.per_page')))->withQueryString();

        return view('contracts.index', $this->data);
    }

    public function show(Contract $contract)
    {
        $this->data['contract'] = $contract;
        return view('contracts.edit', $this->data);
    }

    public function create()
    {
        $this->data['contract'] = null;
        return view('contracts.edit', $this->data);
    }

    public function store(StoreContractRequest $request)
    {
        Contract::query()->create($request->validated());
        return redirect()->route('contract.index');
    }

    public function update(StoreContractRequest $request, Contract $contract)
    {
        $contract->update($request->validated());
        return redirect()->route('contract.index');
    }

    public function delete(Contract $contract)
    {
        $contract->delete();
        return redirect()->route('contract.index');
    }
}
