<?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\BpTrack;

/**
 * Class BpTrackController
 */
class BpTrackController extends ClinicController
{

    /**
     * Load entries
     *
     * @param $id
     * @param Request $request
     * @return JsonResponse
     */
    public function load($id, Request $request): JsonResponse
    {
        $query = BpTrack::query()
            ->where('member_id', $id)
            ->with('file')
            ->orderByDesc('date_provided');

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

        return response()
            ->json([
                'bpTrack' => $query->get()
                    ->map(function (BpTrack $record) {
                        $record->date_provided = Carbon::parse($record->date_provided)
                            ->format('d/m/Y');
                        $record->fileURL = !empty($record->file_id) ?
                            route('admin-file-get', [
                                $record->file_id,
                            ]) :
                            '';
                        return $record;
                    }),
                'todayDate' => Carbon::now()
                    ->format('d/m/Y'),
            ]);
    }

    /**
     * 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 = BpTrack::validate($data)) {
            return response()
                ->json([
                    'errors' => $errors,
                ]);
        }

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

        $action = empty($bpTrack->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;

        $bpTrack->fill($data);

        if (!empty($request->file('file'))) {
            $file = BpTrack::uploadFile($request->file('file'), [
                'date_provided' => $data['date_provided'],
                'member_id' => $id,
            ]);
            $bpTrack->file_id = $file->id;
            (new Logger($file, User::getAdminUser(), $id))
                ->log(Logger::FILE, $action, $file->toArray());
        }

        $bpTrack->save();

        (new Logger($bpTrack, User::getAdminUser(), $id))
            ->log(Logger::BP_TRACK, $action, $bpTrack->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 BpTrack $bpTrack */
        $bpTrack = BpTrack::query()
            ->where('id', $request->input('id'))
            ->where('member_id', $id)
            ->firstOrFail();

        if (!empty($bpTrack->file)) {
            $bpTrack->file->deleteFile();
        }

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

        $bpTrack->delete();

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