<?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(Request $request)
    {
        $pasien = Pasien::where('user_id', Auth::id())->first();

        $totalDiagnosa = 0;
        $lastDiagnosa = null;

        $perPage = $request->perPage ?? 5;

        // Jika pasien belum mengisi data diri
        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 diagnosa
        $riwayat = Diagnosa::with('penyakit')
            ->where('pasien_id', $pasien->id)
            ->latest()
            ->paginate($perPage)
            ->withQueryString();

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