<?php

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

use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Mtc\Core\Admin\User;
use Mtc\Modules\Members\Models\Member;
use Mtc\Modules\Members\Models\MemberNote;
use Mtc\Plugins\Clinic\Src\Flag;
use Mtc\Plugins\Clinic\Src\Logger;

/**
 * Class MemberAttributeController
 * @package App\Http\Controllers
 */
class MemberNoteController extends ClinicController
{
    /**
     * Loads member attributes
     *
     * @param $id
     * @return JsonResponse
     */
    public function load($id): JsonResponse
    {
        return response()->json([
            'notes' => MemberNote::query()
                    ->with('admin_user')
                    ->where('member_id', $id)
                    ->where('is_flag', false)
                    ->latest()
                    ->get()
                    ->map(function ($note) {
                        $note->datetime = Carbon::parse($note->created_at)->format('d.m.Y H:i');
                        return $note;
                    }),
        ]);
    }

    /**
     * Stores patient notes
     *
     * @param $id
     * @param Request $request
     * @return JsonResponse
     */
    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 = MemberNote::validate($request->input('note'))) {
            return response()->json([
                'errors' => $errors,
            ]);
        }

        $flagDue = null;
        if (!empty($request->input('flagDue'))) {
            $flagDue = Carbon::createFromFormat('d/m/Y', $request->input('flagDue'))
                ->format('Y-m-d');
        }

        $member->logPatientNotes([
            'note' => $request->input('note'),
            'isFlag' => $request->input('isFlag'),
            'status' => $request->input('isTask') ?
                MemberNote::STATUS_TODO :
                null,
            'flagDue' => $flagDue,
            'orderID' => $request->input('orderID') ?: null
        ]);

        return response()->json([
            'success' => $request->input('isFlag') ?
                'Patient flag saved successfully!' :
                'Patient note saved successfully!',
        ]);
    }

    /**
     * Loads member attributes
     *
     * @param $id
     * @return JsonResponse
     */
    public function loadFlags($id): JsonResponse
    {
        return response()->json([
            'flags' => Flag::getPatientFlags($id),
        ]);
    }

    /**
     * Deletes a flag
     *
     * @param $id
     * @param Request $request
     * @return JsonResponse
     */
    public function deleteFlag($id, Request $request): JsonResponse
    {
        $flag = MemberNote::query()
            ->where('member_id', $id)
            ->where('is_flag', true)
            ->findOrFail($request->input('id'));

        (new Logger($flag, User::getAdminUser(), $id))
            ->log(Logger::MEMBER_FLAG, Logger::ACTION_DELETED, []);

        $flag->delete();

        return response()->json([
            'success' => 'Patient flag deleted successfully!'
        ]);
    }

    /**
     * Toggles Flag status
     *
     * @param $id
     * @param Request $request
     * @return JsonResponse
     */
    public function toggleFlagStatus($id, Request $request): JsonResponse
    {
        $flag = MemberNote::query()
            ->where('member_id', $id)
            ->where('id', $request->input('id'))
            ->where('is_flag', true)
            ->first();

        $flag->update([
            'status' => $request->input('status'),
        ]);

        (new Logger($flag, User::getAdminUser(), $id))
            ->log(Logger::MEMBER_FLAG, Logger::ACTION_UPDATED, [
                'new_status' => $request->input('status'),
            ]);

        return response()->json([
            'success' => true,
        ]);
    }
}
