<?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 = [];
    $sql_products = "SELECT * FROM products ";
    $result_products = $conn->query($sql_products);

    if ($result_products) {
        while ($product = $result_products->fetch_assoc()) {
            $product_id = $product['id'];

            // Konversi tipe data dari database (0/1) ke boolean (false/true) untuk JSON
            $product['is_best_seller'] = (bool)$product['is_best_seller'];
            // Konversi harga ke tipe numerik yang benar
            $product['base_price'] = (float)$product['base_price'];

            // 1. Ambil Varian
            $stmt_variants = $conn->prepare("SELECT * FROM product_variants WHERE product_id = ?");
            $stmt_variants->bind_param("i", $product_id);
            $stmt_variants->execute();
            $variants_result = $stmt_variants->get_result();
            $variants = [];
            while ($variant_row = $variants_result->fetch_assoc()) {
                // Konversi atribut dari string JSON ke objek PHP
                $variant_row['attributes'] = json_decode($variant_row['attributes'], true);
                $variant_row['stock'] = (int)$variant_row['stock'];
                $variants[] = $variant_row;
            }
            $product['variants'] = $variants ?: [];
            
            // 2. Ambil Addons
            $stmt_addons = $conn->prepare("SELECT * FROM product_addons WHERE product_id = ?");
            $stmt_addons->bind_param("i", $product_id);
            $stmt_addons->execute();
            $addons_result = $stmt_addons->get_result();
            $addons = [];
            while ($addon_row = $addons_result->fetch_assoc()) {
                $addon_row['price'] = (float)$addon_row['price'];
                $addons[] = $addon_row;
            }
            $product['addons'] = $addons ?: [];
            
            // 3. Ambil Grup Kustomisasi (Condiment Groups) dan Opsi-nya
            $stmt_groups = $conn->prepare("SELECT * FROM condiment_groups WHERE product_id = ?");
            $stmt_groups->bind_param("i", $product_id);
            $stmt_groups->execute();
            $groups_result = $stmt_groups->get_result();
            $condiment_groups = [];
            
            while($group = $groups_result->fetch_assoc()){
                $group_id = $group['id'];
                $group['is_required'] = (bool)$group['is_required'];

                // Ambil Opsi untuk setiap grup
                $stmt_options = $conn->prepare("SELECT * FROM condiment_options WHERE group_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;
            }
            $product['condiment_groups'] = $condiment_groups;

            // Masukkan produk yang sudah lengkap ke array utama
            $products[] = $product;
        }
    }
    
    // Kembalikan semua data produk sebagai satu JSON besar
    echo json_encode($products);
}

// =================================================================
// 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();
?>