<?php

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

use Carbon\Carbon;
use Illuminate\Http\Request;
use Mtc\Core\AdminUser;
use Mtc\Modules\Members\Models\MemberNote;
use Mtc\Plugins\Clinic\Src\Models\Review;
use Mtc\Shop\Assessment\Form;
use Mtc\Shop\Category;

/**
 * Class DashboardController
 */
class DashboardController extends ClinicController
{
    /**
     * Dashboard
     *
     * @param Request $request
     * @return string
     */
    public function index(Request $request): string
    {
        $title = 'Clinic Dashboard';
        $page_meta['title'] = config('app.name').' | '.$title;

        return template('admin/dashboard/index.twig', [
            'page_meta' => $page_meta,
            'title' => $title,
            'mediums' => Review::$mediums,
            'types' => Review::$types,
            'categories' => Category::getCompleteFlatTree(),
            'statuses' => Review::$statuses,
            'users' => AdminUser::query()
                ->orderBy('name')
                ->get(),
            'forms' => Form::query()
                ->orderBy('name')
                ->get(),
            'reviews' => Review::getReviewAlerts($request->all())
                ->map(function (Review $review) {
                    if (
                        $review->status === Review::STATUS_UNSCHEDULED
                        && $review->due_date < Carbon::now()->addWeek()->format('Y-m-d')
                    ) {
                        $review->statusRed = true;
                    }

                    if (
                        $review->status === Review::STATUS_PENDING
                        && $review->due_date < Carbon::now()->format('Y-m-d')
                    ) {
                        $review->dateRed = true;
                    }

                    return $review;
                }),
            'flags' => MemberNote::getFlagAlerts()
                ->map(function (MemberNote $flag) {
                    if (! empty($flag->flag_due)) {
                        $flag->due_date = Carbon::parse($flag->flag_due)->format('d/m/Y');
                        if ($flag->flag_due < Carbon::now()->format('Y-m-d')) {
                            $flag->dateRed = true;
                        }
                        $flag->type = ! empty($flag->status)
                            ? MemberNote::TYPE_TASK
                            : MemberNote::TYPE_FLAG;
                    }

                    return $flag;
                }),
        ]);
    }
}
