<?php
// qrcode_generator_it.php
// Start session
session_start();

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

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

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

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

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

// Function to generate simple QR code for code barang only
function generateSimpleQRCode($codeBarang) {
    require_once('../phpqrcode/qrlib.php');
    
    // Generate a unique filename
    $tempDir = "../qrcodes/";
    if (!file_exists($tempDir)) {
        mkdir($tempDir, 0777, true);
    }
    
    $filename = "qr_" . $codeBarang . "_" . time() . ".png";
    $filePath = $tempDir . $filename;
    
    // Generate QR code with just the code barang
    QRcode::png($codeBarang, $filePath, QR_ECLEVEL_L, 8);
    
    // Return the image as base64
    $qrData = file_get_contents($filePath);
    $base64 = 'data:image/png;base64,' . base64_encode($qrData);
    
    // Remove the temporary file
    unlink($filePath);
    
    return $base64;
}

// Process QR code generation for code barang
if (isset($_POST['generate_qr_cp'])) {
    $stock_id = $_POST['stock_id'];
    $code_barang = $_POST['code_barang'];
    
    // Generate simple QR code
    $qr_code_cp = generateSimpleQRCode($code_barang);
    
    // Update the item with the new QR code
    $stmt = $conn->prepare("UPDATE color_stock_items SET qrcode_cp = ? WHERE id = ?");
    $stmt->bind_param("si", $qr_code_cp, $stock_id);
    $stmt->execute();
    $stmt->close();
    
    // Log activity
    log_activity($conn, $it_id, 'it', 'QR Code CP Generation', "IT user generated simple QR code for code barang: $code_barang (ID: $stock_id)");
    
    // Redirect to prevent resubmission
    header("Location: qrcode_generator_it.php?success=1&code=" . urlencode($code_barang));
    exit();
}

// Get search parameter
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$buyer_filter = isset($_GET['buyer']) ? trim($_GET['buyer']) : '';

