<?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\Plugins\Clinic\Src\Logger;
use Mtc\Plugins\Clinic\Src\Models\Treatment;

/**
 * Class TreatmentController
 */
class TreatmentController extends ClinicController
{

    /**
     * Load entries
     *
     * @param $id
     * @return JsonResponse
     */
    public function load($id): JsonResponse
    {
        return response()
            ->json([
                'treatments' => Treatment::query()
                    ->where('member_id', $id)
                    ->with('item')
                    ->orderByDesc('date_from')
                    ->get()
                    ->map(function (Treatment $treatment) {
                        $treatment->product = $treatment->item->name;
                        $treatment->status = $treatment->getStatus();
                        $treatment->date_from = Carbon::parse($treatment->date_from)
                            ->format('d/m/Y');
                        $treatment->date_to = Carbon::parse($treatment->date_to)
                            ->format('d/m/Y');
                        return $treatment;
                    }),
            ]);
    }

    /**
     * Creates / updates entry in database
     *
     * @param $id
     * @param Request $request
     * @return JsonResponse
     */
    public function store($id, Request $request): JsonResponse
    {
        $data = $request->all();
        $data['member_id'] = $id;
        if ($errors = Treatment::validate($data)) {
            return response()
                ->json([
                    'errors' => $errors,
                ]);
        }

        /** @var Treatment $treatment */
        $treatment = Treatment::query()
            ->firstOrNew([
                'id' => $request->input('id'),
                'member_id' => $id,
            ]);

        $data['date_from'] = Carbon::createFromFormat('d/m/Y', $data['date_from'])
            ->format('Y-m-d');
        $data['date_to'] = Carbon::createFromFormat('d/m/Y', $data['date_to'])
            ->format('Y-m-d');

        $action = !empty($treatment->id) ?
            Logger::ACTION_UPDATED :
            Logger::ACTION_CREATED;

        $treatment->fill($data);
        $treatment->save();

        $details = [
            'item_name' => $treatment->item->name,
        ];

        if (!empty($treatment->size)) {
            $details['variation'] = $treatment->size->size;
        }

        (new Logger($treatment, User::getAdminUser(), $id))
            ->log(Logger::TREATMENT, $action, array_merge(
                $treatment->toArray(),
                $details
            ));

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

    /**
     * Deletes entry in database
     *
     * @param $id
     * @param Request $request
     * @return JsonResponse
     */
    public function delete($id, Request $request): JsonResponse
    {
        /** @var Treatment $treatment */
        $treatment = Treatment::query()
            ->where('id', $request->input('id'))
            ->where('member_id', $id)
            ->firstOrFail();

        $details = [
            'item_name' => $treatment->item->name,
        ];

        if (!empty($treatment->size)) {
            $details['variation'] = $treatment->size->size;
        }

        (new Logger($treatment, User::getAdminUser(), $id))
            ->log(Logger::TREATMENT, Logger::ACTION_DELETED, array_merge(
                $treatment->toArray(),
                $details
            ));

        $treatment->delete();

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