<?php
// Start session
session_start();

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

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

// Include QR Code library
require_once "../phpqrcode/qrlib.php";

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

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

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'generate_qr':
                $item_id = intval($_POST['item_id']);
                $stmt = $conn->prepare("SELECT kode_barang FROM color_stock_items_surabaya WHERE id = ?");
                $stmt->bind_param("i", $item_id);
                $stmt->execute();
                $result = $stmt->get_result();
                
                if ($row = $result->fetch_assoc()) {
                    $kode_barang = $row['kode_barang'];
                    
                    // Generate QR code
                    ob_start();
                    QRcode::png($kode_barang, null, QR_ECLEVEL_L, 4, 2);
                    $qr_image = ob_get_contents();
                    ob_end_clean();
                    
                    $qr_code_base64 = 'data:image/png;base64,' . base64_encode($qr_image);
                    
                    // Update database
                    $update_stmt = $conn->prepare("UPDATE color_stock_items_surabaya SET qr_code = ? WHERE id = ?");
                    $update_stmt->bind_param("si", $qr_code_base64, $item_id);
                    $update_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_code_base64]);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Item not found']);
                }
                $stmt->close();
                exit();
                
            case 'generate_all_qr':
                $color_id = intval($_POST['color_id']);
                $stmt = $conn->prepare("SELECT id, kode_barang FROM color_stock_items_surabaya WHERE color_id = ? AND (qr_code IS NULL OR qr_code = '')");
                $stmt->bind_param("i", $color_id);
                $stmt->execute();
                $result = $stmt->get_result();
                
                $generated_count = 0;
                while ($row = $result->fetch_assoc()) {
                    $item_id = $row['id'];
                    $kode_barang = $row['kode_barang'];
                    
                    // Generate QR code
                    ob_start();
                    QRcode::png($kode_barang, null, QR_ECLEVEL_L, 4, 2);
                    $qr_image = ob_get_contents();
                    ob_end_clean();
                    
                    $qr_code_base64 = 'data:image/png;base64,' . base64_encode($qr_image);
                    
                    // Update database
                    $update_stmt = $conn->prepare("UPDATE color_stock_items_surabaya SET qr_code = ? WHERE id = ?");
                    $update_stmt->bind_param("si", $qr_code_base64, $item_id);
                    $update_stmt->execute();
                    
                    // Log activity
                    create_audit_log($conn, 'Bulk QR Generation', $it_id, 'it', "IT user generated QR code for item ID: $item_id");
                    
                    $generated_count++;
                }
                
                echo json_encode(['success' => true, 'generated_count' => $generated_count]);
                $stmt->close();
                exit();
        }
    }
}

// Get buyers_surabaya for filter
$buyers_surabaya_stmt = $conn->prepare("SELECT id, nama_buyer FROM buyers_surabaya ORDER BY nama_buyer");
$buyers_surabaya_stmt->execute();
$buyers_surabaya_result = $buyers_surabaya_stmt->get_result();
$buyers_surabaya = [];
while ($row = $buyers_surabaya_result->fetch_assoc()) {
    $buyers_surabaya[] = $row;
}
$buyers_surabaya_stmt->close();

// Set page title
$page_title = "QR Code Generator - Color Code";

