<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Diagnosa;
use App\Models\Pasien;
use Illuminate\Support\Facades\Auth;

class UserDashboardController extends Controller
{
    public function index()
    {
        $pasien = Pasien::where('user_id', Auth::id())->first();

        // default kosong
        $totalDiagnosa = 0;
        $lastDiagnosa = null;

        // pagination
        $perPage = request()->perPage ?? 5;

        // jika pasien belum ada
        if (!$pasien) {

            $riwayat = Diagnosa::where('id', 0)->paginate($perPage);

            return view('user.dashboard', compact(
                'totalDiagnosa',
                'lastDiagnosa',
                'riwayat',
                'perPage'
            ));
        }

        // total diagnosa
        $totalDiagnosa = Diagnosa::where('pasien_id', $pasien->id)->count();

        // diagnosa terakhir
        $lastDiagnosa = Diagnosa::with('penyakit')
            ->where('pasien_id', $pasien->id)
            ->latest()
            ->first();

        // riwayat
        $riwayat = Diagnosa::with('penyakit')
            ->where('pasien_id', $pasien->id)
            ->latest()
            ->paginate($perPage)
            ->withQueryString();

        return view('user.dashboard', compact(
            'totalDiagnosa',
            'lastDiagnosa',
            'riwayat',
            'perPage'
        ));
    }
}