<?php

namespace Mtc\Plugins\NHS\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Mtc\Plugins\NHS\Classes\NHSUnilexiconProduct;


class UnilexiconController extends \App\Http\Controllers\Controller
{

    public function manage(Request $request)
    {
        $products = NHSUnilexiconProduct::query()
            ->orderBy('number_of_charges', 'desc')
            ->orderBy('id', 'asc')
        ;

        if ($search_query = $request->get('search_query')) {
            $search_query_like = preg_replace('/\s+/', '%', $search_query);
            $products->where('mtc__display_name', 'LIKE', "%{$search_query_like}%");
        }

        return template('admin/manage.twig', [
            'selected_tab' => 'manage',
            'title' => 'Unilexicon Products',
            'products' => $products->paginate(100),
            'search_query' => $search_query,
            'actions' => [
                [
                    'button_route' => 'nhs-unilexicon-decrease-charges',
                    'button_label' => '-',
                ],
                [
                    'button_route' => 'nhs-unilexicon-increase-charges',
                    'button_label' => '+',
                ],
            ],
        ]);
    }


    public function increase_charges($id, Request $request)
    {
        $product = NHSUnilexiconProduct::findOrFail($id);

        $product->number_of_charges++;
        $product->save();

        return back();
    }


    public function decrease_charges($id, Request $request)
    {
        $product = NHSUnilexiconProduct::findOrFail($id);

        $product->number_of_charges--;
        if ($product->number_of_charges < 1) {
            $product->number_of_charges = 1;
        }
        $product->save();

        return back();
    }

}