// 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 Section -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            <div>
                <h2 class="text-2xl font-bold text-gray-800 mb-2">QR Code Generator - Color Code</h2>
                <p class="text-gray-600">Generate dan kelola QR Code untuk semua code barang</p>
            </div>
            
            <!-- Filter and Search -->
            <div class="flex flex-col sm:flex-row gap-4">
                <!-- Buyer Filter -->
                <div class="relative">
                    <select id="buyerFilter" class="bg-white border border-gray-300 rounded-lg px-4 py-2 pr-8 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        <option value="">Semua Buyer</option>
                        <?php foreach ($buyers_surabaya as $buyer): ?>
                            <option value="<?php echo $buyer['id']; ?>"><?php echo htmlspecialchars($buyer['nama_buyer']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <!-- Search Box -->
                <div class="relative">
                    <input type="text" id="searchBox" placeholder="Cari code barang..." 
                           class="bg-white border border-gray-300 rounded-lg px-4 py-2 pl-10 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent w-64">
                    <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Color Codes Section -->
    <div id="colorCodesContainer" class="space-y-4">
        <!-- Color codes will be loaded here -->
    </div>
</main>

<!-- QR Code Preview Modal -->
<div id="qrModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-lg p-6 max-w-md w-full mx-4">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold">QR Code Preview</h3>
            <button onclick="closeQRModal()" class="text-gray-500 hover:text-gray-700">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        <div id="qrContent" class="text-center">
            <!-- QR code content will be inserted here -->
        </div>
        <div class="mt-4 flex justify-center">
            <button onclick="printQR()" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg">
                <i class="fas fa-print mr-2"></i>Print QR Code
            </button>
        </div>
    </div>
</div>

<!-- Print Template (Hidden) -->
<div id="printTemplate" class="hidden">
    <div class="print-content" style="width: 60mm; margin: 0 auto; text-align: center; font-family: Arial, sans-serif;">
        <div id="printQRCode" style="margin: 10px auto;"></div>
        <div style="margin: 10px 0; font-size: 12px; font-weight: bold;" id="printKodeBarang"></div>
        <div style="margin: 5px 0; font-size: 10px;" id="printBuyer"></div>
        <div style="margin: 5px 0; font-size: 10px;" id="printComponent"></div>
        <div style="margin: 5px 0; font-size: 10px;" id="printColorCode"></div>
        <div style="margin: 5px 0; font-size: 10px;" id="printLocation"></div>
        <div style="margin: 5px 0; font-size: 10px;" id="printRackNo"></div>
        <div style="margin: 5px 0; font-size: 9px;" id="printDates"></div>
        <div style="margin: 15px 0 5px 0; border-top: 1px solid #000; padding-top: 5px; font-size: 9px;">
            Tanda Tangan: ________________
        </div>
        <div style="font-size: 8px; margin-top: 10px;">
            Tanggal Cetak: <span id="printDate"></span>
        </div>
    </div>
</div>

<script>
let currentPrintData = null;

// Load color codes
function loadColorCodes(buyerId = '', searchTerm = '') {
    fetch('color_code_data.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'action=get_color_codes&buyer_id=' + encodeURIComponent(buyerId) + '&search=' + encodeURIComponent(searchTerm)
    })
    .then(response => response.text())
    .then(data => {
        document.getElementById('colorCodesContainer').innerHTML = data;
        
        // If search term provided, auto-expand and highlight
        if (searchTerm) {
            highlightSearchResult(searchTerm);
        }
    })
    .catch(error => console.error('Error:', error));
}

// Highlight search result
function highlightSearchResult(searchTerm) {
    const items = document.querySelectorAll(`[data-kode-barang*="${searchTerm}"]`);
    items.forEach(item => {
        // Expand parent color code
        const colorCard = item.closest('.color-card');
        if (colorCard) {
            const toggle = colorCard.querySelector('.toggle-items');
            const itemsContainer = colorCard.querySelector('.items-container');
            if (toggle && itemsContainer) {
                itemsContainer.classList.remove('hidden');
                toggle.querySelector('i').classList.remove('fa-chevron-down');
                toggle.querySelector('i').classList.add('fa-chevron-up');
            }
        }
        
        // Highlight item
        item.classList.add('bg-yellow-200', 'border-2', 'border-yellow-500');
        
        // Scroll to item
        setTimeout(() => {
            item.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }, 100);
    });
}

// Toggle color code items
function toggleItems(button, colorId) {
    const container = document.getElementById('items-' + colorId);
    const icon = button.querySelector('i');
    
    if (container.classList.contains('hidden')) {
        container.classList.remove('hidden');
        icon.classList.remove('fa-chevron-down');
        icon.classList.add('fa-chevron-up');
    } else {
        container.classList.add('hidden');
        icon.classList.remove('fa-chevron-up');
        icon.classList.add('fa-chevron-down');
    }
}

// Generate single QR code
function generateQR(itemId) {
    const button = document.querySelector(`button[onclick="generateQR(${itemId})"]`);
    const originalText = button.innerHTML;
    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating...';
    button.disabled = true;
    
    fetch('', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'action=generate_qr&item_id=' + itemId
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Reload the current view
            const buyerId = document.getElementById('buyerFilter').value;
            const searchTerm = document.getElementById('searchBox').value;
            loadColorCodes(buyerId, searchTerm);
            
            // Show success message
            showNotification('QR Code berhasil digenerate!', 'success');
        } else {
            showNotification('Gagal generate QR Code: ' + data.message, 'error');
            button.innerHTML = originalText;
            button.disabled = false;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('Terjadi kesalahan saat generate QR Code', 'error');
        button.innerHTML = originalText;
        button.disabled = false;
    });
}

