<?php

namespace App\Http\Controllers;

use App\Models\Bobot;
use App\Models\Diagnosa;
use App\Models\DiagnosaDetail;
use App\Models\Gejala;
use App\Models\Informasi;
use App\Models\Kontak;
use App\Models\Penyakit;
use App\Models\Rule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redirect;
use Whoops\Run;

class ClientController extends Controller
{
    public function BlogInformasi()
    {
        $informasi = Informasi::latest()->get();
        return view('client-side.blog-informasi.data', compact('informasi'));
    }

    public function DetailBlogInformasi($slug)
    {
        $informasi = Informasi::where('slug', $slug)->first();
        return view('client-side.blog-informasi.detail', compact('informasi'));
    }

    public function KontakKami()
    {
        return view('client-side.kontak-kami.form');
    }

    public function KontakStore(Request $request)
    {
        $request->validate([
            'nama' => ['required'],
            'email' => ['required', 'email'],
            'nope' => ['required', 'numeric'],
            'subjek' => ['required'],
            'pesan' => ['required'],
        ]);
        Kontak::create($request->all());
        return Redirect::route('kontak.index')->with('message', 'Berhasil mengirim pesan kepada admin KlinikSapi.Go');
    }

    public function DiagnosaPenyakit()
    {
        $numtab = 1;
        $rule = Rule::with('gejala')->select('gejalaId')->distinct()->get();
        return view('client-side.konsultasi.diagnosa', compact(['numtab', 'rule']));
    }

    private function hitungDempsterShafer($gejalaYangDipilih)
    {
        $rules = DB::table('rules')->whereIn('gejalaId', $gejalaYangDipilih)->get();

        $hasilPerhitungan = [];
        $m = [];

        foreach ($gejalaYangDipilih as $index => $gejalaId) {
            $ruleTerkait = $rules->where('gejalaId', $gejalaId);

            $belief = $ruleTerkait->max('belief');
            $plausibility = 1 - $belief;

            $penyakitTerkait = $ruleTerkait->pluck('penyakitId')->toArray();

            $m[$index][implode(',', $penyakitTerkait)] = $belief;
            $m[$index]['THETA (ϴ)'] = $plausibility;

            if ($index == 0) {
                $hasilPerhitungan = $m[$index];
            } else {
                $hasilPerhitungan = $this->hitungKombinasi($hasilPerhitungan, $m[$index]);
            }
        }

        return $hasilPerhitungan;
    }

    private function hitungKombinasi($m1, $m2)
    {
        $kombinasi = [];
        $conflict = 0;

        foreach ($m1 as $k1 => $v1) {
            foreach ($m2 as $k2 => $v2) {
                if ($k1 == 'THETA (ϴ)' && $k2 == 'THETA (ϴ)') {
                    $key = 'THETA (ϴ)';
                } elseif ($k1 == 'THETA (ϴ)') {
                    $key = $k2;
                } elseif ($k2 == 'THETA (ϴ)') {
                    $key = $k1;
                } else {
                    $set1 = explode(',', $k1);
                    $set2 = explode(',', $k2);
                    $intersection = array_intersect($set1, $set2);

                    if (empty($intersection)) {
                        $conflict += $v1 * $v2;
                        continue;
                    }

                    $key = implode(',', $intersection);
                }

                if (!isset($kombinasi[$key])) {
                    $kombinasi[$key] = 0;
                }
                $kombinasi[$key] += $v1 * $v2;
            }
        }

        // // Normalisasi
        // if ($conflict < 1) {
        //     foreach ($kombinasi as $k => $v) {
        //         $kombinasi[$k] = $v / (1 - $conflict);
        //     }
        // }

        return $kombinasi;
    }

    public function HasilDiagnosa(Request $request)
    {
        $request->validate([
            'gejala' => 'required|array|min:2|max:6',
            'gejala.*' => 'required|string',
        ], [
            'gejala.required' => 'Pilih 2 sampai 6 gejala untuk melakukan diagnosa!',
            'gejala.min' => 'Harus memilih setidaknya dua gejala!',
            'gejala.max' => 'Maaf, maksimal hanya boleh memilih 6 gejala!',
        ]);

        $diagnosaId = (new Diagnosa())->generateId();
        $firsttab = 1; $secondtab = 1; $thirdtab = 1;
        $selectedGejala = $request->gejala;
        // Ambil data terkait gejala yang dipilih
        $datarules = Rule::with('gejala', 'penyakit')->whereIn('gejalaId', $selectedGejala)->get();
        // Kelompokkan berdasarkan gejalaId
        $groupedResults = $datarules->groupBy('gejalaId')->map(function ($group) {
            $firstGejala = $group->first()->gejala;
            $gejalaId = $firstGejala->gejalaId;
            $gejalaName = $firstGejala->gejala;
            // Gabungkan nilai pakar (rata-rata)
            $totalBelief = round($group->avg('nilaiPakar'), 2);
            $totalPlausibility = round(1 - $totalBelief, 2);
            return [
                'gejalaId' => $gejalaId,
                'gejala' => $gejalaName,
                'allbelief' => $group->pluck('nilaiPakar')->toArray(),
                'belief' => $totalBelief,
                'plausibility' => $totalPlausibility,
                'penyakitIds' => $group->pluck('penyakitId')->unique()->toArray() // Menyimpan penyakit terkait
            ];
        });

        $gejalaYangDipilih = $request->input('gejala');
        $hasilPerhitungan = $this->hitungDempsterShafer($gejalaYangDipilih);

        // Urutkan hasil dari probabilitas tertinggi ke terendah
        arsort($hasilPerhitungan);

        // Ambil penyakit dengan probabilitas tertinggi
        $penyakitTerdiagnosa = key($hasilPerhitungan);
        $probabilitas = current($hasilPerhitungan);

        // Jika hasil bukan 'THETA (ϴ)', pecah string penyakit menjadi array
        if ($penyakitTerdiagnosa !== 'THETA (ϴ)') {
            $penyakitTerdiagnosa = explode(',', $penyakitTerdiagnosa);
        }

        // Ambil detail penyakit dari database
        // $detailPenyakit = DB::table('penyakits')->whereIn('penyakitId', $penyakitTerdiagnosa)->get();

        return view('client-side.konsultasi.hasil-diagnosa', compact(
            ['diagnosaId', 'firsttab', 'secondtab', 'thirdtab', 'groupedResults', 'probabilitas', 'hasilPerhitungan', 'penyakitTerdiagnosa']
        ));
    }

