<?php
// File: crud_mobile.php (Versi Lengkap)

require 'config_pos.php'; // Mengimpor koneksi database

// Fungsi untuk mengeksekusi query dan mengembalikan hasil sebagai array
function executeQuery($conn, $sql) {
    $result = $conn->query($sql);
    if (!$result) {
        echo json_encode(["success" => false, "error" => "Query Error: " . $conn->error]);
        exit();
    }
    return $result->fetch_all(MYSQLI_ASSOC);
}

$action = isset($_GET['action']) ? $_GET['action'] : '';

switch ($action) {
    // Aksi untuk mengambil data awal (kategori, voucher, dll)
    case 'get_initial_data':
        $sql_categories = "SELECT kode AS id, name FROM menugroups ORDER BY name ASC";
        $categories = executeQuery($conn, $sql_categories);
        
        $vouchers = [];

        echo json_encode([
            "categories" => $categories,
            "vouchers" => $vouchers
        ]);
        break;

    // Aksi untuk mengambil daftar semua produk
    case 'get_products_list':
        $sql_products = "
            SELECT 
                m.kode AS id, 
                m.name, 
                m.price AS base_price, 
                m.image AS image_url,
                mg.kode AS category_id,
                mg.name AS category_name,
                'none' AS promo_type,
                0 AS promo_value,
                1 AS is_bestseller,
                50 AS stock,
                'Hokkaido-Ya' AS brand_name,
                m.keterangan AS description
            FROM menus m
            LEFT JOIN menugroups mg ON m.kgroup = mg.kode
            ORDER BY m.name ASC
        ";
        
        $products = executeQuery($conn, $sql_products);

        // Di sini kita tidak perlu mengambil topping karena akan diambil saat detail diklik
        // Ini membuat loading awal lebih cepat

        echo json_encode($products);
        break;

    // --- CASE BARU UNTUK MENGAMBIL DETAIL PRODUK ---
    case 'get_product_details':
        $productId = isset($_GET['id']) ? $_GET['id'] : 0;
        if ($productId === 0) {
            echo json_encode(["error" => "ID Produk tidak valid"]);
            exit();
        }

        $response = [
            'variants' => [], // Varian belum ada di skema DB POS, kita kirim array kosong
            'addons' => [],   // Addons belum ada di skema DB POS, kita kirim array kosong
            'condiment_groups' => []
        ];

        // 1. Cari grup topping yang terhubung dengan menu ini dari tabel 'btoppings'
        $sql_linked_toppings = "
            SELECT t.id, t.groupname, t.tipe, t.wajib, t.max 
            FROM btoppings bt
            JOIN toppings t ON bt.toppings = t.toping
            WHERE bt.barang = ? AND bt.ya = '1'
        ";
        $stmt_linked = $conn->prepare($sql_linked_toppings);
        $stmt_linked->bind_param("s", $productId);
        $stmt_linked->execute();
        $linked_toppings_result = $stmt_linked->get_result();
        $linked_toppings = $linked_toppings_result->fetch_all(MYSQLI_ASSOC);
        $stmt_linked->close();

        // 2. Untuk setiap grup topping yang terhubung, ambil item-itemnya
        foreach ($linked_toppings as $topping_group) {
            $sql_topping_items = "
                SELECT kode_toping AS id, nama_toping AS name, harga AS price, topping_id AS group_id
                FROM topping_items
                WHERE topping_id = ?
            ";
            $stmt_items = $conn->prepare($sql_topping_items);
            $stmt_items->bind_param("i", $topping_group['id']);
            $stmt_items->execute();
            $topping_items_result = $stmt_items->get_result();
            $topping_items = $topping_items_result->fetch_all(MYSQLI_ASSOC);
            $stmt_items->close();

            // 3. Susun data condiment group sesuai format yang dibutuhkan frontend
            $response['condiment_groups'][] = [
                'id' => $topping_group['id'],
                'title' => $topping_group['groupname'],
                'type' => $topping_group['tipe'] == '1' ? 'radio' : 'checkbox',
                'is_required' => $topping_group['wajib'] == '1',
                'options' => $topping_items
            ];
        }

        echo json_encode($response);
        break;
    
    default:
        echo json_encode(["success" => false, "error" => "Aksi tidak valid"]);
        break;
}

$conn->close();
?>