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

/**
 * Class WeightTrackController
 */
class WeightTrackController extends ClinicController
{

    /**
     * Load entries
     *
     * @param $id
     * @param Request $request
     * @return JsonResponse
     */
    public function load($id, Request $request): JsonResponse
    {
        /** @var Member $member */
        $member = Member::query()
            ->find($id);
        $query = WeightTrack::query()
            ->where('member_id', $id)
            ->with('user')
            ->orderByDesc('date_provided');

        if (!empty($request->input('review_id'))) {
            $query->where('review_id', $request->input('review_id'));
        }

        $weightTrack = $query->get();

        foreach ($weightTrack as $key => $record) {
            if ($key === $weightTrack->count() - 1) {
                // Last element
                $weightTrack[$key]->time_span = 0;
                $weightTrack[$key]->bmi_diff = 0;
                $weightTrack[$key]->weight_diff = 0;
                break;
            }
            // Get how many days have passed since the last record
            $weightTrack[$key]->time_span = Carbon::parse($record->date_provided)
                ->diffInDays(Carbon::parse($weightTrack[$key + 1]->date_provided));
            $weightTrack[$key]->bmi_diff = number_format($record->bmi - $weightTrack[$key + 1]->bmi, 2);
            $weightTrack[$key]->weight_diff = $record->weight - $weightTrack[$key + 1]->weight;
        }

        $weightTrack->map(function (WeightTrack $record) {
            $record->date_provided = Carbon::parse($record->date_provided)
                ->format('d/m/Y');
            return $record;
        });

        return response()
            ->json([
                'weightTrack' => $weightTrack,
                'todayDate' => Carbon::now()
                    ->format('d/m/Y'),
                'height' => $member->height,
                'heightImperial' => BMI::convertHeightToImperial($member->height),
            ]);
    }

    /**
     * Creates / updates entry in database
     *
     * @param $id
     * @param Request $request
     * @return JsonResponse
     */
    public function store($id, Request $request): JsonResponse
    {
        /** @var Member $member */
        $member = Member::query()
            ->find($id);

        $data = $request->all();
        $data['member_id'] = $id;
        $data['weight'] = !empty($data['metric']) ?
            $data['weightKg'] :
            BMI::convertWeightToMetric($data['weightSt'], $data['weightLb']);
        $data['height'] = !empty($data['metric']) ?
            $data['heightCm'] :
            BMI::convertHeightToMetric($data['heightFt'], $data['heightIn']);

        $member->update([
            'height' => $data['height'],
        ]);

        $data['bmi'] = BMI::calculateBMI($data['height'], $data['weight']);

        if ($errors = WeightTrack::validate($data)) {
            return response()
                ->json([
                    'errors' => $errors,
                ]);
        }

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

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

        $dateProvided = !empty($data['date_provided']) ?
            Carbon::createFromFormat('d/m/Y', $data['date_provided']) :
            Carbon::now();
        $data['date_provided'] = $dateProvided->format('Y-m-d');

        $data['review_id'] = !empty($data['review_id']) ?
            $data['review_id'] :
            null;

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

        (new Logger($weightTrack, User::getAdminUser(), $id))
            ->log(Logger::WEIGHT_TRACK, $action, $weightTrack->toArray());

        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 WeightTrack $weightTrack */
        $weightTrack = WeightTrack::query()
            ->where('id', $request->input('id'))
            ->where('member_id', $id)
            ->firstOrFail();

        (new Logger($weightTrack, User::getAdminUser(), $id))
            ->log(Logger::WEIGHT_TRACK, Logger::ACTION_DELETED, $weightTrack->toArray());

        $weightTrack->delete();

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