<?php
// Start session
session_start();

// Include database connection
require_once "../config/connection.php";
require_once "../phpqrcode/qrlib.php";

// Redirect if not IT user
if (!is_logged_in() || !is_user_type('it')) {
    header("Location: ../login.php");
    exit();
}

// Get IT user data
$it_id = $_SESSION['user_id'];

// Handle AJAX requests
if (isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    if ($_POST['action'] === 'generate_qr') {
        $item_id = $_POST['item_id'];
        $code_barang = $_POST['code_barang'];
        
        try {
            // Generate QR code with kode_barang (5 digit format)
            $qr_content = $code_barang;
            
            ob_start();
            QRcode::png($qr_content, false, QR_ECLEVEL_L, 10, 2);
            $qr_image = ob_get_contents();
            ob_end_clean();
            
            $qr_base64 = 'data:image/png;base64,' . base64_encode($qr_image);
            
            // Update database
            $stmt = $conn->prepare("UPDATE color_stock_items SET qr_code = ? WHERE id = ?");
            $stmt->bind_param("si", $qr_base64, $item_id);
            
            if ($stmt->execute()) {
                log_activity($conn, $it_id, 'it', 'QR Code Generation', 'IT user generated QR code for item: ' . $code_barang);
                echo json_encode(['success' => true, 'qr_code' => $qr_base64]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to save QR code']);
            }
            $stmt->close();
            
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error generating QR code: ' . $e->getMessage()]);
        }
        exit();
    }
    
    if ($_POST['action'] === 'generate_all_qr') {
        $panel_id = $_POST['panel_id'];
        
        try {
            // Get all items for this panel that don't have QR codes yet
            $stmt = $conn->prepare("
                SELECT id, kode_barang 
                FROM color_stock_items 
                WHERE color_id = ? AND (qr_code IS NULL OR qr_code = '')
            ");
            $stmt->bind_param("i", $panel_id);
            $stmt->execute();
            $items = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            
            $generated_count = 0;
            
            foreach ($items as $item) {
                $qr_content = $item['kode_barang'];
                
                ob_start();
                QRcode::png($qr_content, false, QR_ECLEVEL_L, 10, 2);
                $qr_image = ob_get_contents();
                ob_end_clean();
                
                $qr_base64 = 'data:image/png;base64,' . base64_encode($qr_image);
                
                $update_stmt = $conn->prepare("UPDATE color_stock_items SET qr_code = ? WHERE id = ?");
                $update_stmt->bind_param("si", $qr_base64, $item['id']);
                
                if ($update_stmt->execute()) {
                    $generated_count++;
                }
                $update_stmt->close();
            }
            
            log_activity($conn, $it_id, 'it', 'Generate All QR Codes', 'IT user generated ' . $generated_count . ' QR codes for panel ID: ' . $panel_id);
            
            echo json_encode(['success' => true, 'generated_count' => $generated_count]);
            
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error generating QR codes: ' . $e->getMessage()]);
        }
        exit();
    }
    
    if ($_POST['action'] === 'search_items') {
        $search_code = trim($_POST['search']);
        
        try {
            $search_results = [];
            
            if (!empty($search_code)) {
                $query = "
                    SELECT 
                        csi.id as item_id,
                        csi.kode_barang,
                        csi.color_id,
                        csi.component_id,
                        mcp.code_color as panel_code,
                        mc.code_color as master_code,
                        mc.name_color as master_name,
                        cc.component_name
                    FROM color_stock_items csi
                    JOIN master_color_panel mcp ON csi.color_id = mcp.id
                    LEFT JOIN master_color mc ON mcp.master_color_id = mc.id
                    JOIN color_components cc ON csi.component_id = cc.id
                    WHERE csi.kode_barang LIKE ?
                    LIMIT 50
                ";
                
                $search_param = "%$search_code%";
                $stmt = $conn->prepare($query);
                $stmt->bind_param("s", $search_param);
                $stmt->execute();
                $results = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
                $stmt->close();
                
                foreach ($results as $result) {
                    $panel_id = $result['color_id'];
                    $component_id = $result['component_id'];
                    
                    if (!isset($search_results[$panel_id])) {
                        $search_results[$panel_id] = [];
                    }
                    
                    if (!isset($search_results[$panel_id][$component_id])) {
                        $search_results[$panel_id][$component_id] = [];
                    }
                    
                    $search_results[$panel_id][$component_id][] = $result['item_id'];
                }
            }
            
            echo json_encode(['success' => true, 'results' => $search_results]);
            
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error searching items: ' . $e->getMessage()]);
        }
        exit();
    }
}

// Get buyers for filter
$buyers_query = "SELECT id, nama_buyer FROM buyers ORDER BY nama_buyer";
$buyers_result = $conn->query($buyers_query);

$selected_buyer = isset($_GET['buyer']) ? (int)$_GET['buyer'] : 0;

// Build query for master color panels
$panel_where = "WHERE 1=1";
$params = [];
$types = "";

if ($selected_buyer > 0) {
    $panel_where .= " AND mcp.buyer_id = ?";
    $params[] = $selected_buyer;
    $types .= "i";
}

// Get all panels with their master color data
$panels_query = "
    SELECT 
        mcp.id as panel_id,
        mcp.code_color as panel_code,
        mcp.deskripsi,
        mcp.lemari,
        mcp.status,
        mcp.panel_type,
        mc.code_color as master_code,
        mc.name_color as master_name,
        b.nama_buyer,
        b.kode_buyer
    FROM master_color_panel mcp
    LEFT JOIN master_color mc ON mcp.master_color_id = mc.id
    JOIN buyers b ON mcp.buyer_id = b.id
    $panel_where
    ORDER BY mcp.code_color ASC
";

$stmt = $conn->prepare($panels_query);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$panels = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Get components and items for each panel
$panel_components = [];
$component_items = [];

foreach ($panels as $panel) {
    // Get components for this panel
    $components_query = "
        SELECT DISTINCT
            cc.id as component_id,
            cc.component_name,
            cpc.quantity
        FROM color_panel_components cpc
        JOIN color_components cc ON cpc.component_id = cc.id
        WHERE cpc.color_id = ?
        ORDER BY cc.component_name ASC
    ";
    
    $stmt = $conn->prepare($components_query);
    $stmt->bind_param("i", $panel['panel_id']);
    $stmt->execute();
    $components = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    
    $panel_components[$panel['panel_id']] = $components;
    
    // Get items for each component
    foreach ($components as $component) {
        $items_query = "
            SELECT 
                csi.id,
                csi.kode_barang,
                csi.stock_number,
                csi.status,
                csi.lokasi,
                csi.rack_no,
                csi.qr_code,
                csi.item_type,
                csi.tanggal_pembuatan,
                csi.tanggal_kedaluwarsa,
                csi.keterangan
            FROM color_stock_items csi
            WHERE csi.color_id = ? AND csi.component_id = ?
            ORDER BY 
                csi.item_type DESC,
                CAST(csi.kode_barang AS UNSIGNED) ASC
        ";
        
        $stmt = $conn->prepare($items_query);
        $stmt->bind_param("ii", $panel['panel_id'], $component['component_id']);
        $stmt->execute();
        $items = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        
        $component_items[$panel['panel_id']][$component['component_id']] = $items;
    }
}

$page_title = "Manajemen QR Code";
log_activity($conn, $it_id, 'it', 'QR Code Generator Access', 'IT user accessed QR code generator page');
include '../template_it/header.php';
?>

<!-- Main Content Area -->
<main class="flex-1 p-6 overflow-auto bg-gradient-to-br from-blue-100 via-teal-100 to-green-100">
    <!-- Header -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h2 class="text-2xl font-bold text-gray-800 mb-4">
            <i class="fas fa-qrcode mr-2 text-blue-600"></i>
            Manajemen QR Code Color Panel
        </h2>
        
        <!-- Filters and Search -->
        <div class="flex flex-col md:flex-row gap-4 mb-4">
            <!-- Buyer Filter -->
            <div class="flex-1">
                <label for="buyer_filter" class="block text-sm font-medium text-gray-700 mb-2">
                    <i class="fas fa-filter mr-1"></i> Filter Buyer:
                </label>
                <select id="buyer_filter" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="0">Semua Buyer</option>
                    <?php 
                    $buyers_result->data_seek(0);
                    while ($buyer = $buyers_result->fetch_assoc()): 
                    ?>
                        <option value="<?php echo $buyer['id']; ?>" <?php echo $selected_buyer == $buyer['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($buyer['nama_buyer']); ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>
            
            <!-- Search -->
            <div class="flex-1">
                <label for="search_input" class="block text-sm font-medium text-gray-700 mb-2">
                    <i class="fas fa-search mr-1"></i> Cari Code Barang:
                </label>
                <input 
                    type="text" 
                    id="search_input" 
                    placeholder="Masukkan code barang (contoh: 00001)"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
            </div>
        </div>
        
        <!-- Info Badge -->
        <div class="mt-4 p-3 bg-blue-50 border-l-4 border-blue-500 rounded">
            <p class="text-sm text-blue-700">
                <i class="fas fa-info-circle mr-2"></i>
                <strong>Format Code:</strong> Semua code menggunakan format 5 digit (00001, 00002, dst). 
                <span class="font-semibold text-blue-800">Master Color</span> →
                <span class="font-semibold text-green-600">Panel</span> →
                <span class="font-semibold text-purple-600">Copy Items</span>
            </p>
        </div>
    </div>

    <!-- Panels -->
    <div class="space-y-4" id="panels-container">
        <?php foreach ($panels as $panel): ?>
            <div class="bg-white rounded-lg shadow-md overflow-hidden panel-card border-l-4 <?php echo $panel['panel_type'] === 'master_color' ? 'border-blue-500' : 'border-green-500'; ?>" data-panel-id="<?php echo $panel['panel_id']; ?>">
                <!-- Panel Header -->
                <div 
                    class="cursor-pointer p-4 bg-gradient-to-r <?php echo $panel['panel_type'] === 'master_color' ? 'from-blue-50 to-indigo-50 hover:from-blue-100 hover:to-indigo-100' : 'from-green-50 to-teal-50 hover:from-green-100 hover:to-teal-100'; ?> transition-colors duration-200"
                    onclick="togglePanelComponents(<?php echo $panel['panel_id']; ?>)"
                    id="panel-header-<?php echo $panel['panel_id']; ?>"
                >
                    <div class="flex justify-between items-center">
                        <div class="flex items-center space-x-4">
                            <div class="flex items-center space-x-2">
                                <i class="fas <?php echo $panel['panel_type'] === 'master_color' ? 'fa-crown text-blue-600' : 'fa-copy text-green-600'; ?> text-lg"></i>
                                <i class="fas fa-chevron-right transform transition-transform duration-200" id="chevron-panel-<?php echo $panel['panel_id']; ?>"></i>
                                <h3 class="text-lg font-bold text-gray-800">
                                    <?php echo htmlspecialchars($panel['panel_code']); ?>
                                </h3>
                            </div>
                            
                            <!-- Panel Type Badge -->
                            <span class="px-3 py-1 text-xs font-bold rounded-full <?php echo $panel['panel_type'] === 'master_color' ? 'bg-blue-600 text-white' : 'bg-green-600 text-white'; ?>">
                                <?php echo $panel['panel_type'] === 'master_color' ? 'MASTER PANEL' : 'COPY PANEL'; ?>
                            </span>
                            
                            <!-- Master Color Reference -->
                            <?php if (!empty($panel['master_code'])): ?>
                            <span class="px-3 py-1 text-xs font-medium rounded-full bg-purple-100 text-purple-800">
                                <i class="fas fa-link mr-1"></i> Master: <?php echo htmlspecialchars($panel['master_code']); ?>
                            </span>
                            <?php endif; ?>
                            
                            <span class="px-3 py-1 text-xs font-medium rounded-full bg-gray-100 text-gray-800">
                                <?php echo htmlspecialchars($panel['nama_buyer']); ?>
                            </span>
                            <span class="px-3 py-1 text-xs font-medium rounded-full bg-yellow-100 text-yellow-800">
                                <?php echo htmlspecialchars($panel['deskripsi']); ?>
                            </span>
                            <span class="px-2 py-1 text-xs font-medium rounded bg-gray-200 text-gray-700">
                                Lemari <?php echo htmlspecialchars($panel['lemari']); ?>
                            </span>
                        </div>
                        
                        <div class="flex items-center space-x-2">
                            <span class="text-sm text-gray-600">
                                <?php echo count($panel_components[$panel['panel_id']]); ?> Components
                            </span>
                            <button 
                                class="px-3 py-1 bg-green-500 text-white text-xs rounded hover:bg-green-600 transition-colors shadow-md"
                                onclick="generateAllQR(<?php echo $panel['panel_id']; ?>); event.stopPropagation();"
                                title="Generate QR untuk semua item yang belum punya QR"
                            >
                                <i class="fas fa-qrcode mr-1"></i> Generate All QR
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Components Container -->
                <div 
                    class="hidden p-4 bg-gray-50" 
                    id="panel-components-<?php echo $panel['panel_id']; ?>"
                >
                    <?php if (empty($panel_components[$panel['panel_id']])): ?>
                        <p class="text-gray-500 text-center py-4">Tidak ada component untuk panel ini.</p>
                    <?php else: ?>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            <?php foreach ($panel_components[$panel['panel_id']] as $component): ?>
                                <div class="bg-white rounded-lg border-2 border-indigo-200 shadow-sm hover:shadow-md transition-shadow duration-200 component-card" data-panel-id="<?php echo $panel['panel_id']; ?>" data-component-id="<?php echo $component['component_id']; ?>">
                                    <div 
                                        class="cursor-pointer p-4 bg-gradient-to-r from-indigo-50 to-purple-50 hover:from-indigo-100 hover:to-purple-100 transition-colors duration-200"
                                        onclick="toggleComponentItems(<?php echo $panel['panel_id']; ?>, <?php echo $component['component_id']; ?>)"
                                    >
                                        <div class="flex justify-between items-center">
                                            <div class="flex items-center space-x-2">
                                                <i class="fas fa-cube text-indigo-600"></i>
                                                <i class="fas fa-chevron-right transform transition-transform duration-200 text-sm" id="chevron-comp-<?php echo $panel['panel_id']; ?>-<?php echo $component['component_id']; ?>"></i>
                                                <h4 class="font-semibold text-gray-800"><?php echo htmlspecialchars($component['component_name']); ?></h4>
                                            </div>
                                            <span class="text-xs text-gray-600 bg-white px-2 py-1 rounded shadow-sm">
                                                <?php echo count($component_items[$panel['panel_id']][$component['component_id']]); ?> Items
                                            </span>
                                        </div>
                                    </div>
                                    
                                    <!-- Items Container -->
                                    <div class="hidden p-3 bg-gray-50" id="component-items-<?php echo $panel['panel_id']; ?>-<?php echo $component['component_id']; ?>">
                                        <?php if (empty($component_items[$panel['panel_id']][$component['component_id']])): ?>
                                            <p class="text-gray-500 text-center text-sm py-2">Tidak ada item.</p>
                                        <?php else: ?>
                                            <div class="space-y-2">
                                                <?php foreach ($component_items[$panel['panel_id']][$component['component_id']] as $item): ?>
                                                    <div class="bg-white rounded border border-gray-200 p-3 item-card hover:shadow-md transition-shadow" data-item-id="<?php echo $item['id']; ?>" data-code="<?php echo htmlspecialchars($item['kode_barang']); ?>">
                                                        <div class="flex justify-between items-start mb-2">
                                                            <div class="flex-1">
                                                                <div class="flex items-center space-x-2 mb-1">
                                                                    <p class="font-bold text-base text-gray-800"><?php echo htmlspecialchars($item['kode_barang']); ?></p>
                                                                    <?php if ($item['item_type'] === 'master_color'): ?>
                                                                    <span class="px-2 py-0.5 text-xs font-bold rounded bg-blue-600 text-white">
                                                                        <i class="fas fa-crown mr-1"></i> MASTER
                                                                    </span>
                                                                    <?php else: ?>
                                                                    <span class="px-2 py-0.5 text-xs font-bold rounded bg-green-600 text-white">
                                                                        <i class="fas fa-copy mr-1"></i> COPY
                                                                    </span>
                                                                    <?php endif; ?>
                                                                </div>
                                                                <p class="text-xs text-gray-500">
                                                                    <i class="fas fa-map-marker-alt mr-1"></i> <?php echo htmlspecialchars($item['lokasi']); ?> | 
                                                                    <i class="fas fa-layer-group mr-1"></i> Rack: <?php echo htmlspecialchars($item['rack_no']); ?>
                                                                </p>
                                                            </div>
                                                            <span class="px-2 py-1 text-xs rounded-full font-semibold <?php 
                                                                echo $item['status'] === 'Tersedia' ? 'bg-green-100 text-green-800' : 
                                                                    ($item['status'] === 'Dipinjam' ? 'bg-yellow-100 text-yellow-800' : 
                                                                    ($item['status'] === 'Rusak' ? 'bg-red-100 text-red-800' : 'bg-gray-100 text-gray-800')); 
                                                            ?>">
                                                                <?php echo htmlspecialchars($item['status']); ?>
                                                            </span>
                                                        </div>
                                                        
                                                        <div class="flex justify-between items-center gap-2 mt-2">
                                                            <?php if (!empty($item['qr_code'])): ?>
                                                                <button 
                                                                    class="flex-1 px-2 py-1.5 bg-blue-500 text-white text-xs font-medium rounded hover:bg-blue-600 transition-colors shadow-sm"
                                                                    onclick="viewQR('<?php echo $item['id']; ?>', '<?php echo htmlspecialchars($item['kode_barang']); ?>')"
                                                                >
                                                                    <i class="fas fa-qrcode mr-1"></i>View QR
                                                                </button>
                                                                <button 
                                                                    class="flex-1 px-2 py-1.5 bg-purple-500 text-white text-xs font-medium rounded hover:bg-purple-600 transition-colors shadow-sm"
                                                                    onclick="printQR('<?php echo $item['id']; ?>')"
                                                                >
                                                                    <i class="fas fa-print mr-1"></i>Print
                                                                </button>
                                                            <?php else: ?>
                                                                <button 
                                                                    class="w-full px-2 py-1.5 bg-green-500 text-white text-xs font-medium rounded hover:bg-green-600 transition-colors shadow-sm"
                                                                    onclick="generateQR(<?php echo $item['id']; ?>, '<?php echo htmlspecialchars($item['kode_barang']); ?>')"
                                                                    id="generate-btn-<?php echo $item['id']; ?>"
                                                                >
                                                                    <i class="fas fa-plus mr-1"></i>Generate QR
                                                                </button>
                                                            <?php endif; ?>
                                                        </div>
                                                        
                                                        <?php if (!empty($item['keterangan'])): ?>
                                                        <div class="mt-2 p-2 bg-blue-50 rounded text-xs text-gray-600 border-l-2 border-blue-400">
                                                            <i class="fas fa-info-circle mr-1"></i><?php echo htmlspecialchars($item['keterangan']); ?>
                                                        </div>
                                                        <?php endif; ?>
                                                    </div>
                                                <?php endforeach; ?>
                                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</main>

<!-- QR Code Modal -->
<div id="qrModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50 flex items-center justify-center">
    <div class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4">
        <div class="p-6">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold text-gray-800">
                    <i class="fas fa-qrcode mr-2 text-blue-600"></i> QR Code
                </h3>
                <button onclick="closeQRModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            
            <div class="text-center">
                <div id="qrCodeDisplay" class="mb-4"></div>
                <p id="qrCodeText" class="text-sm text-gray-600 mb-4 font-semibold"></p>
                <button 
                    id="printQRBtn"
                    class="px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600 transition-colors shadow-md"
                    onclick="printCurrentQR()"
                >
                    <i class="fas fa-print mr-2"></i>Print QR Code
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Loading Overlay -->
<div id="loadingOverlay" class="fixed inset-0 bg-black bg-opacity-50 hidden z-40 flex items-center justify-center">
    <div class="bg-white rounded-lg p-6 text-center shadow-xl">
        <div class="animate-spin rounded-full h-12 w-12 border-b-4 border-blue-500 mx-auto mb-4"></div>
        <p class="text-gray-600 font-medium">Processing...</p>
    </div>
</div>

<script>
let currentQRData = null;
let searchTimeout = null;

// Toggle panel components visibility
function togglePanelComponents(panelId) {
    const componentsContainer = document.getElementById(`panel-components-${panelId}`);
    const chevron = document.getElementById(`chevron-panel-${panelId}`);
    
    if (componentsContainer.classList.contains('hidden')) {
        componentsContainer.classList.remove('hidden');
        chevron.style.transform = 'rotate(90deg)';
    } else {
        componentsContainer.classList.add('hidden');
        chevron.style.transform = 'rotate(0deg)';
    }
}

// Toggle component items visibility
function toggleComponentItems(panelId, componentId) {
    const itemsContainer = document.getElementById(`component-items-${panelId}-${componentId}`);
    const chevron = document.getElementById(`chevron-comp-${panelId}-${componentId}`);
    
    if (itemsContainer.classList.contains('hidden')) {
        itemsContainer.classList.remove('hidden');
        chevron.style.transform = 'rotate(90deg)';
    } else {
        itemsContainer.classList.add('hidden');
        chevron.style.transform = 'rotate(0deg)';
    }
}

// Optimized search functionality with debouncing
document.getElementById('search_input').addEventListener('input', function() {
    const searchTerm = this.value.trim();
    
    // Clear previous timeout
    if (searchTimeout) {
        clearTimeout(searchTimeout);
    }
    
    // If search is empty, show all
    if (searchTerm === '') {
        showAllItems();
        return;
    }
    
    // Wait 500ms after user stops typing before searching
    searchTimeout = setTimeout(() => {
        performSearch(searchTerm);
    }, 500);
});

function performSearch(searchTerm) {
    const formData = new FormData();
    formData.append('action', 'search_items');
    formData.append('search', searchTerm);
    
    fetch(window.location.pathname, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            filterItemsBySearch(data.results);
        }
    })
    .catch(error => {
        console.error('Search error:', error);
    });
}

function filterItemsBySearch(results) {
    // Hide all panels first
    document.querySelectorAll('.panel-card').forEach(panel => {
        panel.style.display = 'none';
    });
    
    // Show only matching panels and expand them
    for (const panelId in results) {
        const panelCard = document.querySelector(`.panel-card[data-panel-id="${panelId}"]`);
        if (panelCard) {
            panelCard.style.display = 'block';
            
            // Expand panel
            const componentsContainer = document.getElementById(`panel-components-${panelId}`);
            const chevronPanel = document.getElementById(`chevron-panel-${panelId}`);
            componentsContainer.classList.remove('hidden');
            chevronPanel.style.transform = 'rotate(90deg)';
            
            // Hide all components first
            panelCard.querySelectorAll('.component-card').forEach(compCard => {
                compCard.style.display = 'none';
            });
            
            // Show only matching components
            for (const componentId in results[panelId]) {
                const componentCard = panelCard.querySelector(`.component-card[data-component-id="${componentId}"]`);
                if (componentCard) {
                    componentCard.style.display = 'block';
                    
                    // Expand component
                    const itemsContainer = document.getElementById(`component-items-${panelId}-${componentId}`);
                    const chevronComp = document.getElementById(`chevron-comp-${panelId}-${componentId}`);
                    itemsContainer.classList.remove('hidden');
                    chevronComp.style.transform = 'rotate(90deg)';
                    
                    // Hide all items first
                    componentCard.querySelectorAll('.item-card').forEach(itemCard => {
                        itemCard.style.display = 'none';
                    });
                    
                    // Show only matching items
                    results[panelId][componentId].forEach(itemId => {
                        const itemCard = componentCard.querySelector(`.item-card[data-item-id="${itemId}"]`);
                        if (itemCard) {
                            itemCard.style.display = 'block';
                            itemCard.classList.add('bg-yellow-50', 'border-yellow-300', 'border-2');
                        }
                    });
                }
            }
        }
    }
}

function showAllItems() {
    // Show all panels
    document.querySelectorAll('.panel-card').forEach(panel => {
        panel.style.display = 'block';
    });
    
    // Show all components
    document.querySelectorAll('.component-card').forEach(card => {
        card.style.display = 'block';
    });
    
    // Show all items and remove highlight
    document.querySelectorAll('.item-card').forEach(card => {
        card.style.display = 'block';
        card.classList.remove('bg-yellow-50', 'border-yellow-300', 'border-2');
    });
}

// Buyer filter
document.getElementById('buyer_filter').addEventListener('change', function() {
    const buyerId = this.value;
    const currentUrl = new URL(window.location);
    
    if (buyerId && buyerId !== '0') {
        currentUrl.searchParams.set('buyer', buyerId);
    } else {
        currentUrl.searchParams.delete('buyer');
    }
    
    window.location.href = currentUrl.toString();
});

// Generate single QR code
function generateQR(itemId, codeBarang) {
    document.getElementById('loadingOverlay').classList.remove('hidden');
    
    const formData = new FormData();
    formData.append('action', 'generate_qr');
    formData.append('item_id', itemId);
    formData.append('code_barang', codeBarang);
    
    fetch(window.location.pathname, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        document.getElementById('loadingOverlay').classList.add('hidden');
        
        if (data.success) {
            alert(`QR Code berhasil di-generate untuk ${codeBarang}!`);
            location.reload();
        } else {
            alert('Gagal generate QR Code: ' + data.message);
        }
    })
    .catch(error => {
        document.getElementById('loadingOverlay').classList.add('hidden');
        alert('Error: ' + error.message);
    });
}

