<?php
require_once 'config/connection.php';
require_once 'phpqrcode/qrlib.php';

// Handle bulk download request
if (isset($_POST['bulk_download'])) {
    try {
        // Create temporary directory for QR codes
        $tempDir = sys_get_temp_dir() . '/qr_codes_' . time();
        if (!mkdir($tempDir, 0755, true)) {
            throw new Exception("Failed to create temporary directory");
        }

        // Query to get all stock items with related information
        $sql = "SELECT 
                    csi.id,
                    csi.kode_barang,
                    csi.stock_number,
                    csi.status,
                    csi.lokasi,
                    csi.rack_no,
                    csi.tanggal_pembuatan,
                    csi.tanggal_kedaluwarsa,
                    csi.keterangan,
                    mcp.code_color,
                    mcp.deskripsi as color_description,
                    b.nama_buyer,
                    b.kode_buyer,
                    cc.component_name,
                    col.nama_collection
                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
                JOIN collections col ON mcp.collection_id = col.id
                ORDER BY csi.kode_barang ASC";
        
        $result = $conn->query($sql);
        
        if (!$result) {
            throw new Exception("Database query failed: " . $conn->error);
        }

        $counter = 1;
        while ($row = $result->fetch_assoc()) {
            // Create QR code content
            $qrContent = "Item Code: " . $row['kode_barang'] . "\n";
            $qrContent .= "Stock Number: " . $row['stock_number'] . "\n";
            $qrContent .= "Color: " . $row['kode_buyer'] . " " . $row['code_color'] . "\n";
            $qrContent .= "Component: " . $row['component_name'] . "\n";
            $qrContent .= "Status: " . $row['status'] . "\n";
            $qrContent .= "Location: " . $row['lokasi'] . "\n";
            $qrContent .= "Rack: " . $row['rack_no'] . "\n";
            $qrContent .= "Production Date: " . $row['tanggal_pembuatan'] . "\n";
            $qrContent .= "Expiry Date: " . $row['tanggal_kedaluwarsa'] . "\n";
            $qrContent .= "Description: " . $row['keterangan'];

            // Generate filename with counter for sorting
            $filename = sprintf("%04d_%s.png", $counter, $row['kode_barang']);
            $filepath = $tempDir . '/' . $filename;
            
            // Generate QR code
            QRcode::png($qrContent, $filepath, QR_ECLEVEL_L, 8);
            
            $counter++;
        }

        // Create ZIP file
        $zipFile = sys_get_temp_dir() . '/all_qr_codes_' . date('Y-m-d_H-i-s') . '.zip';
        $zip = new ZipArchive();
        
        if ($zip->open($zipFile, ZipArchive::CREATE) !== TRUE) {
            throw new Exception("Cannot create ZIP file");
        }

        // Add all QR code files to ZIP
        $files = scandir($tempDir);
        foreach ($files as $file) {
            if ($file != "." && $file != "..") {
                $zip->addFile($tempDir . '/' . $file, $file);
            }
        }
        
        $zip->close();

        // Download the ZIP file
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="QR_Codes_' . date('Y-m-d_H-i-s') . '.zip"');
        header('Content-Length: ' . filesize($zipFile));
        
        readfile($zipFile);
        
        // Clean up temporary files
        $files = scandir($tempDir);
        foreach ($files as $file) {
            if ($file != "." && $file != "..") {
                unlink($tempDir . '/' . $file);
            }
        }
        rmdir($tempDir);
        unlink($zipFile);
        
        exit();
        
    } catch (Exception $e) {
        $error_message = "Error: " . $e->getMessage();
    }
}

// Query to display all stock items
$display_sql = "SELECT 
                    csi.id,
                    csi.kode_barang,
                    csi.stock_number,
                    csi.status,
                    csi.lokasi,
                    csi.rack_no,
                    csi.tanggal_pembuatan,
                    csi.tanggal_kedaluwarsa,
                    csi.keterangan,
                    mcp.code_color,
                    mcp.deskripsi as color_description,
                    b.nama_buyer,
                    b.kode_buyer,
                    cc.component_name,
                    col.nama_collection
                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
                JOIN collections col ON mcp.collection_id = col.id
                ORDER BY csi.kode_barang ASC";