    // public function HasilDiagnosa(Request $request)
    // {
    //     $request->validate([
    //         'gejala' => 'required|array',
    //         'gejala.*' => 'required|string',
    //     ], [
    //         'gejala.required' => 'Pilih setidaknya satu gejala!',
    //     ]);

    //     $diagnosaId = (new Diagnosa())->generateId();
    //     $firsttab = 1; $secondtab = 1; $thirdtab = 1;
    //     $selectedGejala = $request->gejala;
    //     // Ambil data terkait gejala yang dipilih
    //     $rules = Rule::with('gejala', 'penyakit')->whereIn('gejalaId', $selectedGejala)->get();
    //     // Kelompokkan berdasarkan gejalaId
    //     $groupedResults = $rules->groupBy('gejalaId')->map(function ($group) {
    //         $firstGejala = $group->first()->gejala;
    //         $gejalaId = $firstGejala->gejalaId;
    //         $gejalaName = $firstGejala->gejala;
    //         // Gabungkan nilai pakar (rata-rata)
    //         $totalBelief = round($group->avg('nilaiPakar'), 3);
    //         $totalPlausibility = round(1 - $totalBelief, 3);
    //         return [
    //             'gejalaId' => $gejalaId,
    //             'gejala' => $gejalaName,
    //             'allbelief' => $group->pluck('nilaiPakar')->toArray(),
    //             'belief' => $totalBelief,
    //             'plausibility' => $totalPlausibility,
    //             'penyakitIds' => $group->pluck('penyakitId')->unique()->toArray() // Menyimpan penyakit terkait
    //         ];
    //     });

    //     // Perhitungan Dempster-Shafer
    //     $dempsterResults = $this->calculateDempsterShafer($groupedResults);

    //     // Temukan penyakit dengan nilai keyakinan terbesar
    //     $maxBelief = max($dempsterResults);
    //     $diagnosaTerbaik = array_search($maxBelief, $dempsterResults);

    //     // Sorting Dempster-Shafer DESC
    //     $dempsterResults = collect($dempsterResults)->sortDesc();

    //     return view('client-side.konsultasi.hasil-diagnosa', compact(
    //         ['diagnosaId', 'firsttab', 'secondtab', 'thirdtab', 'groupedResults', 'dempsterResults', 'maxBelief', 'diagnosaTerbaik']
    //     ));
    // }

    // private function calculateDempsterShafer($groupedResults)
    // {
    //     $dempsterResults = [];
    //     // Inisialisasi nilai belief untuk setiap penyakit
    //     $beliefs = [];
    //     foreach ($groupedResults as $result) {
    //         foreach ($result['penyakitIds'] as $penyakitId) {
    //             if (!isset($beliefs[$penyakitId])) {
    //                 $beliefs[$penyakitId] = 1;
    //             }
    //             // Kombinasi nilai belief untuk setiap penyakit
    //             $beliefs[$penyakitId] *= $result['belief'];
    //         }
    //     }
    //     // Normalisasi nilai belief
    //     $sumBelief = array_sum($beliefs);
    //     foreach ($beliefs as $penyakitId => $belief) {
    //         $dempsterResults[$penyakitId] = $belief / $sumBelief;
    //     }
    //     return $dempsterResults;
    // }

    public function DiagnosaStore(Request $request) {
        Diagnosa::create($request->all());
        if (count($request->gejalaId) > 0) {
            foreach ($request->gejalaId as $key => $value) {
                $multipleInsert = array(
                    'diagnosaId' => $request->diagnosaId,
                    'gejalaId' => $request->gejalaId[$key],
                    'nilaiKeyakinan' => $request->nilaiKeyakinan[$key],
                );
                DiagnosaDetail::create($multipleInsert);
            }
        }
        return Redirect::route('riwayat.diagnosa', Auth::user()->id)->with('message', 'Berhasil menyimpan hasil diagnosa terbaru');
    }

    public function SolusiPerawatan()
    {
        $solusi = Penyakit::all();
        return view('client-side.konsultasi.solusi', compact('solusi'));
    }

    public function RiwayatDiagnosa($userId)
    {
        $numtab = 1;
        $diagnosa = Diagnosa::with(['user'])->where('userId', $userId)->get();
        return view('client-side.konsultasi.riwayat-diagnosa', compact(['numtab', 'diagnosa']));
    }

    public function DetailDiagnosa($diagnosaId)
    {
        $numtab = 1;
        $diagnosa = Diagnosa::with(['user', 'penyakit'])->where('diagnosaId', $diagnosaId)->first();
        $detail = DiagnosaDetail::with(['gejala'])->where('diagnosaId', $diagnosaId)->get();
        return view('client-side.konsultasi.detail', compact(['numtab', 'diagnosa', 'detail']));
    }
}
