<?php
// kiosk_api.php

header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Memuat koneksi database dari file konfigurasi yang sudah ada
require 'config.php';

// Mendapatkan aksi yang diminta dari frontend
$action = $_GET['action'] ?? $_POST['action'] ?? '';

// =================================================================
// AKSI 1: MENGAMBIL SEMUA DATA PRODUK SECARA TERSTRUKTUR
// =================================================================
if ($action === 'get_products') {
    $products_kiosk_format = [];

    // Query utama: Mengambil semua menu dan menggabungkannya dengan kategori dan sub-kategori
$sql_menus = "
    SELECT 
        m.id, 
        m.kode,
        m.name,
        m.price AS base_price,
        m.image AS image_url,
        m.stock, 
        m.keterangan as description,
        m.is_best_seller,
        -- JIKA mt.nama NULL, gunakan 'Lainnya'. JIKA mg.name NULL, gunakan 'Tanpa Sub-Kategori'.
        CONCAT(COALESCE(mt.nama, 'Lainnya'), ' / ', COALESCE(mg.name, 'Tanpa Sub-Kategori')) AS category,
        -- BARU: Menambahkan nama grup menu secara terpisah untuk sidebar
        COALESCE(mg.name, 'Lainnya') AS group_name,
        -- JIKA mt.nama NULL, gunakan 'Tanpa Brand' sebagai fallback
        COALESCE(mt.nama, 'Tanpa Brand') AS brand_name 
    FROM 
        menus m
    LEFT JOIN 
        menugroups mg ON m.kgroup = mg.kode
    LEFT JOIN 
        menutops mt ON mg.top = mt.nama
";

    $result_menus = $conn->query($sql_menus);

    if ($result_menus) {
        while ($menu_item = $result_menus->fetch_assoc()) {
            $product_id = $menu_item['id']; // Menggunakan ID dari tabel menus
            $product_kode = $menu_item['kode']; // Menggunakan kode dari tabel menus

            // --- Konversi Tipe Data ---
            $menu_item['id'] = (int)$menu_item['id'];
            $menu_item['base_price'] = (float)$menu_item['base_price'];
            $menu_item['is_best_seller'] = (bool)$menu_item['is_best_seller'];

            // --- 1. Buat Varian Default ---
            // Setiap menu di POS menjadi satu produk dengan satu varian di Kiosk
            $menu_item['variants'] = [
                [
                    "id" => $menu_item['kode'] . "-default", // ID unik untuk varian
                    "stock" => (int)$menu_item['stock'],
                    "image_url" => $menu_item['image_url'],
                    "attributes" => new stdClass() // Objek kosong karena tidak ada atribut
                ]
            ];
            
            // --- 2. Addons (dikosongkan) ---
            $menu_item['addons'] = [];

            // --- 3. Ambil dan Bentuk Condiment Groups ---
            $stmt_groups = $conn->prepare("
                SELECT 
                    t.id AS group_id,
                    t.groupname AS title,
                    CASE 
                        WHEN t.tipe = 'R' THEN 'radio' 
                        WHEN t.tipe = 'C' THEN 'checkbox' 
                        ELSE 'radio' 
                    END AS type,
                    t.wajib AS is_required
                FROM btoppings bt
                JOIN toppings t ON bt.toppings = t.toping
                WHERE bt.barang = ? AND bt.ya = '1'
            ");
            $stmt_groups->bind_param("s", $product_kode);
            $stmt_groups->execute();
            $groups_result = $stmt_groups->get_result();
            
            $condiment_groups = [];
            while($group = $groups_result->fetch_assoc()){
                $group_id = $group['group_id'];
                $group['is_required'] = (bool)$group['is_required'];

                // Ambil Opsi untuk setiap grup
                $stmt_options = $conn->prepare("
                    SELECT 
                        nama_toping AS name, 
                        harga AS price 
                    FROM topping_items 
                    WHERE topping_id = ?
                ");
                $stmt_options->bind_param("i", $group_id);
                $stmt_options->execute();
                $options_result = $stmt_options->get_result();
                $options = [];
                while ($option_row = $options_result->fetch_assoc()) {
                    $option_row['price'] = (float)$option_row['price'];
                    $options[] = $option_row;
                }
                $group['options'] = $options;
                $condiment_groups[] = $group;
            }
            $menu_item['condiment_groups'] = $condiment_groups;

            // Masukkan produk yang sudah lengkap ke array utama
            $products_kiosk_format[] = $menu_item;
        }
    }
    
    // Kembalikan semua data produk dalam format yang diinginkan Kiosk
    echo json_encode($products_kiosk_format, JSON_PRETTY_PRINT);
}

// =================================================================
// AKSI 2: MEMPROSES TRANSAKSI DARI KIOSK
// =================================================================
elseif ($action === 'process_transaction') {
    // Logika ini disalin dan disesuaikan dari crud.php Anda
    $cartData = json_decode($_POST['cartData'] ?? '{}', true);

    if (empty($cartData) || !isset($cartData['customerName']) || !isset($cartData['items']) || empty($cartData['items'])) {
        echo json_encode(['success' => false, 'error' => 'Data keranjang tidak lengkap atau tidak valid.']);
        $conn->close();
        exit();
    }

    $customerName = $cartData['customerName'];
    $customerPhone = $cartData['customerPhone'] ?? null;
    $items = $cartData['items'];
    $totalAmount = $cartData['total'];
    $brand = $cartData['brand'] ?? '001'; // Ambil dari data jika ada, atau default
    $cab = $cartData['cab'] ?? '002'; // Ambil dari data jika ada, atau default
    $transaction_code = 'TRX-' . time() . '-' . rand(100, 999);

    $conn->begin_transaction();

    try {
        // 1. Simpan header transaksi
        $stmtHeader = $conn->prepare("INSERT INTO transactions (transaction_code, customer_name, customer_phone, total_amount, brand, cab) VALUES (?, ?, ?, ?, ?, ?)");
        if (!$stmtHeader) throw new Exception("Prepare statement header gagal: " . $conn->error);
        
        $stmtHeader->bind_param("sssdss", $transaction_code, $customerName, $customerPhone, $totalAmount, $brand, $cab);
        $stmtHeader->execute();
        $transaction_id = $conn->insert_id;
        $stmtHeader->close();

        // 2. Loop melalui setiap item, simpan, dan potong stok
        $stmtItem = $conn->prepare("INSERT INTO transaction_items (transaction_id, product_id, variant_ref_id, product_name, quantity, price_per_item, item_details, brand, cab) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        if (!$stmtItem) throw new Exception("Prepare statement item gagal: " . $conn->error);
        
        $stmtUpdateStock = $conn->prepare("UPDATE product_variants SET stock = stock - ? WHERE id = ? AND stock >= ?");
        if (!$stmtUpdateStock) throw new Exception("Prepare statement update stok gagal: ". $conn->error);

        foreach ($items as $item) {
            $details = [
                'variant' => $item['variant'],
                'addons' => $item['addons'],
                'condiments' => $item['condiments'],
                'note' => $item['note']
            ];
            $item_details_json = json_encode($details);
            $variant_id = $item['variant']['id']; // ID dari tabel product_variants

            // Simpan item transaksi
            $stmtItem->bind_param("iisssisss", $transaction_id, $item['productId'], $variant_id, $item['name'], $item['quantity'], $item['finalPrice'], $item_details_json, $brand, $cab);
            $stmtItem->execute();

            // Potong stok
            $stmtUpdateStock->bind_param("iii", $item['quantity'], $variant_id, $item['quantity']);
            $stmtUpdateStock->execute();

            if ($stmtUpdateStock->affected_rows === 0) {
                throw new Exception("Stok untuk produk '". $item['name']. "' tidak mencukupi.");
            }
        }
        $stmtItem->close();
        $stmtUpdateStock->close();
        
        $conn->commit();
        echo json_encode(['success' => true, 'message' => 'Transaksi berhasil diproses.', 'transaction_code' => $transaction_code]);

    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
}

// =================================================================
// JIKA TIDAK ADA AKSI YANG SESUAI
// =================================================================
else {
    http_response_code(400); // Bad Request
    echo json_encode(['success' => false, 'error' => 'Aksi tidak valid atau tidak disediakan.']);
}

$conn->close();
?>