// Generate all QR codes for a panel
function generateAllQR(panelId) {
    if (!confirm('Generate QR code untuk semua item di panel ini yang belum memiliki QR code?')) {
        return;
    }
    
    document.getElementById('loadingOverlay').classList.remove('hidden');
    
    const formData = new FormData();
    formData.append('action', 'generate_all_qr');
    formData.append('panel_id', panelId);
    
    fetch(window.location.pathname, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        document.getElementById('loadingOverlay').classList.add('hidden');
        
        if (data.success) {
            alert(`Berhasil generate ${data.generated_count} QR Code!`);
            location.reload();
        } else {
            alert('Gagal generate QR Codes: ' + data.message);
        }
    })
    .catch(error => {
        document.getElementById('loadingOverlay').classList.add('hidden');
        alert('Error: ' + error.message);
    });
}

// View QR Code
function viewQR(itemId, codeBarang) {
    fetch(`get_qr_data.php?item_id=${itemId}`)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            currentQRData = data.item;
            document.getElementById('qrCodeDisplay').innerHTML = `<img src="${data.item.qr_code}" alt="QR Code" class="mx-auto border-4 border-gray-200 rounded-lg shadow-lg" style="max-width: 250px;">`;
            document.getElementById('qrCodeText').textContent = `Code Barang: ${codeBarang}`;
            document.getElementById('qrModal').classList.remove('hidden');
        } else {
            alert('Gagal memuat QR Code: ' + data.message);
        }
    })
    .catch(error => {
        alert('Error: ' + error.message);
    });
}

// Print QR Code
function printQR(itemId) {
    window.open(`print_qr.php?item_id=${itemId}`, '_blank');
}

function printCurrentQR() {
    if (currentQRData) {
        window.open(`print_qr.php?item_id=${currentQRData.id}`, '_blank');
    }
}

// Close modal
function closeQRModal() {
    document.getElementById('qrModal').classList.add('hidden');
    currentQRData = null;
}

// Close modal on outside click
document.getElementById('qrModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeQRModal();
    }
});

// Close modal on ESC key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeQRModal();
    }
});
</script>

<?php include '../template_it/footer.php'; ?>