<?php
include 'koneksi.php';
include 'header1.php';

// **1. Cek akses user**
if (!isset($_SESSION['level']) || $_SESSION['level'] == "user") {
    header("location:login.php");
    exit();
}

?>

<?php
// **3. Mengambil data bobot dan alternatif dari tabel**
$query_bobot = mysqli_query($conn, "SELECT * FROM bobot1");
$bobot = mysqli_fetch_assoc($query_bobot);

$query_alternatif = mysqli_query($conn, "SELECT * FROM mahasiswa");
$nilai_alternatif = [];
while ($row = mysqli_fetch_assoc($query_alternatif)) {
    $nilai_alternatif[] = $row;
}


// **4. Definisi kriteria dan tipe atribut**
$kriteria = ["C1", "C2", "C3", "C4", "C5", "C6", "C7"];
$tipe_kriteria = [
    "C6" => "Cost",
    "C1" => "Benefit",
    "C2" => "Benefit",
    "C3" => "Benefit",
    "C4" => "Benefit",
    "C5" => "Benefit",
    "C7" => "Benefit"
];

// **5. Pastikan data tidak kosong sebelum perhitungan**
if (!$bobot || empty($nilai_alternatif)) {
    echo "<div class='alert alert-danger text-center'>Data tidak lengkap! Pastikan tabel Bobot Kriteria dan Nilai Alternatif telah diisi sebelum melakukan perhitungan.</div>";
    exit();
}

// **6. Normalisasi Bobot (Wj)**
$total_bobot = array_sum($bobot);
if ($total_bobot == 0) {
    echo "<div class='alert alert-danger text-center'>Total bobot tidak boleh nol!</div>";
    exit();
}

$w = [];
foreach ($kriteria as $key) {
    $w[$key] = $bobot[strtolower($key)] / $total_bobot;
}

// **7. Perhitungan Pangkat**
$pangkat = [];
foreach ($kriteria as $key) {
    $pangkat[$key] = ($tipe_kriteria[$key] == "Benefit") ? ($w[$key] * 1) : ($w[$key] * -1);
}

// **8. Perhitungan Vektor S**
$total_s = 0.0;
$hasil_vektor_s = [];
$nilai_bermasalah = false;  // Flag untuk menandakan apakah ada nilai yang 0

foreach ($nilai_alternatif as $alt) {
    $s = 1.0;
    foreach ($kriteria as $key) {
        // Periksa apakah ada nilai yang 0
        if ($alt[strtolower($key)] == 0) {
            $nilai_bermasalah = true;  // Tandai jika ada nilai 0
        }

        $s *= pow((float) $alt[strtolower($key)], (float) $pangkat[$key]);
    }
    $total_s += $s;
    $hasil_vektor_s[] = ["id" => $alt["id"], "alternatif" => $alt["alternatif"], "S" => $s];
}

// **9. Tampilkan pemberitahuan jika ada nilai 0**
if ($nilai_bermasalah) {
    echo "<div class='alert alert-warning text-center'>Peringatan: Ada nilai alternatif yang bernilai 0, ini dapat mempengaruhi hasil perhitungan!</div>";
}

// **9. Pastikan total S dihitung dengan benar**
if ($total_s == 0) {
    echo "<div class='alert alert-danger text-center'>Total S tidak boleh nol!</div>";
    exit();
}

// **9. Simpan atau Update Hasil Vektor S ke Database (vektors1)**
foreach ($hasil_vektor_s as $hasil) {
    $id_nilai = intval($hasil["id"]);  // Pastikan ID adalah angka
    $alternatif = mysqli_real_escape_string($conn, $hasil["alternatif"]);
    $nilai_s = $hasil["S"];

    // Cek apakah ID sudah ada di vektors1
    $cek_data = mysqli_query($conn, "SELECT * FROM vektors1 WHERE id = '$id_nilai'");

    if (mysqli_num_rows($cek_data) > 0) {
        // Update jika sudah ada
        mysqli_query($conn, "UPDATE vektors1 SET alternatif = '$alternatif', nilai = '$nilai_s' WHERE id = '$id_nilai'");
    } else {
        // Insert jika belum ada
        mysqli_query($conn, "INSERT INTO vektors1 (id, alternatif, nilai) VALUES ('$id_nilai', '$alternatif', '$nilai_s')");
    }
}


