<?php
require_once 'config/connection.php';
require_once 'phpqrcode/qrlib.php';
// For PDF generation with FPDF (without Composer)
require_once 'fpdf/fpdf.php'; // Assuming FPDF is in the fpdf directory

// Create custom PDF class for exact layout matching
class QRCodePDF extends FPDF {
    function CenteredText($y, $txt, $fontSize = 12, $fontStyle = '') {
        $this->SetFont('Arial', $fontStyle, $fontSize);
        $this->SetY($y);
        $this->Cell(0, 10, $txt, 0, 1, 'C');
    }
}

// Handle bulk download request
if (isset($_POST['bulk_download'])) {
    try {
        // Set higher memory limit and execution time
        ini_set('memory_limit', '256M');
        set_time_limit(300);
        
        // 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,
                    mcp.lemari,
                    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 - only the item code
            $qrContent = $row['kode_barang'];
            
            // Format dates for display
            $date_range = '';
            if ($row['tanggal_pembuatan'] && $row['tanggal_kedaluwarsa']) {
                $date_range = date('Y-m-d', strtotime($row['tanggal_pembuatan'])) . ' - ' . date('Y-m-d', strtotime($row['tanggal_kedaluwarsa']));
            }
            
            // Generate QR code image
            $qrImageFile = $row['kode_barang'] . '_qr.png';
            $qrImagePath = $tempDir . '/' . $qrImageFile;
            QRcode::png($qrContent, $qrImagePath, QR_ECLEVEL_L, 10); // Increased size to 10
            
            // Generate PDF file
            $pdfFilePath = $tempDir . '/' . sprintf("%04d_%s.pdf", $counter, $row['kode_barang']);
            
            // Create PDF using custom FPDF class
            $pdf = new QRCodePDF('P', 'mm', 'A4');
            $pdf->SetAutoPageBreak(false);
            $pdf->AddPage();
            
            // Main title at the top (Buyer - Color Code)
            $pdf->CenteredText(20, $row['nama_buyer'] . ' - ' . $row['code_color'], 20, 'B');
            
            // Component and Item Code subtitle
            $pdf->CenteredText(32, $row['component_name'] . ' (' . $row['kode_barang'] . ')', 14);
            
            // QR Code (centered)
            $pdf->Image($qrImagePath, 74, 45, 60, 60);
            
            // *** DETAILS SECTION - IMPROVED SPACING ***
            
            // Left column positions
            $leftLabelX = 30;  // Left column label position
            $rightLabelX = 120; // Right column label position
            
            // Row 1 - Buyer and Lokasi - first row after QR code
            $row1Y = 115; // Starting position for first row
            
            // Buyer label
            $pdf->SetFont('Arial', 'B', 12);
            $pdf->SetXY($leftLabelX, $row1Y);
            $pdf->Cell(30, 10, 'Buyer:');
            
            // Buyer value
            $pdf->SetFont('Arial', '', 12);
            $pdf->SetXY($leftLabelX + 40, $row1Y);
            $pdf->Cell(50, 10, $row['nama_buyer']);
            
            // Lokasi label
            $pdf->SetFont('Arial', 'B', 12);
            $pdf->SetXY($rightLabelX, $row1Y);
            $pdf->Cell(30, 10, 'Lokasi:');
            
            // Lokasi value
            $pdf->SetFont('Arial', '', 12);
            $pdf->SetXY($rightLabelX + 40, $row1Y);
            $pdf->Cell(50, 10, $row['lokasi']);
            
            // Row 2 - Color Code and Rack No - REDUCED spacing from row 1
            $row2Y = $row1Y + 15; // Reduced from 25 to 15mm spacing
            
            // Color Code label
            $pdf->SetFont('Arial', 'B', 12);
            $pdf->SetXY($leftLabelX, $row2Y);
            $pdf->Cell(30, 10, 'Color Code:');
            
            // Color Code value
            $pdf->SetFont('Arial', '', 12);
            $pdf->SetXY($leftLabelX + 40, $row2Y);
            $pdf->Cell(50, 10, $row['code_color']);
            
            // Rack No label
            $pdf->SetFont('Arial', 'B', 12);
            $pdf->SetXY($rightLabelX, $row2Y);
            $pdf->Cell(30, 10, 'Rack No:');
            
            // Rack No value
            $pdf->SetFont('Arial', '', 12);
            $pdf->SetXY($rightLabelX + 40, $row2Y);
            $pdf->Cell(50, 10, $row['rack_no']);
            
            // Row 3 - Component and Status - REDUCED spacing from row 2
            $row3Y = $row2Y + 15; // Reduced from 25 to 15mm spacing
            
            // Component label
            $pdf->SetFont('Arial', 'B', 12);
            $pdf->SetXY($leftLabelX, $row3Y);
            $pdf->Cell(30, 10, 'Component:');
            
            // Component value
            $pdf->SetFont('Arial', '', 12);
            $pdf->SetXY($leftLabelX + 40, $row3Y);
            $pdf->Cell(50, 10, $row['component_name']);
            
            // Status label
            $pdf->SetFont('Arial', 'B', 12);
            $pdf->SetXY($rightLabelX, $row3Y);
            $pdf->Cell(30, 10, 'Status:');
            
            // Status value
            $pdf->SetFont('Arial', '', 12);
            $pdf->SetXY($rightLabelX + 40, $row3Y);
            $pdf->Cell(50, 10, $row['status']);
            
            // Row 4 - Code Barang and Tanggal - REDUCED spacing from row 3
            $row4Y = $row3Y + 15; // Reduced from 25 to 15mm spacing
            
            // Code Barang label
            $pdf->SetFont('Arial', 'B', 12);
            $pdf->SetXY($leftLabelX, $row4Y);
            $pdf->Cell(30, 10, 'Code Barang:');
            
            // Code Barang value
            $pdf->SetFont('Arial', '', 12);
            $pdf->SetXY($leftLabelX + 40, $row4Y);
            $pdf->Cell(50, 10, $row['kode_barang']);
            
            // Tanggal label
            $pdf->SetFont('Arial', 'B', 12);
            $pdf->SetXY($rightLabelX, $row4Y);
            $pdf->Cell(30, 10, 'Tanggal:');
            
            // Tanggal value
            $pdf->SetFont('Arial', '', 12);
            $pdf->SetXY($rightLabelX + 40, $row4Y);
            $pdf->Cell(70, 10, $date_range);
            
            // Signatures section - First row - positioned after the details section
            $sigRow1Y = $row4Y + 35; // Appropriate spacing after details
            $signatureWidth = 50;
            
            // Calculate positions to center the signature blocks
            $pageWidth = 210; // A4 width in mm
            $totalWidth = 3 * $signatureWidth; // 3 signatures side by side
            $spacing = 20; // Space between signatures
            $totalWidthWithSpacing = $totalWidth + (2 * $spacing); // Total width including spacing
            $leftMargin = ($pageWidth - $totalWidthWithSpacing) / 2; // Left margin to center everything
            
            $sig1X = $leftMargin;
            $sig2X = $leftMargin + $signatureWidth + $spacing;
            $sig3X = $leftMargin + (2 * $signatureWidth) + (2 * $spacing);
            
            // First signature - K A Unit
            $pdf->SetFont('Arial', 'B', 12);
            $pdf->SetXY($sig1X, $sigRow1Y);
            $pdf->Cell($signatureWidth, 10, 'K A Unit', 0, 0, 'C');
            
            // Line
            $pdf->Line($sig1X, $sigRow1Y + 20, $sig1X + $signatureWidth, $sigRow1Y + 20);
            
            // Name
            $pdf->SetFont('Arial', '', 12);
            $pdf->SetXY($sig1X, $sigRow1Y + 25);
            $pdf->Cell($signatureWidth, 10, 'Y Andi S', 0, 0, 'C');
            
            // Second signature - Color Room
            $pdf->SetFont('Arial', 'B', 12);
            $pdf->SetXY($sig2X, $sigRow1Y);
            $pdf->Cell($signatureWidth, 10, 'Color Room', 0, 0, 'C');
            
            // Line
            $pdf->Line($sig2X, $sigRow1Y + 20, $sig2X + $signatureWidth, $sigRow1Y + 20);
            
            // Name
            $pdf->SetFont('Arial', '', 12);
            $pdf->SetXY($sig2X, $sigRow1Y + 25);
            $pdf->Cell($signatureWidth, 10, 'Alifi A.U', 0, 0, 'C');
            
            // Third signature - Akzonobel
            $pdf->SetFont('Arial', 'B', 12);
            $pdf->SetXY($sig3X, $sigRow1Y);
            $pdf->Cell($signatureWidth, 10, 'Akzonobel', 0, 0, 'C');
            
            // Line
            $pdf->Line($sig3X, $sigRow1Y + 20, $sig3X + $signatureWidth, $sigRow1Y + 20);
            
            // Name
            $pdf->SetFont('Arial', '', 12);
            $pdf->SetXY($sig3X, $sigRow1Y + 25);
            $pdf->Cell($signatureWidth, 10, 'Asmari', 0, 0, 'C');
            
            // Signatures section - Second row
            $sigRow2Y = $sigRow1Y + 40; // Appropriate spacing from first row
            
            // Fourth signature - Approved by
            $pdf->SetFont('Arial', 'B', 12);
            $pdf->SetXY($sig1X, $sigRow2Y);
            $pdf->Cell($signatureWidth, 10, 'Approved by', 0, 0, 'C');
            
            // Line
            $pdf->Line($sig1X, $sigRow2Y + 20, $sig1X + $signatureWidth, $sigRow2Y + 20);
            
            // Name
            $pdf->SetFont('Arial', '', 12);
            $pdf->SetXY($sig1X, $sigRow2Y + 25);
            $pdf->Cell($signatureWidth, 10, 'Eris', 0, 0, 'C');
            
            // Fifth signature - Approved by QC
            $pdf->SetFont('Arial', 'B', 12);
            $pdf->SetXY($sig2X, $sigRow2Y);
            $pdf->Cell($signatureWidth, 10, 'Approved by QC', 0, 0, 'C');
            
            // Line
            $pdf->Line($sig2X, $sigRow2Y + 20, $sig2X + $signatureWidth, $sigRow2Y + 20);
            
            // Name
            $pdf->SetFont('Arial', '', 12);
            $pdf->SetXY($sig2X, $sigRow2Y + 25);
            $pdf->Cell($signatureWidth, 10, 'Suhari yanto', 0, 0, 'C');
            
            // Sixth signature - Approved by
            $pdf->SetFont('Arial', 'B', 12);
            $pdf->SetXY($sig3X, $sigRow2Y);
            $pdf->Cell($signatureWidth, 10, 'Approved by', 0, 0, 'C');
            
            // Line
            $pdf->Line($sig3X, $sigRow2Y + 20, $sig3X + $signatureWidth, $sigRow2Y + 20);
            
            // Name
            $pdf->SetFont('Arial', '', 12);
            $pdf->SetXY($sig3X, $sigRow2Y + 25);
            $pdf->Cell($signatureWidth, 10, 'QC Buyer', 0, 0, 'C');
            
            // Save PDF
            $pdf->Output($pdfFilePath, 'F');
            
            $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 PDF files to ZIP (skip the QR image files)
        $files = scandir($tempDir);
        foreach ($files as $file) {
            if ($file != "." && $file != ".." && pathinfo($file, PATHINFO_EXTENSION) == 'pdf') {
                $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();
?>