<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;
use App\Models\Gejala;
use App\Models\Rule;
use App\Models\Pasien;
use App\Models\Diagnosa;
use App\Models\Penyakit;
use Illuminate\Support\Facades\Auth;

class DiagnosaController extends Controller
{

    
    // FORM DIAGNOSA

    public function index()
    {
        $gejalas = Gejala::all();
        return view('user.diagnosa', compact('gejalas'));
    }

   
    // PROSES CF KOMBINASI + CF USER
   
    public function proses(Request $request)
    {
        // validasi minimal 1 gejala dipilih
        if (empty(array_filter($request->gejala ?? []))) {
            return back()->with('error', 'Pilih minimal 1 gejala!');
        }

        // ambil input (format: [gejala_id => nilai_cf_user])
        $inputGejala = array_filter($request->gejala);
        

        // ambil rule sesuai gejala yang dipilih
        $rules = Rule::whereIn('gejala_id', array_keys($inputGejala))->get();

        $hasil = [];

        foreach ($rules as $rule) {

            // CF dari pakar
            $cf_pakar = $rule->mb - $rule->md;

            // CF dari user
            $cf_user = $inputGejala[$rule->gejala_id];

            // CF akhir
            $cf = $cf_pakar * $cf_user;

            if (!isset($hasil[$rule->penyakit_id])) {
                $hasil[$rule->penyakit_id] = $cf;
            } else {
                // CF KOMBINASI
                $hasil[$rule->penyakit_id] =
                    $hasil[$rule->penyakit_id] +
                    ($cf * (1 - $hasil[$rule->penyakit_id]));
            }
        }

        // jika tidak ada hasil
        if (empty($hasil)) {
            return back()->with('error', 'Tidak ada rule yang cocok!');
        }

        // ambil hasil tertinggi
        arsort($hasil);
        $penyakit_id = array_key_first($hasil);
        $cf_hasil = $hasil[$penyakit_id];

        $pasien = Pasien::where('user_id', Auth::id())->latest()->first();

        // simpan ke DB
        $diagnosa = Diagnosa::create([
            'pasien_id' => $pasien->id,
            'penyakit_id' => $penyakit_id,
            'cf_hasil' => $cf_hasil,
            'gejala_dipilih' => json_encode($inputGejala)
        ]);

        return redirect()->route('diagnosa.hasil', $diagnosa->id);
    }


    // HASIL DIAGNOSA
   
public function hasil($id)
{
    $diagnosa = Diagnosa::with(['pasien', 'penyakit'])->findOrFail($id);

    // ROLE
    if (auth()->user()->role == 'admin') {
        return view('admin.hasil', compact('diagnosa'));
    }

    return view('user.hasil', compact('diagnosa'));
}

    // =========================
    // CETAK PDF
    // =========================
public function pdf($id)
{
    $diagnosa = Diagnosa::with(['pasien','penyakit'])->findOrFail($id);

    // ✅ ambil data gejala (id => cf_user)
    $gejalaData = json_decode($diagnosa->gejala_dipilih, true) ?? [];

    // ✅ ambil hanya ID
    $gejalaIds = array_keys($gejalaData);

    // ✅ ambil data gejala dari DB
    $gejalas = Gejala::whereIn('id', $gejalaIds)->get();

    $pdf = Pdf::loadView('pdf.diagnosa', compact('diagnosa','gejalas'));

    return $pdf->download('hasil_diagnosa_'.$diagnosa->id.'.pdf');
}


    // =========================
    // RIWAYAT USER
    // =========================
public function riwayat()
{
    $pasien = Pasien::where('user_id', Auth::id())->first();

    // jumlah data per halaman
    $perPage = request()->perPage ?? 5;

    // jika belum isi data diri
    if (!$pasien) {

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

        return view('user.riwayat', compact('data', 'perPage'));
    }

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

    return view('user.riwayat', compact('data', 'perPage'));
}


    public function dashboard(Request $request)
{
    $pasien = \App\Models\Pasien::where('user_id', auth()->id())->first();

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

    $totalDiagnosa = 0;
    $lastDiagnosa = null;
    $riwayat = collect();

    if ($pasien) {
        $riwayat = \App\Models\Diagnosa::with('penyakit')
            ->where('pasien_id', $pasien->id)
            ->latest()
            ->paginate($perPage)
            ->withQueryString();

        $totalDiagnosa = \App\Models\Diagnosa::where('pasien_id', $pasien->id)->count();
        $lastDiagnosa = \App\Models\Diagnosa::where('pasien_id', $pasien->id)->latest()->first();
    }

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

}