// 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">
    <!-- Notifications -->
    <?php if (isset($_GET['success']) && $_GET['success'] == 1): ?>
    <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 mb-6" role="alert">
        <p class="font-bold">Sukses</p>
        <p>QR Code untuk <?php echo htmlspecialchars($_GET['code'] ?? 'code barang'); ?> telah berhasil dibuat!</p>
    </div>
    <?php endif; ?>

    <!-- QR Code Generator Card -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-2xl font-bold text-gray-800">QR Code Generator - Code Barang</h2>
            
            <!-- Search and Filter Section -->
            <div class="flex space-x-4">
                <form method="GET" class="flex space-x-4">
                    <div>
                        <label for="search" class="block text-sm font-medium text-gray-700 mb-1">Cari Code Barang:</label>
                        <input type="text" id="search" name="search" value="<?php echo htmlspecialchars($search); ?>"
                               class="border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm" 
                               placeholder="CP.0001">
                    </div>
                    <div>
                        <label for="buyer" class="block text-sm font-medium text-gray-700 mb-1">Filter Buyer:</label>
                        <select id="buyer" name="buyer" class="border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm">
                            <option value="">Semua Buyer</option>
                            <?php
                            $buyer_query = "SELECT id, nama_buyer FROM buyers ORDER BY nama_buyer";
                            $buyer_result = $conn->query($buyer_query);
                            while ($buyer = $buyer_result->fetch_assoc()) {
                                $selected = ($buyer_filter == $buyer['nama_buyer']) ? 'selected' : '';
                                echo '<option value="' . htmlspecialchars($buyer['nama_buyer']) . '" ' . $selected . '>' . htmlspecialchars($buyer['nama_buyer']) . '</option>';
                            }
                            ?>
                        </select>
                    </div>
                    <div class="flex items-end">
                        <button type="submit" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md">
                            <i class="fas fa-search mr-2"></i>Filter
                        </button>
                        <?php if ($search || $buyer_filter): ?>
                        <a href="qrcode_generator_it.php" class="ml-2 bg-gray-500 hover:bg-gray-600 text-white px-4 py-2 rounded-md">
                            <i class="fas fa-times mr-2"></i>Reset
                        </a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Code Barang List -->
        <div class="overflow-x-auto">
            <table class="min-w-full bg-white border border-gray-200">
                <thead>
                    <tr class="bg-gray-50">
                        <th class="px-4 py-3 border-b text-left text-sm font-medium text-gray-700 uppercase tracking-wider">No</th>
                        <th class="px-4 py-3 border-b text-left text-sm font-medium text-gray-700 uppercase tracking-wider">Code Barang</th>
                        <th class="px-4 py-3 border-b text-left text-sm font-medium text-gray-700 uppercase tracking-wider">Buyer</th>
                        <th class="px-4 py-3 border-b text-left text-sm font-medium text-gray-700 uppercase tracking-wider">Color Code</th>
                        <th class="px-4 py-3 border-b text-left text-sm font-medium text-gray-700 uppercase tracking-wider">Component</th>
                        <th class="px-4 py-3 border-b text-left text-sm font-medium text-gray-700 uppercase tracking-wider">Status</th>
                        <th class="px-4 py-3 border-b text-left text-sm font-medium text-gray-700 uppercase tracking-wider">QR Code CP</th>
                        <th class="px-4 py-3 border-b text-left text-sm font-medium text-gray-700 uppercase tracking-wider">Aksi</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200">
                    <?php
                    // Build query with search and filter
                    $query = "SELECT csi.id, csi.kode_barang, csi.status, csi.qrcode_cp,
                                     mcp.code_color, b.nama_buyer, cc.component_name
                              FROM color_stock_items csi
                              JOIN master_color_panel mcp ON csi.color_id = mcp.id
                              JOIN buyers b ON mcp.buyer_id = b.id
                              JOIN color_components cc ON csi.component_id = cc.id
                              WHERE 1=1";
                    
                    $params = [];
                    $types = "";
                    
                    if ($search) {
                        $query .= " AND csi.kode_barang LIKE ?";
                        $params[] = "%$search%";
                        $types .= "s";
                    }
                    
                    if ($buyer_filter) {
                        $query .= " AND b.nama_buyer = ?";
                        $params[] = $buyer_filter;
                        $types .= "s";
                    }
                    
                    $query .= " ORDER BY b.nama_buyer, mcp.code_color, cc.component_name, csi.stock_number";
                    
                    $stmt = $conn->prepare($query);
                    if ($params) {
                        $stmt->bind_param($types, ...$params);
                    }
                    $stmt->execute();
                    $result = $stmt->get_result();
                    
                    $i = 1;
                    while ($row = $result->fetch_assoc()) {
                        // Status styling
                        $statusClass = '';
                        switch ($row['status']) {
                            case 'Tersedia':
                                $statusClass = 'bg-green-100 text-green-800';
                                break;
                            case 'Dipinjam':
                                $statusClass = 'bg-blue-100 text-blue-800';
                                break;
                            case 'Rusak':
                                $statusClass = 'bg-red-100 text-red-800';
                                break;
                            case 'Expired':
                                $statusClass = 'bg-gray-100 text-gray-800';
                                break;
                            case 'Renew':
                                $statusClass = 'bg-yellow-100 text-yellow-800';
                                break;
                        }
                    ?>
                    <tr class="hover:bg-gray-50">
                        <td class="px-4 py-3 whitespace-nowrap text-sm"><?php echo $i++; ?></td>
                        <td class="px-4 py-3 whitespace-nowrap">
                            <span class="text-sm font-medium text-gray-900"><?php echo htmlspecialchars($row['kode_barang']); ?></span>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                            <?php echo htmlspecialchars($row['nama_buyer']); ?>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                            <?php echo htmlspecialchars($row['code_color']); ?>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                            <?php echo htmlspecialchars($row['component_name']); ?>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap">
                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full <?php echo $statusClass; ?>">
                                <?php echo $row['status']; ?>
                            </span>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                            <?php if ($row['qrcode_cp']): ?>
                                <button class="view-qr-cp bg-blue-500 hover:bg-blue-600 text-white px-2 py-1 rounded text-xs"
                                        data-qr="<?php echo htmlspecialchars($row['qrcode_cp']); ?>"
                                        data-code="<?php echo htmlspecialchars($row['kode_barang']); ?>">
                                    <i class="fas fa-qrcode mr-1"></i>Lihat QR
                                </button>
                            <?php else: ?>
                                <span class="text-gray-400 text-xs">Belum ada</span>
                            <?php endif; ?>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap text-sm font-medium">
                            <div class="flex space-x-2">
                                <form method="post" class="inline">
                                    <input type="hidden" name="stock_id" value="<?php echo $row['id']; ?>">
                                    <input type="hidden" name="code_barang" value="<?php echo htmlspecialchars($row['kode_barang']); ?>">
                                    <button type="submit" name="generate_qr_cp" 
                                            class="bg-green-500 hover:bg-green-600 text-white px-2 py-1 rounded text-xs"
                                            onclick="return confirm('Generate QR Code untuk <?php echo htmlspecialchars($row['kode_barang']); ?>?')">
                                        <i class="fas fa-plus mr-1"></i><?php echo $row['qrcode_cp'] ? 'Re-generate' : 'Generate'; ?>
                                    </button>
                                </form>
                                
                                <?php if ($row['qrcode_cp']): ?>
                                <button class="print-qr-cp bg-purple-500 hover:bg-purple-600 text-white px-2 py-1 rounded text-xs"
                                        data-qr="<?php echo htmlspecialchars($row['qrcode_cp']); ?>"
                                        data-code="<?php echo htmlspecialchars($row['kode_barang']); ?>">
                                    <i class="fas fa-print mr-1"></i>Print
                                </button>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php } ?>
                </tbody>
            </table>
            
            <?php if ($result->num_rows == 0): ?>
            <div class="text-center py-8">
                <p class="text-gray-500">
                    <?php if ($search || $buyer_filter): ?>
                        Tidak ada data yang sesuai dengan filter yang dipilih.
                    <?php else: ?>
                        Tidak ada data code barang ditemukan.
                    <?php endif; ?>
                </p>
            </div>
            <?php endif; ?>
        </div>
    </div>
