<?php

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

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Mtc\Plugins\Clinic\Src\Models\Review;
use Mtc\Plugins\Clinic\Src\Models\ReviewType;
use Mtc\Shop\Assessment\Form;
use Mtc\Shop\Category;

/**
 * Class ReviewTypeController
 */
class ReviewTypeController extends ClinicController
{
    /**
     * @param Request $request
     * @return string
     */
    public function index(Request $request): string
    {
        $title = 'Manage Review Types';
        $page_meta['title'] = config('app.name') . ' | ' . $title;

        return template('admin/reviewTypes/index.twig', [
            'page_meta' => $page_meta,
            'title' => $title,
            'mediums' => Review::$mediums,
            'types' => Review::$types,
            'reviewTypes' => ReviewType::query()
                ->with('form')
                ->with('category')
                ->orderBy('name')
                ->get(),
        ]);
    }

    /**
     * @param $id
     * @return string
     */
    public function edit($id = null): string
    {
        $title = !empty($id) ?
            'Edit Review Type' :
            'Add Review Type';
        $page_meta['title'] = config('app.name') . ' | ' . $title;

        /** @var ReviewType $reviewType */
        $reviewType = ReviewType::query()
            ->findOrNew($id);

        return template('admin/reviewTypes/edit.twig', [
            'page_meta' => $page_meta,
            'title' => $title,
            'reviewType' => $reviewType,
            'mediums' => Review::$mediums,
            'types' => Review::$types,
            'categories' => Category::getCompleteFlatTree(),
            'forms' => Form::query()
                ->orderBy('name')
                ->get(),
            'routes' => [
                'admin-review-types-store' => route('admin-review-types-store'),
            ],
        ]);
    }

    /**
     * Creates / updates entry in database
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function store(Request $request): JsonResponse
    {
        if (empty($request->input('name'))) {
            return response()->json([
                'errors' => [
                    'name' => 'This field is required',
                ],
            ]);
        }

        /** @var ReviewType $reviewType */
        $reviewType = ReviewType::query()
            ->findOrNew($request->input('id'));

        $reviewType->fill($request->all());
        $reviewType->save();

        return response()->json([
            'success' => 'Data saved successfully!',
            'reviewType' => $reviewType,
        ]);
    }
}