// **10. Perhitungan Vektor V**
$hasil_vektor_v = [];
foreach ($hasil_vektor_s as $alt) {
    $v = $alt["S"] / $total_s;
    $hasil_vektor_v[] = ["alternatif" => $alt["alternatif"], "S" => $alt["S"], "V" => $v];
}

// **11. Pastikan Total V = 1 dengan presisi tinggi**
$total_v = array_sum(array_column($hasil_vektor_v, 'V'));

// **12. Simpan hasil ke database (hasil1)**
mysqli_query($conn, "DELETE FROM hasil1");
foreach ($hasil_vektor_v as $hasil) {
    $alternatif = $hasil["alternatif"];
    $nilai_v = $hasil["V"];
    mysqli_query($conn, "INSERT INTO hasil1 (alternatif, nilai) VALUES ('$alternatif', '$nilai_v')");
}

// **13. Urutkan hasil berdasarkan Vektor V untuk perankingan**
$hasil_vektor_ranked = $hasil_vektor_v;
usort($hasil_vektor_ranked, fn($a, $b) => $b['V'] <=> $a['V']);



?>

<div id="layoutSidenav_content">
    <main>
    <div class="container-fluid mt-4">
            <div class="text-center mb-3">
                <h1 style="font-size: 28px; font-weight: bold;">HASIL PERHITUNGAN METODE WEIGHTED PRODUCT</h1>
            </div>


            <div class="card shadow-sm">
                <div class="card-body">
                    
                    <!-- Tabel Normalisasi Bobot -->
                    <div class="alert alert-info text-center mb-3 bg-primary text-white d-flex align-items-center justify-content-center" style="font-size: 20px; height: 50px;">
                        <strong>Normalisasi Bobot :</strong></div>

                    <table class="table table-bordered text-center w-100" style="font-size: 20;">
                        <thead class="table-primary"> 
                            <tr><?php foreach ($kriteria as $key) { echo "<th>{$key}</th>"; } ?></tr>
                        </thead>
                        <tbody>
                            <tr><?php foreach ($kriteria as $key) { echo "<td>" . number_format($w[$key], 6) . "</td>"; } ?></tr>
                        </tbody>
                    </table>
                    <h4 class="text-center"style="font-size: 18px;">Total Normaliasi Bobot ∑W : <?= number_format(array_sum($w), 6) ?></h4>
                    <br></br>
                    <br></br>

                    <!-- Tabel Pangkat -->
                    <div class="alert alert-info text-center mb-3 bg-primary text-white d-flex align-items-center justify-content-center" style="font-size: 20px; height: 50px;">
                        <strong>Pangkat :</strong></div>

                    <table class="table table-bordered text-center w-100">
                        <thead class="table-primary">
                            <tr><?php foreach ($kriteria as $key) { echo "<th>{$key}</th>"; } ?></tr>
                        </thead>
                        <tbody>
                            <tr><?php foreach ($kriteria as $key) { echo "<td>" . number_format($pangkat[$key], 6) . "</td>"; } ?></tr>
                        </tbody>
                    </table>
                    <br><br>
                    <br><br>

                    <!-- Tabel Vektor S -->
                    <div class="alert alert-info text-center mb-3 bg-primary text-white d-flex align-items-center justify-content-center" style="font-size: 20px; height: 50px;">
                        <strong>Nilai Vektor S :</strong></div>

                    <table class="table table-bordered text-center w-100">
                        <thead class="table-primary">
                            <tr><th>No.</th><th>Alternatif</th><th>Nilai</th></tr>
                        </thead>
                        <tbody>
                            <?php $i = 1; foreach ($hasil_vektor_s as $alt) { ?>
                                <tr>
                                    <td><?= $i++; ?></td>
                                    <td><?= $alt["alternatif"] ?></td>
                                    <td><?= number_format($alt["S"], 6) ?></td>
                                </tr>
                            <?php } ?>
                        </tbody>
                    </table>
                    <h4 class="text-center"style="font-size: 18px;">Total Vektor ∑S : <?= number_format($total_s, 6) ?></h4>
                    <br><br>
                    <br><br>

                    <!-- Tabel Vektor V -->
                    <div class="alert alert-info text-center mb-3 bg-primary text-white d-flex align-items-center justify-content-center" style="font-size: 20px; height: 50px;">
                    <strong>Nilai Vektor V :</strong></div>
                        <table class="table table-bordered text-center w-100">
                            <thead class="table-primary">
                                <tr><th>No.</th><th>Alternatif</th><th>Nilai</th></tr>
                            </thead>
                            <tbody>
                                <?php $i = 1; foreach ($hasil_vektor_v as $alt) { ?>
                                    <tr>
                                        <td><?= $i++; ?></td>
                                        <td><?= $alt["alternatif"] ?></td>
                                        <td><?= number_format($alt["V"], 6) ?></td>
                                    </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                        <h4 class="text-center" style="font-size: 18px;">Total Nilai Vektor ∑V : <?= number_format($total_v, 6) ?></h4>
                        <br><br>


                            <br><br>
                            <div class="text-center">    
                <a href="hasilspk1.php" class="btn btn-lg btn-outline-primary align-items-center">
                        <i class="fas fa-check"></i> Lihat Hasil dan Kesimpulan
                    </a>
                    <br><br>
            </div>
                        </tbody>
                    </table>

                    <br><br>
                    <br></br>

<?php
// Ambil data dari tabel hasil1 dengan urutan mahasiswa 1-15 (berdasarkan id_nilai)
$query = "SELECT alternatif, nilai FROM hasil1 ORDER BY id_hasil ASC";
$result = mysqli_query($conn, $query);

$alternatif = [];
$nilai = [];

while ($row = mysqli_fetch_assoc($result)) {
    $alternatif[] = $row['alternatif'];
    $nilai[] = $row['nilai'];
}

// Palet warna unik untuk setiap batang
$warna_pallete = [];
for ($i = 0; $i < count($alternatif); $i++) {
    $warna_pallete[] = "hsl(" . (360 / count($alternatif) * $i) . ", 70%, 50%)"; 
}
?>

<div class="alert alert-info text-center mb-3 bg-primary text-white d-flex align-items-center justify-content-center" style="font-size: 20px; height: 50px;">
<strong>Visualisasi Hasil :</strong></div>
<div class="card p-4 shadow-lg">
    <div class="chart-container" style="width: 100%; height: 75vh; overflow: hidden;">
        <canvas id="chartNilaiS"></canvas>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    document.addEventListener("DOMContentLoaded", function () {
        let ctx = document.getElementById('chartNilaiS').getContext('2d');
        let chartNilaiS = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: <?= json_encode($alternatif); ?>,
                datasets: [{
                    label: 'Nilai Vektor S',
                    data: <?= json_encode($nilai); ?>,
                    backgroundColor: <?= json_encode($warna_pallete); ?>,
                    borderColor: <?= json_encode($warna_pallete); ?>,
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                animation: {
                    duration: 2000,
                    easing: 'easeOutBounce'
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function (tooltipItem) {
                                let value = tooltipItem.raw;
                                return 'Nilai: ' + value.toFixed(6);  // Tampilkan 6 angka di belakang koma
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        ticks: {
                            autoSkip: false,
                            maxRotation: 20,
                            minRotation: 0,
                            font: {
                                size: 12
                            }
                        },
                        grid: {
                            display: false
                        }
                    },
                    y: {
                        beginAtZero: true,
                        grid: {
                            drawBorder: false
                        },
                        ticks: {
                            font: {
                                size: 14
                            }
                        }
                    }
                },
                layout: {
                    padding: {
                        left: 10,
                        right: 10,
                        top: 10,
                        bottom: 10
                    }
                }
            }
        });
    });
</script>


                </div>
            </div>

            <br><br>
 
                    <br><br>
                    <br><br>
        </div>
    </main>
</div> <!-- Tutup layoutSidenav_content -->
</div> <!-- Tutup layoutSidenav -->



