<?php

namespace App\Services;

use App\Models\Lapor;

class DecisionService
{
    public function hitungAHP()
    {
        $matrix = [
            [1,3,5,7],
            [1/3,1,3,5],
            [1/5,1/3,1,3],
            [1/7,1/5,1/3,1],
        ];

        $n = count($matrix);
        $colSum = array_fill(0,$n,0);

        for ($j=0;$j<$n;$j++){
            for ($i=0;$i<$n;$i++){
                $colSum[$j] += $matrix[$i][$j];
            }
        }

        $norm = [];
        for ($i=0;$i<$n;$i++){
            for ($j=0;$j<$n;$j++){
                $norm[$i][$j] = $matrix[$i][$j]/$colSum[$j];
            }
        }

        $bobot = [];
        for ($i=0;$i<$n;$i++){
            $bobot[$i] = array_sum($norm[$i])/$n;
        }

        $lambdaMax = 0;
        for ($i=0;$i<$n;$i++){
            $sum = 0;
            for ($j=0;$j<$n;$j++){
                $sum += $matrix[$i][$j]*$bobot[$j];
            }
            $lambdaMax += $sum/$bobot[$i];
        }

        $lambdaMax = $lambdaMax/$n;

        $CI = ($lambdaMax-$n)/($n-1);
        $RI = 0.90;
        $CR = $CI/$RI;

        return [
            'bobot'=>$bobot,
            'CR'=>$CR
        ];
    }

    public function hitungTOPSIS()
    {
        // ✅ HANYA DATA VALID
        $data = Lapor::whereIn('status',['menunggu','diproses','selesai'])->get();

        if($data->count() < 2) return;

        $ahp = $this->hitungAHP();
        $bobot = $ahp['bobot'];

        $rSerangan = ['Ringan'=>1,'Sedang'=>3,'Berat'=>5];
        $rLuas     = ['luas_kecil'=>1,'luas_sedang'=>3,'luas_besar'=>5];
        $rLama     = ['cepat'=>1,'menengah'=>3,'lama'=>5];
        $rHama     = ['Wereng'=>5,'Penggerek Batang'=>4,'Tikus'=>3,'Walang Sangit'=>2];

        $matrix = [];

        foreach ($data as $item){
            $matrix[] = [
                $rSerangan[$item->tingkat_serangan]/5,
                $rLuas[$item->luas_lahan]/5,
                $rLama[$item->lama_kejadian]/5,
                $rHama[$item->jenis_hama]/5,
            ];
        }

        $norm = [];

        for($j=0;$j<4;$j++){
            $sum=0;
            foreach($matrix as $row){
                $sum += pow($row[$j],2);
            }

            $akar = sqrt($sum);

            foreach($matrix as $i=>$row){
                $norm[$i][$j] = $row[$j]/$akar;
            }
        }

        $weighted = [];

        foreach($norm as $i=>$row){
            for($j=0;$j<4;$j++){
                $weighted[$i][$j] = $row[$j]*$bobot[$j];
            }
        }

        $idealPos = [];
        $idealNeg = [];

        for($j=0;$j<4;$j++){
            $col = array_column($weighted,$j);
            $idealPos[$j] = max($col);
            $idealNeg[$j] = min($col);
        }

        foreach($weighted as $i=>$row){

            $dPos=0;
            $dNeg=0;

            for($j=0;$j<4;$j++){
                $dPos += pow($row[$j]-$idealPos[$j],2);
                $dNeg += pow($row[$j]-$idealNeg[$j],2);
            }

            $dPos = sqrt($dPos);
            $dNeg = sqrt($dNeg);

            $nilai = $dNeg/($dPos+$dNeg);

            $data[$i]->update([
                'nilai_preferensi'=>$nilai
            ]);
        }

        $rank = Lapor::whereIn('status',['menunggu','diproses','selesai'])
            ->orderByDesc('nilai_preferensi')
            ->orderBy('created_at')
            ->get();

        foreach($rank as $i=>$item){
            $item->update(['ranking'=>$i+1]);
        }
    }


    public function getDetailTOPSIS()
{
    $data = Lapor::whereIn('status',['menunggu','diproses','selesai'])->get();

    $ahp = $this->hitungAHP();
    $bobot = $ahp['bobot'];

    $rSerangan = ['Ringan'=>1,'Sedang'=>3,'Berat'=>5];
    $rLuas     = ['luas_kecil'=>1,'luas_sedang'=>3,'luas_besar'=>5];
    $rLama     = ['cepat'=>1,'menengah'=>3,'lama'=>5];
    $rHama     = ['Wereng'=>5,'Penggerek Batang'=>4,'Tikus'=>3,'Walang Sangit'=>2];

    // ================= MATRIX =================
    $matrix = [];
    foreach ($data as $item){
        $matrix[] = [
            $rSerangan[$item->tingkat_serangan]/5,
            $rLuas[$item->luas_lahan]/5,
            $rLama[$item->lama_kejadian]/5,
            $rHama[$item->jenis_hama]/5,
        ];
    }

    // ================= NORMALISASI =================
    $norm = [];

    for($j=0;$j<4;$j++){
        $sum=0;
        foreach($matrix as $row){
            $sum += pow($row[$j],2);
        }

        $akar = sqrt($sum);

        foreach($matrix as $i=>$row){
            $norm[$i][$j] = $row[$j]/$akar;
        }
    }

    // ================= TERBOBOT =================
    $weighted = [];

    foreach($norm as $i=>$row){
        for($j=0;$j<4;$j++){
            $weighted[$i][$j] = $row[$j]*$bobot[$j];
        }
    }

    // ================= IDEAL =================
    $idealPos = [];
    $idealNeg = [];

    for($j=0;$j<4;$j++){
        $col = array_column($weighted,$j);
        $idealPos[$j] = max($col);
        $idealNeg[$j] = min($col);
    }

    // ================= JARAK =================
    $dPos = [];
    $dNeg = [];

    foreach($weighted as $i=>$row){

        $dp=0;
        $dn=0;

        for($j=0;$j<4;$j++){
            $dp += pow($row[$j]-$idealPos[$j],2);
            $dn += pow($row[$j]-$idealNeg[$j],2);
        }

        $dPos[$i] = sqrt($dp);
        $dNeg[$i] = sqrt($dn);
    }

    return compact('matrix','norm','weighted','idealPos','idealNeg','dPos','dNeg');
}
}


