<?php
// api_server.php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Memuat koneksi database
require 'config.php';

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

// =================================================================
// AKSI 1: MENGAMBIL SEMUA DATA PRODUK SECARA TERSTRUKTUR
// =================================================================
if ($action === 'get_products') {
    try {
        $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
            ORDER BY m.name
        ";

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

        if (!$result_menus) {
            throw new Exception("Query error: " . $conn->error);
        }

        while ($menu_item = $result_menus->fetch_assoc()) {
            $product_id = $menu_item['id'];
            $product_kode = $menu_item['kode'];

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

            // --- 1. Buat Varian Default ---
            $menu_item['variants'] = [
                [
                    "id" => $menu_item['kode'] . "-default",
                    "stock" => (int)$menu_item['stock'],
                    "image_url" => $menu_item['image_url'] ?: 'https://via.placeholder.com/200x200?text=No+Image',
                    "attributes" => new stdClass()
                ]
            ];
            
            // --- 2. Addons (dikosongkan untuk sementara) ---
            $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'
                ORDER BY t.id
            ");
            
            if (!$stmt_groups) {
                throw new Exception("Prepare statement groups error: " . $conn->error);
            }
            
            $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'];
                $group['id'] = (int)$group['group_id']; // Pastikan ID adalah integer

                // Ambil Opsi untuk setiap grup
                $stmt_options = $conn->prepare("
                    SELECT 
                        nama_toping AS name, 
                        harga AS price 
                    FROM topping_items 
                    WHERE topping_id = ?
                    ORDER BY nama_toping
                ");
                
                if (!$stmt_options) {
                    throw new Exception("Prepare statement options error: " . $conn->error);
                }
                
                $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;
                }
                $stmt_options->close();
                
                $group['options'] = $options;
                $condiment_groups[] = $group;
            }
            $stmt_groups->close();
            
            $menu_item['condiment_groups'] = $condiment_groups;

            // Masukkan produk yang sudah lengkap ke array utama
            $products_kiosk_format[] = $menu_item;
        }
        
        // Response sukses
        echo json_encode([
            'success' => true,
            'data' => $products_kiosk_format,
            'count' => count($products_kiosk_format)
        ], JSON_PRETTY_PRINT);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'error' => $e->getMessage()
        ]);
    }
}

// =================================================================
// AKSI 2: MEMPROSES TRANSAKSI DARI KIOSK
// =================================================================
elseif ($action === 'process_transaction') {
    try {
        $input = file_get_contents('php://input');
        $cartData = json_decode($input, true);
        
        // Fallback untuk POST data
        if (empty($cartData)) {
            $cartData = json_decode($_POST['cartData'] ?? '{}', true);
        }

        if (empty($cartData) || !isset($cartData['customerName']) || !isset($cartData['items']) || empty($cartData['items'])) {
            throw new Exception('Data keranjang tidak lengkap atau tidak valid.');
        }

        $customerName = $cartData['customerName'];
        $customerPhone = $cartData['customerPhone'] ?? null;
        $items = $cartData['items'];
        $totalAmount = $cartData['total'];
        $brand = $cartData['brand'] ?? '001';
        $cab = $cartData['cab'] ?? '002';
        $transaction_code = 'TRX-' . time() . '-' . rand(100, 999);

        $conn->begin_transaction();

        // 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. Simpan items dan update stock
        $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 menus SET stock = stock - ? WHERE id = ? AND stock >= ?");
        if (!$stmtUpdateStock) {
            throw new Exception("Prepare statement update stock 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'] ?? null;

            // Simpan item transaksi - PERBAIKAN: sesuaikan tipe data parameter
// BENAR
$stmtItem->bind_param("iissidsss", $transaction_id, $item['productId'], $variant_id, $item['name'], $item['quantity'], $item['finalPrice'], $item_details_json, $brand, $cab);            
            $stmtItem->execute();

    /* NONAKTIFKAN SEMENTARA BAGIAN STOK
    // Update stock di tabel menus
    $stmtUpdateStock->bind_param("iii", $item['quantity'], $item['productId'], $item['quantity']);
    $stmtUpdateStock->execute();

    if ($stmtUpdateStock->affected_rows === 0) {
        throw new Exception("Stock 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,
            'transaction_id' => $transaction_id
        ]);

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

// =================================================================
// AKSI 3: HEALTH CHECK
// =================================================================
elseif ($action === 'health') {
    echo json_encode([
        'success' => true,
        'message' => 'API Server berjalan normal',
        'timestamp' => date('Y-m-d H:i:s'),
        'server' => $_SERVER['SERVER_NAME'] ?? 'localhost'
    ]);
}

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

$conn->close();
?>


