<?php

namespace App\Http\Controllers;

use App\Models\Bobot;
use App\Models\Gejala;
use App\Models\Penyakit;
use App\Models\Rule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redirect;

class RuleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $numtab = 1;
        $rules = Rule::with(['penyakit'])->orderBy('penyakitId')->latest()->get()->unique('penyakitId');
        return view('server-side.pages.manajemen-data.rules.data', compact(
            ['numtab', 'rules',]
        ));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $penyakit = Penyakit::all();
        $gejala = Gejala::all();
        $bobot = Bobot::all();
        return view('server-side.pages.manajemen-data.rules.create', compact(['penyakit', 'gejala', 'bobot']));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        if (count($request->gejalaId) > 0) {
            $gejalaIds = $request->gejalaId;
            $penyakitId = $request->penyakitId;
            $nilaiPakar = $request->nilaiPakar;

            foreach ($gejalaIds as $key => $gejalaId) {
                $existingRules = Rule::where('gejalaId', $gejalaId)->get();
                $totalNilaiPakar = $existingRules->sum('nilaiPakar');
                $jumlahGejala = $existingRules->count();
                $nilaiPakarBaru = $nilaiPakar[$key];
                $belief = ($totalNilaiPakar + $nilaiPakarBaru) / ($jumlahGejala + 1);

                $multipleInsert = array(
                    'penyakitId' => $penyakitId,
                    'gejalaId' => $gejalaId,
                    'nilaiPakar' => $nilaiPakarBaru,
                    'belief' => $belief,
                );
                Rule::create($multipleInsert);

                Rule::where('gejalaId', $gejalaId)->update(['belief' => $belief]);
            }
            return Redirect::route('rule.index')->with('message', 'Berhasil menambah data rules baru dan memperbarui nilai belief');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Rule  $rule
     * @return \Illuminate\Http\Response
     */
    public function show($penyakitId)
    {
        $numtab = 1;
        $detail = Rule::with(['penyakit', 'gejala'])->where('penyakitId', $penyakitId)->latest()->get();
        return view('server-side.pages.manajemen-data.rules.detail', compact(
            ['numtab', 'detail']
        ));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Rule  $rule
     * @return \Illuminate\Http\Response
     */
    public function edit($penyakitId)
    {
        $numtab = 1;
        $bobot = Bobot::all();
        $gejala = Gejala::all();
        $rules = Rule::with(['penyakit', 'gejala'])->where('penyakitId', $penyakitId)->latest()->get();
        return view('server-side.pages.manajemen-data.rules.edit', compact(
            ['numtab', 'bobot', 'gejala', 'rules']
        ));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Rule  $rule
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        if (count($request->gejalaId) > 0) {
            $gejalaIds = $request->gejalaId;
            $penyakitId = $request->penyakitId;
            $nilaiPakar = $request->nilaiPakar;
            $ids = $request->id;

            $existingRules = Rule::whereIn('id', $ids)->get()->keyBy('id');

            foreach ($gejalaIds as $key => $gejalaId) {
                $multipleUpdate = array(
                    'penyakitId' => $penyakitId,
                    'gejalaId' => $gejalaId,
                    'nilaiPakar' => $nilaiPakar[$key],
                );
                Rule::find($ids[$key])->update($multipleUpdate);
            }

            $gejalaTerdampak = array_unique($gejalaIds);
            foreach ($gejalaTerdampak as $gejalaId) {
                $rules = Rule::where('gejalaId', $gejalaId)->get();
                $totalNilaiPakar = $rules->sum('nilaiPakar');
                $jumlahGejala = $rules->count();

                $belief = $jumlahGejala > 0 ? $totalNilaiPakar / $jumlahGejala : 0;

                Rule::where('gejalaId', $gejalaId)->update(['belief' => $belief]);
            }

            foreach ($existingRules as $rule) {
                if (!in_array($rule->gejalaId, $gejalaIds)) {
                    $rules = Rule::where('gejalaId', $rule->gejalaId)->get();
                    $totalNilaiPakar = $rules->sum('nilaiPakar');
                    $jumlahGejala = $rules->count();

                    $belief = $jumlahGejala > 0 ? $totalNilaiPakar / $jumlahGejala : 0;

                    Rule::where('gejalaId', $rule->gejalaId)->update(['belief' => $belief]);
                }
            }

            return Redirect::route('rule.index')->with('message', 'Berhasil melakukan perubahan pada data rules diagnosa yang dipilih');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Rule  $rule
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, Rule $rule)
    {
        $gejalaId = $rule->gejalaId;
        $rule->delete();

        $rules = Rule::where('gejalaId', $gejalaId)->get();
        $totalNilaiPakar = $rules->sum('nilaiPakar');
        $jumlahGejala = $rules->count();

        $belief = $jumlahGejala > 0 ? $totalNilaiPakar / $jumlahGejala : 0;
        Rule::where('gejalaId', $gejalaId)->update(['belief' => $belief]);

        return Redirect::route('rule.show', $request->penyakitId)->with('message', 'Berhasil menghapus rule gejala diagnosa yang dipilih');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Rule  $rule
     * @return \Illuminate\Http\Response
     */
    public function destroyByPenyakit($penyakitId)
    {
        $rules = Rule::where('penyakitId', $penyakitId)->get();
        $gejalaIds = $rules->pluck('gejalaId')->unique();

        Rule::where('penyakitId', $penyakitId)->delete();

        foreach ($gejalaIds as $gejalaId) {
            $rules = Rule::where('gejalaId', $gejalaId)->get();
            $totalNilaiPakar = $rules->sum('nilaiPakar');
            $jumlahGejala = $rules->count();

            $belief = $jumlahGejala > 0 ? $totalNilaiPakar / $jumlahGejala : 0;
            Rule::where('gejalaId', $gejalaId)->update(['belief' => $belief]);
        }

        return Redirect::route('rule.index')->with('message', 'Berhasil menghapus data rules diagnosa penyakit yang dipilih');
    }
}
