<?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
    {
        $notes = MemberNote::query()
            ->with(['admin_user:id,name'])                 // only what we need
            ->where('member_id', $id)
            ->where('is_flag', false)
            ->latest()
            ->get(['id','admin_user_id','order_id','content','created_at'])
            ->map(function (MemberNote $note) {
                return [
                    'id'          => $note->id,
                    'order_id'    => $note->order_id,
                    'content'     => $note->content, // sanitize if needed
                    'datetime'    => Carbon::parse($note->created_at)->format('d.m.Y H:i'),
                    'author_name' => optional($note->admin_user)->name,
                ];
            })
            ->values();

        return response()->json(['notes' => $notes]);
    }


    /**
     * 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,
        ]);
    }
}
