<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Criteria;
use App\Models\SubCriteria;
use App\Models\Extracuricullar;
use App\Models\LogActivity;

class PerhitunganController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function calculateBobotKriteria()
    {
        $criterias = Criteria::all();

        $totalKriteria = count($criterias);

        $bobotKriteria = [];

        foreach ($criterias as $criteria) {
            $sum = 0;

            $prioritas = $criteria->prioritas;
            $i = $prioritas - 1; // Karena indeks array dimulai dari 0, sedangkan prioritas dimulai dari 1

            // perulangan untuk setiap nilai prioritas pada kriteria
            for ($i ; $i < $totalKriteria; $i++) {
                $sum += 1 / ($i + 1);
            }

            $bobot = $sum / $totalKriteria;

            $bobotKriteria[$criteria->nama] = $bobot;

            $criteria->update(['bobot' => $bobot]);
            $criteria->save();
        }

        return redirect()->route('kriteria.index')->with('success', 'Bobot Kriteria Berhasil Dihitung dan Disimpan.');
    }

    public function calculateBobotSubKriteria()
     {
        $criterias = Criteria::all();

        foreach ($criterias as $criteria) {
            $subcriterias = SubCriteria::where('criteria_id', $criteria->id)->get();

            $totalSubKriteria = count($subcriterias);

            $bobotSubKriteria = [];

             foreach ($subcriterias as $subcriteria) {
                $sum = 0;

                $prioritas = $subcriteria->prioritas;
                $i = $prioritas - 1;

                for ($i ; $i < $totalSubKriteria; $i++) {
                    $sum += 1 / ($i + 1);
                }

                $bobot = $sum / $totalSubKriteria;

                $bobotSubKriteria[$subcriteria->nama] = $bobot;

                $subcriteria->update(['bobot' => $bobot]);
                $subcriteria->save();
             }
         }

         return redirect()->route('subkriteria.index')->with('success', 'Bobot Sub Kriteria Berhasil Dihitung dan Disimpan.');
    }

    public function penilaian()
    {
        $criterias = Criteria::all();
        $extracuricullars = Extracuricullar ::all();
        $subcriterias = Subcriteria::all();

        return view('penilaian.input-nilai', compact('criterias','extracuricullars','subcriterias'));
    }

    public function transformasiNilai(Request $request)
    {
        $subcriteriaData = $request->input('subcriteria');

        $transformedValues = [];

        foreach ($subcriteriaData as $extracurricularId => $criteriaData) {
            foreach ($criteriaData as $criteriaId => $subcriteriaId) {
                $subcriteria = SubCriteria::findOrFail($subcriteriaId);

                $bobot = $subcriteria->bobot;

                $transformedValues[$extracurricularId][$criteriaId] = $bobot;
            }
        }

        session(['transformedValues' => $transformedValues]);

        $criterias = Criteria::all();
        $extracuricullars = Extracuricullar::all();

        return view('perhitungan.transformasi-nilai', compact('criterias', 'extracuricullars', 'transformedValues'));
    }

    public function nilaiUtility(Request $request)
    {
        $transformedValues = session('transformedValues', []);

        $nilaiUtility = [];

        foreach ($transformedValues as $extracurricularId => $criteriaData) {
            foreach ($criteriaData as $criteriaId => $bobot) {
                $maxBobot = SubCriteria::where('criteria_id', $criteriaId)->max('bobot');
                $minBobot = SubCriteria::where('criteria_id', $criteriaId)->min('bobot');

                // // rumus nilai utility
                // $denominator = $maxBobot - $minBobot;
                // if ($denominator == 0) {
                //     $nilaiUtility[$extracurricularId][$criteriaId] = 0;
                // } else {
                //     $utility = 1*(($bobot - $minBobot) / $denominator);
                //     $nilaiUtility[$extracurricularId][$criteriaId] = $utility;
                //     // $nilaiUtility[$extracurricularId][$criteriaId] = number_format($utility, 2, '.', '');
                // }

                $utility = 1*(($bobot - $minBobot) / ($maxBobot - $minBobot));
                $nilaiUtility[$extracurricularId][$criteriaId] = $utility;
            }
        }

        session(['nilaiUtility' => $nilaiUtility]);

        $criterias = Criteria::all();
        $extracuricullars = Extracuricullar::all();

        return view('perhitungan.nilai-utility', compact('criterias', 'extracuricullars', 'nilaiUtility'));
    }

    public function nilaiAkhir(Request $request)
    {
        $nilaiUtility = session('nilaiUtility', []);

        $nilaiAkhir = [];
        $totalNilaiAkhir = [];

        foreach ($nilaiUtility as $extracurricularId => $criteriaData) {
            foreach ($criteriaData as $criteriaId => $utility) {

                $criteria = Criteria::find($criteriaId);
                if ($criteria) {
                    $bobotKriteria = $criteria->bobot;
                    $nilaiAkhir[$extracurricularId][$criteriaId] = $utility * $bobotKriteria;
                    // $nilaiAkhir[$extracurricularId][$criteriaId] = number_format($utility * $bobotKriteria, 2, '.', '');
                } else {
                    $nilaiAkhir[$extracurricularId][$criteriaId] = '0';
                }
            }

            $totalNilai = array_sum($nilaiAkhir[$extracurricularId]);
            $totalNilai = min($totalNilai, 100);
            $totalNilaiAkhir[$extracurricularId]= $totalNilai;
            // $totalNilaiAkhir[$extracurricularId] = number_format($totalNilai, 2, '.', '');
        }

        // Membuat koleksi dari nilai akhir yang bersifat multidimensi menjadi satu dimensi
        $totalAkhir = collect($nilaiAkhir)->flatten()->sum();

        $criterias = Criteria::all();
        $extracuricullars = Extracuricullar::all();

        return view('perhitungan.nilai-akhir', compact('criterias', 'extracuricullars', 'nilaiAkhir', 'totalNilaiAkhir'));
    }

    public function perangkingan(Request $request)
    {
        $nilaiUtility = session('nilaiUtility', []);

        $criterias = Criteria::all();
        $extracuricullars = Extracuricullar::all();

        $nilaiAkhir = [];
        $totalNilaiAkhir = [];
        $totalNilaiAkhirPersen = [];
        $peringkat = [];

        foreach ($nilaiUtility as $extracurricularId => $criteriaData) {
            $totalNilai = 0;

            foreach ($criteriaData as $criteriaId => $utility) {
                $criteria = Criteria::find($criteriaId);

                if ($criteria) {
                    $bobotKriteria = $criteria->bobot;
                    // $nilaiAkhir[$extracurricularId][$criteriaId] = number_format($utility * $bobotKriteria, 2, '.', '');
                    $nilaiAkhir[$extracurricularId][$criteriaId] = $utility * $bobotKriteria;

                    $totalNilai += $utility * $bobotKriteria;
                } else {
                    $nilaiAkhir[$extracurricularId][$criteriaId] = '0';
                }
            }

            // $totalNilaiAkhir[$extracurricularId] = number_format($totalNilai, 2, '.', '');
            $totalNilaiAkhir[$extracurricularId]= $totalNilai;

            $totalPersen = ($totalNilai ) * 100;
            $totalNilaiAkhirPersen[$extracurricularId] = number_format($totalPersen, 0, '.', '');

            $peringkat[$extracurricularId] = $totalPersen;
        }

        arsort($peringkat);

        return view('perhitungan.perangkingan', compact('criterias', 'extracuricullars', 'nilaiAkhir', 'totalNilaiAkhir', 'totalNilaiAkhirPersen', 'peringkat'));
    }

    public function getRiwayatHasil(Request $request)
    {
        $logsQuery = LogActivity::query();

        if (auth()->check() && auth()->user()->role !== 'admin') {
            $logsQuery->where('user_id', auth()->id());
        }

        if ($request->has('search')) {
            $search = $request->search;
            $logsQuery->where(function ($query) use ($search) {
                $query->whereHas('user', function ($query) use ($search) {
                    $query->where('name', 'like', '%' . $search . '%');
                })->orWhereHas('extracuricullar', function ($query) use ($search) {
                    $query->where('nama', 'like', '%' . $search . '%');
                });
            });
        }

        $logs = $logsQuery->paginate(10);

        $nilaiUtility = session('nilaiUtility', []);

        // Lakukan perhitungan perangkingan jika ada data
        if (!empty($nilaiUtility)) {
            $nilaiAkhir = [];
            foreach ($nilaiUtility as $extracurricularId => $criteriaData) {
                $totalNilai = 0;

                foreach ($criteriaData as $criteriaId => $utility) {
                    $criteria = Criteria::find($criteriaId);
                    if ($criteria) {
                        $bobotKriteria = $criteria->bobot;
                        $nilaiAkhir[$extracurricularId][$criteriaId] = $utility * $bobotKriteria;
                        $totalNilai += $utility * $bobotKriteria;
                    } else {
                        $nilaiAkhir[$extracurricularId][$criteriaId] = 0;
                    }
                }

                $totalNilaiAkhir[$extracurricularId] = $totalNilai;
                $totalPersen = $totalNilai * 100;
                $totalNilaiAkhirPersen[$extracurricularId] = $totalPersen;
                $peringkat[$extracurricularId] = $totalPersen;
            }

            arsort($peringkat);

            $extracurricularIds = array_keys($peringkat);
            $extracurricularId = reset($extracurricularIds);

            if (isset($nilaiAkhir[$extracurricularId])) {
                $nilaiAkhir = $nilaiAkhir[$extracurricularId];
                $userId = auth()->check() ? auth()->user()->id : 1;

                // Check apakah sudah ada log untuk ekskul peringkat pertama
                $existingLog = LogActivity::where('user_id', $userId)
                    ->where('extracuricullar_id', $extracurricularId)
                    ->first();

                // Jika belum ada log, buat log baru
                if (!$existingLog) {
                    LogActivity::create([
                        'user_id' => $userId,
                        'extracuricullar_id' => $extracurricularId,
                        'final_score' => $totalNilaiAkhir[$extracurricularId],
                    ]);
                } else {
                    // Jika sudah ada log, perbarui final score jika nilai akhir baru lebih tinggi
                    if ($existingLog->final_score < $totalNilaiAkhir[$extracurricularId]) {
                        $existingLog->final_score = $totalNilaiAkhir[$extracurricularId];
                        $existingLog->save();
                    }
                }

                return view('perhitungan.riwayat-hasil', compact('logs', 'userId', 'extracurricularId', 'nilaiAkhir'));
            } else {
                return redirect()->back()->with('error', 'Ekstrakurikuler tidak valid');
            }
        }

        return view('perhitungan.riwayat-hasil', compact('logs'));
    }

    public function index()
    {

    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
