<?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
            $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
                create_audit_log($conn, 'QR Code Generation', $it_id, 'it', 'IT user generated QR code for item ID: ' . $item_id);
                
                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') {
        $color_id = $_POST['color_id'];
        
        try {
            // Get all items for this color that don't have QR codes
            $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", $color_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++;
                    // Log individual generation
                    create_audit_log($conn, 'Bulk QR Generation', $it_id, 'it', 'IT user generated QR code for item ID: ' . $item['id']);
                }
                $update_stmt->close();
            }
            
            // Log bulk generation
            create_audit_log($conn, 'Generate All QR Codes', $it_id, 'it', 'IT user generated QR codes for ' . $generated_count . ' items');
            
            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();
    }
}

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

// Get search parameter
$search_code = isset($_GET['search']) ? trim($_GET['search']) : '';
$selected_buyer = isset($_GET['buyer']) ? (int)$_GET['buyer'] : 0;

// Build query for colors
$color_where = "WHERE 1=1";
$params = [];
$types = "";

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

// Get all colors with their data
$colors_query = "
    SELECT 
        mcp.id,
        mcp.code_color,
        mcp.deskripsi,
        mcp.lemari,
        mcp.status,
        b.nama_buyer,
        b.kode_buyer
    FROM master_color_panel mcp
    JOIN buyers b ON mcp.buyer_id = b.id
    $color_where
    ORDER BY mcp.code_color ASC
";

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

// Get items for each color and check for search
$color_items = [];
$search_found_color_id = null;

foreach ($colors as $color) {
    $items_query = "
        SELECT 
            csi.id,
            csi.kode_barang,
            csi.stock_number,
            csi.status,
            csi.lokasi,
            csi.rack_no,
            csi.qr_code,
            csi.tanggal_pembuatan,
            csi.tanggal_kedaluwarsa,
            csi.keterangan,
            cc.component_name
        FROM color_stock_items csi
        JOIN color_components cc ON csi.component_id = cc.id
        WHERE csi.color_id = ?
        ORDER BY 
            CAST(SUBSTRING(csi.rack_no, 2) AS UNSIGNED) ASC,
            csi.rack_no ASC
    ";
    
    $stmt = $conn->prepare($items_query);
    $stmt->bind_param("i", $color['id']);
    $stmt->execute();
    $items = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    
    $color_items[$color['id']] = $items;
    
    // Check if search code exists in this color's items
    if (!empty($search_code) && $search_found_color_id === null) {
        foreach ($items as $item) {
            if (stripos($item['kode_barang'], $search_code) !== false) {
                $search_found_color_id = $color['id'];
                break;
            }
        }
    }
}

// Set page title
$page_title = "Manajemen QR Code";

// Log activity
create_audit_log($conn, 'QR Code Generator Access', $it_id, 'it', 'IT user accessed QR code generator page');