</main>

<!-- QR Code Viewer Modal -->
<div id="qrCpModal" class="fixed z-10 inset-0 overflow-y-auto hidden">
    <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        
        <!-- Modal Content -->
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <div class="sm:flex sm:items-start">
                    <div class="mt-3 text-center sm:mt-0 sm:text-left w-full">
                        <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">QR Code - Code Barang</h3>
                        
                        <div class="flex flex-col items-center">
                            <div class="w-64 h-64 border border-gray-300 flex items-center justify-center mb-4" id="qrCpCodeImage">
                                <!-- QR Code will be inserted here -->
                            </div>
                            <div class="text-sm text-gray-600 mb-4" id="qrCpCodeInfo">
                                <!-- QR Code info will be inserted here -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                <button type="button" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm" id="closeQrCpModal">
                    Tutup
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Print QR Code Modal -->
<div id="printQrCpModal" class="fixed z-10 inset-0 overflow-y-auto hidden">
    <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        
        <!-- Modal Content -->
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-md sm:w-full">
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <div class="sm:flex sm:items-start">
                    <div class="mt-3 text-center sm:mt-0 sm:text-left w-full" id="printQrCpContent">
                        <div class="flex justify-between items-center mb-6 print-header">
                            <h3 class="text-lg leading-6 font-medium text-gray-900">Print QR Code</h3>
                            <div>
                                <button id="printQrCpBtn" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-md flex items-center">
                                    <i class="fas fa-print mr-2"></i> Cetak
                                </button>
                            </div>
                        </div>
                        
                        <div id="qrCpPrintContent" class="flex flex-col items-center">
                            <!-- Content will be populated via JavaScript -->
                        </div>
                    </div>
                </div>
            </div>
            <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                <button type="button" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm" id="closePrintQrCpModal">
                    Tutup
                </button>
            </div>
        </div>
    </div>
</div>

