<?php
// **2. Connect to the database**
include 'koneksi.php';
include 'header2.php';

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

// **3. Retrieve weights and alternatives from the table**
$query_bobot = mysqli_query($conn, "SELECT * FROM bobot2");
$bobot = mysqli_fetch_assoc($query_bobot);

$query_alternatif = mysqli_query($conn, "SELECT id, nama, c1, c2, c3, c4, c5 FROM channel");
$nilai_alternatif = [];
while ($row = mysqli_fetch_assoc($query_alternatif)) {
    $nilai_alternatif[] = $row;
}

// **4. Define criteria and attribute types**
$kriteria = ["C1", "C2", "C3", "C4", "C5"];
$tipe_kriteria = [
    "C1" => "Benefit",
    "C2" => "Benefit",
    "C3" => "Benefit",
    "C4" => "Benefit",
    "C5" => "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 make sure the Criteria Weights and Alternative Values tables are filled before proceeding.</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. Vector S Calculation**
$total_s = 0.0;
$hasil_vektor_s = [];

foreach ($nilai_alternatif as $alt) {
    $s = 1.0;
    foreach ($kriteria as $key) {
        $s *= pow((float) $alt[strtolower($key)], (float) $pangkat[$key]);
    }
    $total_s += $s;
    $hasil_vektor_s[] = ["nama" => $alt["nama"], "S" => $s];
}

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

/// **9. Save or Update Vector S Results to Database (vektors2)**
$hasil_vektor_s = [];  // Array to store Vector S results

foreach ($nilai_alternatif as $alt) {
    $id_nilai = intval($alt["id"]);
    $nama = mysqli_real_escape_string($conn, $alt["nama"]);
    $nilai_s = 1.0;

    foreach ($kriteria as $key) {
        $nilai_s *= pow((float) $alt[strtolower($key)], (float) $pangkat[$key]);  
    }

    // Save to vector S result array
    $hasil_vektor_s[] = ["id" => $id_nilai, "nama" => $nama, "S" => $nilai_s];

    // Check if ID already exists in vektors2
    $cek_data = mysqli_query($conn, "SELECT id FROM vektors2 WHERE id = '$id_nilai'");
    
    if (mysqli_num_rows($cek_data) > 0) {
        // Update if exists
        mysqli_query($conn, "UPDATE vektors2 SET nama = '$nama', nilai = '$nilai_s' WHERE id = '$id_nilai'");
    } else {
        // Insert if not exists
        mysqli_query($conn, "INSERT INTO vektors2 (id, nama, nilai) VALUES ('$id_nilai', '$nama', '$nilai_s')");
    }
}

// **10. Ensure total S is calculated correctly**
$total_s = array_sum(array_column($hasil_vektor_s, 'S'));
if ($total_s == 0) {
    echo "<div class='alert alert-danger text-center'>⚠️ Total S must not be zero!</div>";
    exit();
}

// **11. Vector V Calculation (Use data from vektors2)**
$hasil_vektor_v = [];
foreach ($hasil_vektor_s as $alt) {  
    $v = $alt["S"] / $total_s;  // ✅ No duplicate S calculation
    $hasil_vektor_v[] = ["id" => $alt["id"], "nama" => $alt["nama"], "S" => $alt["S"], "V" => $v];
}

// **12. Ensure Total V = 1 with high precision**
$total_v = array_sum(array_column($hasil_vektor_v, 'V'));
if (abs($total_v - 1.0) > 0.0001) {  
    echo "<div class='alert alert-warning text-center'>⚠️ WARNING: Total Vector V value does not equal 1, please recheck the calculation!</div>";
}

// **13. Save results to database (hasil2)**
mysqli_query($conn, "DELETE FROM hasil2");  
foreach ($hasil_vektor_v as $hasil) {  
    $nama = mysqli_real_escape_string($conn, $hasil["nama"]);
    $nilai_v = $hasil["V"];
    mysqli_query($conn, "INSERT INTO hasil2 (nama, nilai) VALUES ('$nama', '$nilai_v')");
}


// **11. Ensure Total V = 1 with high precision**
$total_v = array_sum(array_column($hasil_vektor_v, 'V'));

// **12. Save results to database (hasil2)**
mysqli_query($conn, "DELETE FROM hasil2");
foreach ($hasil_vektor_v as $hasil) {
    $nama = mysqli_real_escape_string($conn, $hasil["nama"]);
    $nilai_v = $hasil["V"];
    mysqli_query($conn, "INSERT INTO hasil2 (nama, nilai) VALUES ('$nama', '$nilai_v')");
}

// **13. Sort results based on Vector V 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;">CALCULATION RESULT OF WEIGHTED PRODUCT METHOD</h1>
            </div>

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

                    <table class="table table-bordered text-center w-100">
                        <thead class="table-success">
                            <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 Normalized Weight ∑W: <?= number_format(array_sum($w), 6) ?></h4>
                    <br></br>
                    <br></br>

                    <!-- Power Table -->
                    <div class="alert alert-info text-center mb-3 bg-success text-white d-flex align-items-center justify-content-center" style="font-size: 20px; height: 50px;">
                        <strong>Exponent (Power):</strong>
                    </div>

                    <table class="table table-bordered text-center w-100">
                        <thead class="table-success">
                            <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-success text-white d-flex align-items-center justify-content-center" style="font-size: 20px; height: 50px;">
                        <strong>Vector S Values:</strong>
                    </div>

                    <table class="table table-bordered text-center w-100">
                        <thead class="table-success">
                            <tr><th>No.</th><th>Channel Name</th><th>Value</th></tr>
                        </thead>
                        <tbody>
                            <?php $i = 1; foreach ($hasil_vektor_s as $alt) { ?>
                                <tr>
                                    <td><?= $i++; ?></td>
                                    <td><?= $alt["nama"] ?></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-success text-white d-flex align-items-center justify-content-center" style="font-size: 20px; height: 50px;">
                        <strong>Vector V Values:</strong>
                    </div>

                    <table class="table table-bordered text-center w-100">
                        <thead class="table-success">
                            <tr><th>No.</th><th>Channel Name</th><th>Vector V</th></tr>
                        </thead>
                        <tbody>
                            <?php $i = 1; foreach ($hasil_vektor_v as $alt) { ?>
                                <tr>
                                    <td><?= $i++; ?></td>
                                    <td><?= $alt["nama"] ?></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="hasilspk2.php" class="btn btn-lg btn-outline-success align-items-center">
                            <i class="fas fa-check"></i> View Result and Conclusion
                        </a>
                    </div>
                    <br><br>
                    <br><br>
                </div>

<?php
// Fetch data from 'hasil2' table ordered by id_hasil (1-15)
$query = "SELECT nama, nilai FROM hasil2 ORDER BY id_hasil ASC";
$result = mysqli_query($conn, $query);

$nama = [];
$nilai = [];

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

// Unique color palette for each bar
$warna_pallete = [];
for ($i = 0; $i < count($nama); $i++) {
    $warna_pallete[] = "hsl(" . (360 / count($nama) * $i) . ", 70%, 50%)"; 
}
?>

<div class="alert alert-info text-center mb-3 bg-success 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($nama); ?>,
                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);  // Show 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>
       <br><br>
        </div>
    </main>
    <br><br>
</div>
