<?php

namespace App\Http\Controllers;

use App\Models\Mr;
use App\Models\Visit;
use App\Services\ComplianceScoreService;
use Illuminate\Http\Request;

class ComplianceController extends Controller
{
    public function index(Request $request, ComplianceScoreService $compliance)
    {
        $totalVisitsInDb = Visit::count();
        $visitDateRange = $totalVisitsInDb > 0
            ? Visit::selectRaw('MIN(visit_date) as min_date, MAX(visit_date) as max_date')->first()
            : null;

        $from = $request->get('from');
        $to = $request->get('to');
        if ($from === null || $to === null) {
            if ($visitDateRange && $visitDateRange->min_date && $visitDateRange->max_date) {
                $from = $from ?? $visitDateRange->min_date;
                $to = $to ?? $visitDateRange->max_date;
            } else {
                $from = $from ?? now()->subDays(30)->toDateString();
                $to = $to ?? now()->toDateString();
            }
        }

        $scores = $compliance->scoreAllMrsInPeriod($from, $to);
        $mrs = Mr::whereIn('id', array_keys($scores))->get()->keyBy('id');

        $hasNoVisitsInDb = $totalVisitsInDb === 0;
        $hasVisitsButNoneInRange = $totalVisitsInDb > 0 && count($scores) === 0;

        return view('compliance.index', [
            'scores' => $scores,
            'mrs' => $mrs,
            'from' => $from,
            'to' => $to,
            'hasNoVisitsInDb' => $hasNoVisitsInDb,
            'hasVisitsButNoneInRange' => $hasVisitsButNoneInRange,
            'visitDateRange' => $visitDateRange,
        ]);
    }

    public function show(Request $request, int $mr, ComplianceScoreService $compliance)
    {
        $mrModel = Mr::findOrFail($mr);
        $from = $request->get('from', now()->subDays(30)->toDateString());
        $to = $request->get('to', now()->toDateString());
        $detail = $compliance->scoreForMrInPeriod($mr, $from, $to);

        return view('compliance.show', [
            'mr' => $mrModel,
            'detail' => $detail,
            'from' => $from,
            'to' => $to,
        ]);
    }
}