$display_result = $conn->query($display_sql);
$total_items = $display_result->num_rows;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bulk QR Code Management - Color Access System</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    
    <style>
        .header-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem 0;
            margin-bottom: 2rem;
        }
        
        .stats-card {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 15px;
            padding: 1.5rem;
            color: white;
        }
        
        .stats-number {
            font-size: 2.5rem;
            font-weight: bold;
            margin-bottom: 0.5rem;
        }
        
        .btn-download {
            background: linear-gradient(45deg, #28a745, #20c997);
            border: none;
            border-radius: 25px;
            padding: 12px 30px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .btn-download:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(40, 167, 69, 0.3);
        }
        
        .table-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        
        .table th {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            font-weight: 600;
            border: none;
            padding: 1rem 0.75rem;
        }
        
        .table td {
            padding: 0.75rem;
            vertical-align: middle;
            border-bottom: 1px solid #e9ecef;
        }
        
        .status-badge {
            padding: 0.4rem 0.8rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .status-tersedia { background-color: #d4edda; color: #155724; }
        .status-dipinjam { background-color: #fff3cd; color: #856404; }
        .status-rusak { background-color: #f8d7da; color: #721c24; }
        .status-expired { background-color: #f5c6cb; color: #721c24; }
        .status-renew { background-color: #d1ecf1; color: #0c5460; }
        .status-hilang { background-color: #e2e3e5; color: #383d41; }
        
        .alert-custom {
            border-radius: 15px;
            border: none;
            margin-bottom: 2rem;
        }
        
        .loading-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 9999;
            justify-content: center;
            align-items: center;
        }
        
        .loading-content {
            background: white;
            padding: 2rem;
            border-radius: 15px;
            text-align: center;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
        }
        
        .spinner {
            width: 3rem;
            height: 3rem;
            margin-bottom: 1rem;
        }
        
        @media (max-width: 768px) {
            .table-responsive {
                font-size: 0.875rem;
            }
        }
    </style>
</head>
<body>
    <!-- Loading Overlay -->
    <div class="loading-overlay" id="loadingOverlay">
        <div class="loading-content">
            <div class="spinner-border text-primary spinner" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <h5>Generating QR Codes...</h5>
            <p class="text-muted">Please wait while we prepare your download</p>
        </div>
    </div>

    <!-- Header Section -->
    <div class="header-section">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h1 class="mb-3">
                        <i class="fas fa-qrcode me-3"></i>
                        Bulk QR Code Management
                    </h1>
                    <p class="lead mb-0">Generate and download all QR codes for color stock items</p>
                </div>
                <div class="col-md-4 text-md-end">
                    <div class="stats-card">
                        <div class="stats-number"><?php echo number_format($total_items); ?></div>
                        <div>Total Items</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <?php if (isset($error_message)): ?>
            <div class="alert alert-danger alert-custom" role="alert">
                <i class="fas fa-exclamation-triangle me-2"></i>
                <?php echo htmlspecialchars($error_message); ?>
            </div>
        <?php endif; ?>

        <!-- Action Section -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center">
                    <h3 class="mb-0">
                        <i class="fas fa-list me-2"></i>
                        All Stock Items
                    </h3>
                    <form method="post" class="d-inline" onsubmit="showLoading()">
                        <button type="submit" name="bulk_download" class="btn btn-success btn-download">
                            <i class="fas fa-download me-2"></i>
                            Print All QR Codes
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Data Table -->
        <div class="table-container">
            <div class="table-responsive">
                <table class="table table-hover mb-0" id="stockTable">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Code Barang</th>
                            <th>Stock #</th>
                            <th>Buyer</th>
                            <th>Color</th>
                            <th>Component</th>
                            <th>Status</th>
                            <th>Location</th>
                            <th>Rack</th>
                            <th>Production Date</th>
                            <th>Expiry Date</th>
                            <th>Description</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $no = 1;
                        $display_result->data_seek(0); // Reset result pointer
                        while ($row = $display_result->fetch_assoc()): 
                        ?>
                            <tr>
                                <td><?php echo $no++; ?></td>
                                <td>
                                    <strong><?php echo htmlspecialchars($row['kode_barang']); ?></strong>
                                </td>
                                <td><?php echo htmlspecialchars($row['stock_number']); ?></td>
                                <td>
                                    <span class="badge bg-primary">
                                        <?php echo htmlspecialchars($row['kode_buyer']); ?>
                                    </span>
                                    <small class="d-block text-muted">
                                        <?php echo htmlspecialchars($row['nama_buyer']); ?>
                                    </small>
                                </td>
                                <td>
                                    <strong><?php echo htmlspecialchars($row['code_color']); ?></strong>
                                    <small class="d-block text-muted">
                                        <?php echo htmlspecialchars($row['color_description']); ?>
                                    </small>
                                </td>
                                <td><?php echo htmlspecialchars($row['component_name']); ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo strtolower($row['status']); ?>">
                                        <?php echo htmlspecialchars($row['status']); ?>
                                    </span>
                                </td>
                                <td><?php echo htmlspecialchars($row['lokasi']); ?></td>
                                <td>
                                    <span class="badge bg-secondary">
                                        <?php echo htmlspecialchars($row['rack_no']); ?>
                                    </span>
                                </td>
                                <td><?php echo htmlspecialchars($row['tanggal_pembuatan']); ?></td>
                                <td><?php echo htmlspecialchars($row['tanggal_kedaluwarsa']); ?></td>
                                <td>
                                    <small><?php echo htmlspecialchars($row['keterangan']); ?></small>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>

    <script>
        $(document).ready(function() {
            $('#stockTable').DataTable({
                "pageLength": 25,
                "order": [[ 1, "asc" ]], // Order by Code Barang
                "language": {
                    "search": "Search items:",
                    "lengthMenu": "Show _MENU_ items per page",
                    "info": "Showing _START_ to _END_ of _TOTAL_ items",
                    "paginate": {
                        "first": "First",
                        "last": "Last",
                        "next": "Next",
                        "previous": "Previous"
                    }
                },
                "responsive": true,
                "dom": '<"row"<"col-sm-6"l><"col-sm-6"f>>rtip'
            });
        });

        function showLoading() {
            document.getElementById('loadingOverlay').style.display = 'flex';
        }
    </script>
</body>
</html>

<?php
$conn->close();
?>