<style>
@media print {
    .print-header {
        display: none !important;
    }
    
    @page {
        margin: 0.5cm;
        size: A4;
    }
    
    body {
        print-color-adjust: exact;
        -webkit-print-color-adjust: exact;
    }
    
    .no-print {
        display: none !important;
    }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const qrCpModal = document.getElementById('qrCpModal');
    const closeQrCpModalBtn = document.getElementById('closeQrCpModal');
    const qrCpCodeImage = document.getElementById('qrCpCodeImage');
    const qrCpCodeInfo = document.getElementById('qrCpCodeInfo');
    
    const printQrCpModal = document.getElementById('printQrCpModal');
    const closePrintQrCpModalBtn = document.getElementById('closePrintQrCpModal');
    const printQrCpBtn = document.getElementById('printQrCpBtn');
    const qrCpPrintContent = document.getElementById('qrCpPrintContent');
    
    let currentQrCode = '';
    let currentCodeBarang = '';

    // View QR Code functionality
    document.querySelectorAll('.view-qr-cp').forEach(button => {
        button.addEventListener('click', function() {
            const qrCode = this.getAttribute('data-qr');
            const codeBarang = this.getAttribute('data-code');
            
            qrCpCodeImage.innerHTML = `<img src="${qrCode}" alt="QR Code" class="max-w-full max-h-full">`;
            qrCpCodeInfo.innerHTML = `<strong>Code Barang:</strong> ${codeBarang}`;
            
            qrCpModal.classList.remove('hidden');
        });
    });

    // Print QR Code functionality
    document.querySelectorAll('.print-qr-cp').forEach(button => {
        button.addEventListener('click', function() {
            const qrCode = this.getAttribute('data-qr');
            const codeBarang = this.getAttribute('data-code');
            
            currentQrCode = qrCode;
            currentCodeBarang = codeBarang;
            
            qrCpPrintContent.innerHTML = `
                <div class="flex flex-col items-center mb-6 border p-6 rounded-lg w-full max-w-xs mx-auto">
                    <div class="mb-4 text-center">
                        <h4 class="text-lg font-semibold mb-2">QR Code</h4>
                        <p class="text-md font-medium">${codeBarang}</p>
                    </div>
                    
                    <div class="flex justify-center mb-4">
                        <img src="${qrCode}" alt="QR Code" class="w-32 h-32">
                    </div>
                    
                    <div class="text-center">
                        <p class="text-sm text-gray-600">Scan untuk melihat:</p>
                        <p class="text-sm font-medium">${codeBarang}</p>
                    </div>
                </div>
            `;
            
            printQrCpModal.classList.remove('hidden');
        });
    });

    // Print functionality
    printQrCpBtn.addEventListener('click', function() {
        const fileName = currentCodeBarang || 'QR_Code';
        
        const printContents = document.getElementById('printQrCpContent').innerHTML;
        const originalContents = document.body.innerHTML;
        const originalTitle = document.title;
        
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = printContents;
        const printHeaders = tempDiv.querySelectorAll('.print-header');
        printHeaders.forEach(header => header.remove());
        
        document.title = fileName;
        
        document.body.innerHTML = `
            <div style="padding: 20px; max-width: 300px; margin: 0 auto;">
                ${tempDiv.innerHTML}
            </div>
        `;
        
        const printHandler = function() {
            setTimeout(() => {
                document.body.innerHTML = originalContents;
                document.title = originalTitle;
                location.reload();
            }, 1000);
        };
        
        window.addEventListener('afterprint', printHandler, { once: true });
        
        setTimeout(() => {
            window.print();
        }, 100);
    });

    // Close modal functionality
    closeQrCpModalBtn.addEventListener('click', function() {
        qrCpModal.classList.add('hidden');
    });

    closePrintQrCpModalBtn.addEventListener('click', function() {
        printQrCpModal.classList.add('hidden');
        currentQrCode = '';
        currentCodeBarang = '';
    });

    // Close modal when clicking outside
    qrCpModal.addEventListener('click', function(e) {
        if (e.target === this) {
            this.classList.add('hidden');
        }
    });

    printQrCpModal.addEventListener('click', function(e) {
        if (e.target === this) {
            this.classList.add('hidden');
            currentQrCode = '';
            currentCodeBarang = '';
        }
    });
});
</script>

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