<?php
include 'data.php';
// Membuat koneksi
$conn = new mysqli($servername, $username, $password, $dbname);

// Memeriksa koneksi
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Mendapatkan data toppings
$sql_toppings = "SELECT * FROM toppings";
$result_toppings = $conn->query($sql_toppings);

$toppings = array();

if ($result_toppings->num_rows > 0) {
    // Loop melalui setiap baris data
    while($row_toppings = $result_toppings->fetch_assoc()) {
        $topping_id = $row_toppings['id'];

        // Mendapatkan data topping_items berdasarkan topping_id
        $sql_topping_items = "SELECT * FROM topping_items WHERE topping_id = $topping_id";
        $result_topping_items = $conn->query($sql_topping_items);

        $items = array();

        if ($result_topping_items->num_rows > 0) {
            // Loop melalui setiap baris data
            while($row_topping_items = $result_topping_items->fetch_assoc()) {
                // Menambahkan item ke dalam array items
                $items[] = array(
                    "nama_toping" => $row_topping_items['nama_toping'],
                    "kode_toping" => $row_topping_items['kode_toping'],
                    "quantity" => $row_topping_items['quantity'],
                    "harga" => $row_topping_items['harga'],
                    "pilih" => $row_topping_items['pilih'],
                    "tipe" => $row_topping_items['tipe'],
                    "cek" => $row_topping_items['cek'],
                    "checked" => $row_topping_items['checked']
                );
            }
        }

        // Menambahkan data topping beserta items-nya ke dalam array toppings
        $toppings[] = array(
            "toping" => $row_toppings['toping'],
            "Group" => $row_toppings['groupname'],
            "tipe" => $row_toppings['tipe'],
            "wajib" => ($row_toppings['wajib'] == 1), // Mengubah nilai 0/1 menjadi true/false
            "max" => $row_toppings['max'],
            "pilih" => $row_toppings['pilih'],
            "ok" => $row_toppings['ok'],
            "items" => $items
        );
    }
}

// Menutup koneksi
$conn->close();

// Mengonversi array PHP ke dalam format JSON
$json_toppings = json_encode($toppings);

// Mencetak hasil dalam format JSON
echo $json_toppings;
?>
