<?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 CERTAINTY FACTOR
    // =========================
    public function proses(Request $request)
    {
        // validasi minimal 1 gejala dipilih
        if (empty(array_filter($request->gejala ?? []))) {

            return back()->with('error', 'Pilih minimal 1 gejala!');
        }

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

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

        $hasil = [];

        foreach ($rules as $rule) {

            // =========================
            // CF PAKAR
            // =========================
            $cf_pakar = $rule->mb - $rule->md;

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

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

            // =========================
            // KOMBINASI CF
            // =========================
            if (!isset($hasil[$rule->penyakit_id])) {

                $hasil[$rule->penyakit_id] = $cf;

            } else {

                $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!'
            );
        }

        // =========================
        // HASIL TERTINGGI
        // =========================
        arsort($hasil);

        $penyakit_id = array_key_first($hasil);

        $cf_hasil = $hasil[$penyakit_id];

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

        // =========================
        // SIMPAN DIAGNOSA
        // =========================
        $diagnosa = Diagnosa::create([

            'pasien_id'       => $pasien->id,

            'penyakit_id'     => $penyakit_id,

            'cf_hasil'        => $cf_hasil,

            // simpan gejala + nilai keyakinan user
            // contoh:
            // {"1":"0.8","2":"1"}
            '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);

        // jika admin
        if (auth()->user()->role == 'admin') {

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

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


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

        // =========================
        // AMBIL DATA GEJALA DIPILIH
        // =========================
        $gejalaData = json_decode(
            $diagnosa->gejala_dipilih,
            true
        ) ?? [];

        // ambil ID gejala
        $gejalaIds = array_keys($gejalaData);

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

        // =========================
        // TAMBAHKAN CF USER
        // =========================
        foreach ($gejalas as $g) {

            // ambil nilai user
            $g->cf_user = $gejalaData[$g->id] ?? 0;

            // ubah ke teks
            if ($g->cf_user == 1) {

                $g->keterangan_cf = 'Sangat Yakin';

            } elseif ($g->cf_user == 0.8) {

                $g->keterangan_cf = 'Yakin';

            } elseif ($g->cf_user == 0.6) {

                $g->keterangan_cf = 'Cukup Yakin';

            } elseif ($g->cf_user == 0.4) {

                $g->keterangan_cf = 'Sedikit Yakin';

            } elseif ($g->cf_user == 0.2) {

                $g->keterangan_cf = 'Kurang Yakin';

            } else {

                $g->keterangan_cf = 'Tidak Yakin';
            }
        }

        // =========================
        // GENERATE PDF
        // =========================
        $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')
        );
    }


    // =========================
    // DASHBOARD USER
    // =========================
    public function dashboard(Request $request)
    {
        $pasien = Pasien::where(
            'user_id',
            auth()->id()
        )->first();

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

        $totalDiagnosa = 0;

        $lastDiagnosa = null;

        $riwayat = collect();

        if ($pasien) {

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

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

            $lastDiagnosa = Diagnosa::where(
                'pasien_id',
                $pasien->id
            )->latest()->first();
        }

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