<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Alternatif;
use App\Models\Kriteria;
use App\Models\Penilaian;
use PDF;
use Carbon\Carbon;

class AlgoritmaController extends Controller
{
    public function __construct()
    {
        return $this->middleware('auth');
    }

    public function index()
    {
        $alternatif = Alternatif::with('penilaian.crips')->get();
        $kriteria = Kriteria::get();
        $penilaian = Penilaian::with('crips', 'alternatif')->get();

        if (count($penilaian) == 0) {
            return redirect(route('penilaian.index'))->with('empty', 'Data Kosong Silahkan Isi Terlebih Dahulu');
        }

        // Mencari min max untuk normalisasi
        $minMax = [];
        foreach ($kriteria as $value) {
            foreach ($penilaian as $value_1) {
                if ($value->id == $value_1->crips->kriteria_id) {
                    if ($value->attribut == 'Benefit' || $value->attribut == 'Cost') {
                        $minMax[$value->id][] = $value_1->crips->bobot;
                    }
                }
            }
        }

        // Normalisasi
        $normalisasi = [];
        foreach ($penilaian as $value_1) {
            $namaAlternatif = $value_1->alternatif->nama_alternatif ?? 'Alternatif_' . $value_1->alternatif_id;
            foreach ($kriteria as $value) {
                if ($value->id == $value_1->crips->kriteria_id) {
                    if ($value->attribut == 'Benefit') {
                        $normalisasi[$namaAlternatif][$value->id] = $value_1->crips->bobot / max($minMax[$value->id]);
                    } elseif ($value->attribut == 'Cost') {
                        $normalisasi[$namaAlternatif][$value->id] = min($minMax[$value->id]) / $value_1->crips->bobot;
                    }
                }
            }
        }

        // Perangkingan
        $ranking = [];
        foreach ($normalisasi as $key => $value) {
            $rank = [];
            foreach ($kriteria as $value_1) {
                $rank[] = $value[$value_1->id] * ($value_1->bobot / 100);
            }
            $ranking[] = [
                'name' => $key,
                'normalisasi' => $value,
                'score' => array_sum($rank)
            ];
        }

        // Urutkan berdasarkan skor dan tambahkan peringkat
        $sortedData = collect($ranking)->sortByDesc('score')->values()->map(function ($item, $index) {
            $item['rank'] = $index + 1;
            return $item;
        })->toArray();

        // Debugging (hapus setelah verifikasi)
        // dd($sortedData);

        return view('admin.perhitungan.index', compact('alternatif', 'kriteria', 'normalisasi', 'sortedData'));
    }

    public function downloadPDF()
    {
        setlocale(LC_ALL, 'IND');
        $tanggal = Carbon::now()->formatLocalized('%A, %d %B %Y');
        $alternatif = Alternatif::with('penilaian.crips')->get();
        $kriteria = Kriteria::with('crips')->orderBy('nama_kriteria', 'ASC')->get();
        $penilaian = Penilaian::with('crips', 'alternatif')->get();

        if (count($penilaian) == 0) {
            return redirect(route('penilaian.index'));
        }

        // Mencari min max untuk normalisasi
        $minMax = [];
        foreach ($kriteria as $value) {
            foreach ($penilaian as $value_1) {
                if ($value->id == $value_1->crips->kriteria_id) {
                    if ($value->attribut == 'Benefit' || $value->attribut == 'Cost') {
                        $minMax[$value->id][] = $value_1->crips->bobot;
                    }
                }
            }
        }

        // Normalisasi
        $normalisasi = [];
        foreach ($penilaian as $value_1) {
            $namaAlternatif = $value_1->alternatif->nama_alternatif ?? 'Alternatif_' . $value_1->alternatif_id;
            foreach ($kriteria as $value) {
                if ($value->id == $value_1->crips->kriteria_id) {
                    if ($value->attribut == 'Benefit') {
                        $normalisasi[$namaAlternatif][$value->id] = $value_1->crips->bobot / max($minMax[$value->id]);
                    } elseif ($value->attribut == 'Cost') {
                        $normalisasi[$namaAlternatif][$value->id] = min($minMax[$value->id]) / $value_1->crips->bobot;
                    }
                }
            }
        }

        // Perangkingan
        $ranking = [];
        foreach ($normalisasi as $key => $value) {
            $rank = [];
            foreach ($kriteria as $value_1) {
                $rank[] = $value[$value_1->id] * ($value_1->bobot / 100);
            }
            $ranking[] = [
                'name' => $key,
                'normalisasi' => $value,
                'score' => array_sum($rank)
            ];
        }

        // Urutkan berdasarkan skor dan tambahkan peringkat
        $sortedData = collect($ranking)->sortByDesc('score')->values()->map(function ($item, $index) {
            $item['rank'] = $index + 1;
            return $item;
        })->toArray();

        $pdf = PDF::loadView('admin.perhitungan.perhitungan-pdf', compact('alternatif', 'kriteria', 'normalisasi', 'sortedData', 'tanggal'));
        $pdf->setPaper('A3', 'portrait');
        return $pdf->stream('perhitungan.pdf');
    }
}