// Generate all QR codes for a color
function generateAllQR(colorId) {
    const button = document.querySelector(`button[onclick="generateAllQR(${colorId})"]`);
    const originalText = button.innerHTML;
    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating...';
    button.disabled = true;
    
    fetch('', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'action=generate_all_qr&color_id=' + colorId
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Reload the current view
            const buyerId = document.getElementById('buyerFilter').value;
            const searchTerm = document.getElementById('searchBox').value;
            loadColorCodes(buyerId, searchTerm);
            
            // Show success message
            showNotification(`${data.generated_count} QR Code berhasil digenerate!`, 'success');
        } else {
            showNotification('Gagal generate QR Code', 'error');
            button.innerHTML = originalText;
            button.disabled = false;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('Terjadi kesalahan saat generate QR Code', 'error');
        button.innerHTML = originalText;
        button.disabled = false;
    });
}

// View QR code
function viewQR(qrCode, kodeBarang, buyer, component, colorCode, location, rackNo, dates) {
    currentPrintData = {
        qrCode: qrCode,
        kodeBarang: kodeBarang,
        buyer: buyer,
        component: component,
        colorCode: colorCode,
        location: location,
        rackNo: rackNo,
        dates: dates
    };
    
    document.getElementById('qrContent').innerHTML = `
        <img src="${qrCode}" alt="QR Code" class="mx-auto mb-4" style="width: 200px; height: 200px;">
        <p class="text-lg font-semibold">${kodeBarang}</p>
        <p class="text-sm text-gray-600">${buyer} - ${component}</p>
        <p class="text-sm text-gray-600">${colorCode}</p>
    `;
    
    document.getElementById('qrModal').classList.remove('hidden');
    document.getElementById('qrModal').classList.add('flex');
}

// Close QR modal
function closeQRModal() {
    document.getElementById('qrModal').classList.add('hidden');
    document.getElementById('qrModal').classList.remove('flex');
}

// Print QR code
function printQR() {
    if (!currentPrintData) return;
    
    // Fill print template
    document.getElementById('printQRCode').innerHTML = `<img src="${currentPrintData.qrCode}" style="width: 120px; height: 120px; margin: 0 auto;">`;
    document.getElementById('printKodeBarang').textContent = currentPrintData.kodeBarang;
    document.getElementById('printBuyer').textContent = `Buyer: ${currentPrintData.buyer}`;
    document.getElementById('printComponent').textContent = `Component: ${currentPrintData.component}`;
    document.getElementById('printColorCode').textContent = `Color Code: ${currentPrintData.colorCode}`;
    document.getElementById('printLocation').textContent = `Location: ${currentPrintData.location}`;
    document.getElementById('printRackNo').textContent = `Rack No: ${currentPrintData.rackNo}`;
    document.getElementById('printDates').textContent = currentPrintData.dates;
    document.getElementById('printDate').textContent = new Date().toLocaleDateString('id-ID');
    
    // Print
    const printContent = document.getElementById('printTemplate').innerHTML;
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
        <html>
        <head>
            <title>Print QR Code</title>
            <style>
                @media print {
                    body { margin: 0; }
                    .print-content { page-break-inside: avoid; }
                }
            </style>
        </head>
        <body>
            ${printContent}
            <script>
                window.onload = function() {
                    window.print();
                    window.close();
                }
            </script>
        </body>
        </html>
    `);
    printWindow.document.close();
}

// Show notification
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `fixed top-4 right-4 z-50 p-4 rounded-lg text-white ${
        type === 'success' ? 'bg-green-500' : 
        type === 'error' ? 'bg-red-500' : 'bg-blue-500'
    }`;
    notification.textContent = message;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.remove();
    }, 3000);
}

// Event listeners
document.addEventListener('DOMContentLoaded', function() {
    // Load initial data
    loadColorCodes();
    
    // Buyer filter
    document.getElementById('buyerFilter').addEventListener('change', function() {
        const buyerId = this.value;
        const searchTerm = document.getElementById('searchBox').value;
        loadColorCodes(buyerId, searchTerm);
    });
    
    // Search box
    let searchTimeout;
    document.getElementById('searchBox').addEventListener('input', function() {
        const searchTerm = this.value;
        const buyerId = document.getElementById('buyerFilter').value;
        
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            loadColorCodes(buyerId, searchTerm);
        }, 300);
    });
    
    // Close modal when clicking outside
    document.getElementById('qrModal').addEventListener('click', function(e) {
        if (e.target === this) {
            closeQRModal();
        }
    });
});
</script>

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