<?php

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

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Mtc\Modules\Members\Models\Member;
use Mtc\Modules\Members\Models\MemberAttribute;

/**
 * Class MemberAttributeController
 * @package App\Http\Controllers
 */
class MemberAttributeController extends ClinicController
{
    /**
     *
     *
     * @param Request $request
     * @return string
     */
    public function index($id): string
    {
        $page_meta['title'] = config('app.name') . ' | Manage Member Attributes';

        return template('admin/memberAttributes/index.twig', [
            'page_meta' => $page_meta,
            'title' => 'Manage member attributes',
            'attributes' => MemberAttribute::getFields(),
            'routes' => [
                'admin-member-attributes-load' => route('admin-member-attributes-load', [
                    'id' => $id,
                ]),
                'admin-member-attributes-store' => route('admin-member-attributes-store', [
                    'id' => $id,
                ]),
            ],
        ]);
    }

    /**
     * Loads member attributes
     *
     * @param $id
     * @return JsonResponse
     */
    public function load($id): JsonResponse
    {
        /** @var Member $member */
        $member = Member::query()
            ->with('attributes')
            ->findOrFail($id);

        return response()->json([
            'attributes' => MemberAttribute::unpackDataForForm($member),
        ]);
    }

    /**
     */
    public function store($id, Request $request): JsonResponse
    {
        /** @var Member $member */
        if (!$member = Member::query()->find($id)) {
            return response()->json([
                'errors' => [
                    'general' => 'Patient not found!'
                ]
            ]);
        }

        if ($errors = MemberAttribute::validate($request->input('attributes'))) {
            return response()->json([
                'errors' => $errors,
            ]);
        }

        $data = MemberAttribute::packDataForStore($request->input('attributes'));

        MemberAttribute::logChanges($member, $data);

        foreach ($data as $key => $value) {

            MemberAttribute::query()
                ->updateOrCreate([
                    'member_id' => $member->id,
                    'name' => $key,
                ],
                [
                    'value' => $value,
                ]);
        }

        return response()->json([
            'success' => 'Patient data updated successfully!'
        ]);

        // TODO - Log changes.
    }
}
