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

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

?>

<?php
// **3. Retrieve weights and alternatives data from table**
$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. Define criteria and attribute types**
$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. Ensure data is not empty before calculation**
if (!$bobot || empty($nilai_alternatif)) {
    echo "<div class='alert alert-danger text-center'>Incomplete data! Please ensure that the Criteria Weights and Alternative Values tables are filled before calculation.</div>";
    exit();
}

// **6. Normalize Weights (Wj)**
$total_bobot = array_sum($bobot);
if ($total_bobot == 0) {
    echo "<div class='alert alert-danger text-center'>Total weight must not be zero!</div>";
    exit();
}

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

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

// **8. S Vector Calculation**
$total_s = 0.0;
$hasil_vektor_s = [];
$nilai_bermasalah = false;  // Flag to indicate if there is any 0 value

foreach ($nilai_alternatif as $alt) {
    $s = 1.0;
    foreach ($kriteria as $key) {
        // Check if any value is 0
        if ($alt[strtolower($key)] == 0) {
            $nilai_bermasalah = true;  // Mark if a value is 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. Display warning if there is a zero value**
if ($nilai_bermasalah) {
    echo "<div class='alert alert-warning text-center'>Warning: Some alternative values are 0, which may affect the result!</div>";
}

// **9. Make sure total S is correctly calculated**
if ($total_s == 0) {
    echo "<div class='alert alert-danger text-center'>Total S must not be zero!</div>";
    exit();
}

// **9. Save or Update S Vector results to database (vektors1)**
foreach ($hasil_vektor_s as $hasil) {
    $id_nilai = intval($hasil["id"]);  // Ensure ID is numeric
    $alternatif = mysqli_real_escape_string($conn, $hasil["alternatif"]);
    $nilai_s = $hasil["S"];

    // Check if ID already exists in vektors1
    $cek_data = mysqli_query($conn, "SELECT * FROM vektors1 WHERE id = '$id_nilai'");

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


// **10. V Vector Calculation**
$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. Ensure Total V = 1 with high precision**
$total_v = array_sum(array_column($hasil_vektor_v, 'V'));

// **12. Save results to 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. Sort results based on V Vector for ranking**
$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;">WEIGHTED PRODUCT METHOD CALCULATION RESULTS</h1>
            </div>

            <div class="card shadow-sm">
                <div class="card-body">
                    
                    <!-- Weight Normalization Table -->
                    <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>Weight Normalization :</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 Weight Normalization ∑W : <?= number_format(array_sum($w), 6) ?></h4>
                    <br></br>
                    <br></br>

                    <!-- Exponent Table -->
                    <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>Exponent :</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>

                    <!-- Vector S Table -->
                    <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>Vector S Value :</strong></div>

                    <table class="table table-bordered text-center w-100">
                        <thead class="table-primary">
                            <tr><th>No.</th><th>Alternative</th><th>Value</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 Vector ∑S : <?= number_format($total_s, 6) ?></h4>
                    <br><br>
                    <br><br>

                    <!-- Vector V Table -->
                    <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>Vector V Value :</strong></div>
                        <table class="table table-bordered text-center w-100">
                            <thead class="table-primary">
                                <tr><th>No.</th><th>Alternative</th><th>Value</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 Vector Value ∑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> View Result and Conclusion
                            </a>
                            <br><br>
                        </div>
                    </tbody>
                </table>

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

<?php
// Retrieve data from hasil1 table in order of students 1–15 (based on id_hasil)
$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'];
}

// Unique color palette for each bar
$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>Result Visualization :</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: 'Vector S Value',
                    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 'Value: ' + value.toFixed(6);  // Display 6 decimal places
                            }
                        }
                    }
                },
                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> <!-- Close layoutSidenav_content -->
</div> <!-- Close layoutSidenav -->