// Include header
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">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">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 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">Cari Code Barang:</label>
                <input 
                    type="text" 
                    id="search_input" 
                    placeholder="Masukkan code barang (contoh: CP.0001)"
                    value="<?php echo htmlspecialchars($search_code); ?>"
                    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>
    </div>

    <!-- Color Panels -->
    <div class="space-y-4">
        <?php foreach ($colors as $color): ?>
            <div class="bg-white rounded-lg shadow-md overflow-hidden">
                <!-- Color Header -->
                <div 
                    class="cursor-pointer p-4 bg-gradient-to-r from-blue-50 to-indigo-50 hover:from-blue-100 hover:to-indigo-100 transition-colors duration-200 <?php echo ($search_found_color_id == $color['id']) ? 'bg-yellow-100 border-l-4 border-yellow-500' : ''; ?>"
                    onclick="toggleColorItems(<?php echo $color['id']; ?>)"
                    id="color-header-<?php echo $color['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 fa-chevron-right transform transition-transform duration-200" id="chevron-<?php echo $color['id']; ?>"></i>
                                <h3 class="text-lg font-semibold text-gray-800">
                                    <?php echo htmlspecialchars($color['kode_buyer']); ?> - <?php echo htmlspecialchars($color['code_color']); ?>
                                </h3>
                            </div>
                            <span class="px-2 py-1 text-xs font-medium rounded-full bg-blue-100 text-blue-800">
                                <?php echo htmlspecialchars($color['nama_buyer']); ?>
                            </span>
                            <span class="px-2 py-1 text-xs font-medium rounded-full bg-gray-100 text-gray-800">
                                Lemari <?php echo htmlspecialchars($color['lemari']); ?>
                            </span>
                        </div>
                        
                        <div class="flex items-center space-x-2">
                            <span class="text-sm text-gray-600">
                                <?php echo count($color_items[$color['id']]); ?> Item
                            </span>
                            <button 
                                class="px-3 py-1 bg-green-500 text-white text-xs rounded hover:bg-green-600 transition-colors"
                                onclick="generateAllQR(<?php echo $color['id']; ?>); event.stopPropagation();"
                                id="generate-all-<?php echo $color['id']; ?>"
                            >
                                Generate All QR
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Color Items -->
                <div 
                    class="hidden p-4 bg-gray-50" 
                    id="color-items-<?php echo $color['id']; ?>"
                    <?php echo ($search_found_color_id == $color['id']) ? 'style="display: block;"' : ''; ?>
                >
                    <?php if (empty($color_items[$color['id']])): ?>
                        <p class="text-gray-500 text-center py-4">Tidak ada item untuk color code ini.</p>
                    <?php else: ?>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            <?php foreach ($color_items[$color['id']] as $item): ?>
                                <div class="bg-white rounded-lg border border-gray-200 p-4 hover:shadow-md transition-shadow duration-200 <?php echo (!empty($search_code) && stripos($item['kode_barang'], $search_code) !== false) ? 'bg-yellow-50 border-yellow-300' : ''; ?>">
                                    <div class="flex justify-between items-start mb-3">
                                        <div>
                                            <h4 class="font-semibold text-gray-800"><?php echo htmlspecialchars($item['kode_barang']); ?></h4>
                                            <p class="text-sm text-gray-600"><?php echo htmlspecialchars($item['component_name']); ?></p>
                                            <p class="text-xs text-gray-500">Rack: <?php echo htmlspecialchars($item['rack_no']); ?></p>
                                        </div>
                                        <span class="px-2 py-1 text-xs rounded-full <?php 
                                            echo $item['status'] === 'Tersedia' ? 'bg-green-100 text-green-800' : 
                                                ($item['status'] === 'Dipinjam' ? '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">
                                        <!-- QR Code Display/Generate -->
                                        <div class="flex items-center space-x-2">
                                            <?php if (!empty($item['qr_code'])): ?>
                                                <button 
                                                    class="px-3 py-1 bg-blue-500 text-white text-xs rounded hover:bg-blue-600 transition-colors"
                                                    onclick="viewQR('<?php echo $item['id']; ?>', '<?php echo htmlspecialchars($item['kode_barang']); ?>')"
                                                >
                                                    <i class="fas fa-qrcode mr-1"></i>View QR
                                                </button>
                                            <?php else: ?>
                                                <button 
                                                    class="px-3 py-1 bg-green-500 text-white text-xs rounded hover:bg-green-600 transition-colors"
                                                    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>
                                        
                                        <!-- Print Button -->
                                        <?php if (!empty($item['qr_code'])): ?>
                                            <button 
                                                class="px-3 py-1 bg-purple-500 text-white text-xs rounded hover:bg-purple-600 transition-colors"
                                                onclick="printQR('<?php echo $item['id']; ?>')"
                                            >
                                                <i class="fas fa-print mr-1"></i>Print
                                            </button>
                                        <?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">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"></p>
                <button 
                    id="printQRBtn"
                    class="px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600 transition-colors"
                    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">
        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mx-auto mb-4"></div>
        <p class="text-gray-600">Generating QR Code...</p>
    </div>
</div>

<script>
let currentQRData = null;

// Toggle color items visibility
function toggleColorItems(colorId) {
    const itemsContainer = document.getElementById(`color-items-${colorId}`);
    const chevron = document.getElementById(`chevron-${colorId}`);
    
    if (itemsContainer.style.display === 'none' || itemsContainer.style.display === '') {
        itemsContainer.style.display = 'block';
        chevron.style.transform = 'rotate(90deg)';
    } else {
        itemsContainer.style.display = 'none';
        chevron.style.transform = 'rotate(0deg)';
    }
}

// Auto-open search result color
<?php if ($search_found_color_id): ?>
document.addEventListener('DOMContentLoaded', function() {
    toggleColorItems(<?php echo $search_found_color_id; ?>);
});
<?php endif; ?>

// Search functionality
document.getElementById('search_input').addEventListener('input', function() {
    const searchTerm = this.value.trim();
    const currentUrl = new URL(window.location);
    
    if (searchTerm) {
        currentUrl.searchParams.set('search', searchTerm);
    } else {
        currentUrl.searchParams.delete('search');
    }
    
    if (searchTerm.length >= 3 || searchTerm === '') {
        window.location.href = currentUrl.toString();
    }
});

// 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) {
            // Replace generate button with view button
            const generateBtn = document.getElementById(`generate-btn-${itemId}`);
            generateBtn.outerHTML = `
                <button 
                    class="px-3 py-1 bg-blue-500 text-white text-xs rounded hover:bg-blue-600 transition-colors"
                    onclick="viewQR('${itemId}', '${codeBarang}')"
                >
                    <i class="fas fa-qrcode mr-1"></i>View QR
                </button>
            `;
            
            // Add print button
            generateBtn.parentElement.parentElement.innerHTML += `
                <button 
                    class="px-3 py-1 bg-purple-500 text-white text-xs rounded hover:bg-purple-600 transition-colors"
                    onclick="printQR('${itemId}')"
                >
                    <i class="fas fa-print mr-1"></i>Print
                </button>
            `;
            
            alert('QR Code berhasil di-generate!');
        } 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 color
function generateAllQR(colorId) {
    if (!confirm('Generate QR code untuk semua item yang belum memiliki QR code?')) {
        return;
    }
    
    document.getElementById('loadingOverlay').classList.remove('hidden');
    
    const formData = new FormData();
    formData.append('action', 'generate_all_qr');
    formData.append('color_id', colorId);
    
    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(); // Reload to show updated buttons
        } 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) {
    // Get QR code data from server
    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" style="max-width: 200px;">`;
            document.getElementById('qrCodeText').textContent = `Code Barang: ${codeBarang}`;
            document.getElementById('qrModal').classList.remove('hidden');
        } else {
            alert('Gagal memuat QR Code');
        }
    })
    .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();
    }
});
</script>

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