<?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();
}

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

// Handle print request - HARUS DI ATAS SEBELUM OUTPUT APAPUN
if (isset($_POST['print_action'])) {
    // Clear any previous output
    if (ob_get_length()) ob_end_clean();
    
    $selected_buyer = isset($_POST['buyer_id']) ? (int)$_POST['buyer_id'] : 0;
    
    // Get buyer name for filename
    $buyer_name_for_file = 'All_Buyers';
    if ($selected_buyer > 0) {
        $buyer_stmt = $conn->prepare("SELECT kode_buyer FROM buyers WHERE id = ?");
        $buyer_stmt->bind_param("i", $selected_buyer);
        $buyer_stmt->execute();
        $buyer_result = $buyer_stmt->get_result();
        if ($buyer_row = $buyer_result->fetch_assoc()) {
            // Clean buyer name for filename (remove special characters)
            $buyer_name_for_file = preg_replace('/[^A-Za-z0-9_-]/', '_', $buyer_row['kode_buyer']);
        }
        $buyer_stmt->close();
    }
    
    // Build query based on current database structure
    $query = "
        SELECT 
            b.nama_buyer,
            b.kode_buyer,
            mc.code_color as master_code_color,
            mc.name_color as master_name_color,
            mcp.code_color,
            mcp.deskripsi,
            mcp.lemari,
            mcp.lemari_number,
            c.nama_collection,
            cc.component_name,
            csi.kode_barang,
            csi.stock_number,
            csi.status,
            csi.lokasi,
            csi.rack_no,
            csi.tanggal_pembuatan,
            csi.tanggal_kedaluwarsa,
            csi.keterangan,
            csi.item_type
        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 collections c ON mcp.collection_id = c.id
        JOIN color_components cc ON csi.component_id = cc.id
        LEFT JOIN master_color mc ON mcp.master_color_id = mc.id
    ";
    
    if ($selected_buyer > 0) {
        $query .= " WHERE mcp.buyer_id = ?";
    }
    
    $query .= " ORDER BY b.nama_buyer, mcp.code_color, cc.component_name, csi.stock_number";
    
    $stmt = $conn->prepare($query);
    if ($selected_buyer > 0) {
        $stmt->bind_param("i", $selected_buyer);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    $data = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    
    // Log activity
    create_audit_log($conn, 'Print Data', $it_id, 'it', 'IT user printed data in Excel format for buyer ID: ' . $selected_buyer);
    
    // Generate Excel file with buyer name
    $filename = 'Color_Stock_' . $buyer_name_for_file . '_' . date('Y-m-d_His') . '.xls';
    
    header('Content-Type: application/vnd.ms-excel; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Pragma: no-cache');
    header('Expires: 0');
    
    // Output BOM for UTF-8
    echo "\xEF\xBB\xBF";
    
    // Start HTML table
    echo '<!DOCTYPE html>';
    echo '<html>';
    echo '<head>';
    echo '<meta charset="UTF-8">';
    echo '<style>';
    echo 'table { border-collapse: collapse; width: 100%; }';
    echo 'th, td { border: 1px solid black; padding: 8px; text-align: left; font-size: 12px; }';
    echo 'th { background-color: #4CAF50; color: white; font-weight: bold; }';
    echo '.header-info { font-size: 14px; margin-bottom: 10px; }';
    echo '</style>';
    echo '</head>';
    echo '<body>';
    
    echo '<div class="header-info">';
    echo '<h2>Color Stock Data Report</h2>';
    echo '<p><strong>Tanggal Print:</strong> ' . date('d/m/Y H:i:s') . '</p>';
    echo '<p><strong>Total Data:</strong> ' . count($data) . ' items</p>';
    if ($selected_buyer > 0) {
        echo '<p><strong>Buyer:</strong> ' . htmlspecialchars($data[0]['nama_buyer'] ?? 'N/A') . '</p>';
    } else {
        echo '<p><strong>Buyer:</strong> Semua Buyer</p>';
    }
    echo '</div>';
    
    echo '<table>';
    echo '<thead>';
    echo '<tr>';
    echo '<th style="background-color: #4CAF50;">No</th>';
    echo '<th style="background-color: #4CAF50;">Buyer</th>';
    echo '<th style="background-color: #4CAF50;">Collection</th>';
    echo '<th style="background-color: #4CAF50;">Master Color</th>';
    echo '<th style="background-color: #4CAF50;">Panel Code</th>';
    echo '<th style="background-color: #4CAF50;">Panel Description</th>';
    echo '<th style="background-color: #4CAF50;">Lemari</th>';
    echo '<th style="background-color: #4CAF50;">Component</th>';
    echo '<th style="background-color: #4CAF50;">Kode Barang</th>';
    echo '<th style="background-color: #4CAF50;">Stock Number</th>';
    echo '<th style="background-color: #4CAF50;">Item Type</th>';
    echo '<th style="background-color: #4CAF50;">Status</th>';
    echo '<th style="background-color: #4CAF50;">Lokasi</th>';
    echo '<th style="background-color: #4CAF50;">Rack No</th>';
    echo '<th style="background-color: #4CAF50;">Tanggal Pembuatan</th>';
    echo '<th style="background-color: #4CAF50;">Tanggal Kedaluwarsa</th>';
    echo '<th style="background-color: #4CAF50;">Keterangan</th>';
    echo '</tr>';
    echo '</thead>';
    echo '<tbody>';
    
    $no = 1;
    foreach ($data as $row) {
        echo '<tr>';
        echo '<td>' . $no++ . '</td>';
        echo '<td>' . htmlspecialchars($row['nama_buyer']) . '</td>';
        echo '<td>' . htmlspecialchars($row['nama_collection']) . '</td>';
        echo '<td>' . htmlspecialchars($row['master_code_color'] ?? 'N/A') . ' - ' . htmlspecialchars($row['master_name_color'] ?? 'N/A') . '</td>';
        echo '<td>' . htmlspecialchars($row['code_color']) . '</td>';
        echo '<td>' . htmlspecialchars($row['deskripsi']) . '</td>';
        echo '<td>' . htmlspecialchars($row['lemari']) . '.' . htmlspecialchars($row['lemari_number']) . '</td>';
        echo '<td>' . htmlspecialchars($row['component_name']) . '</td>';
        echo '<td>' . htmlspecialchars($row['kode_barang']) . '</td>';
        echo '<td>' . htmlspecialchars($row['stock_number']) . '</td>';
        echo '<td>' . htmlspecialchars($row['item_type']) . '</td>';
        echo '<td>' . htmlspecialchars($row['status']) . '</td>';
        echo '<td>' . htmlspecialchars($row['lokasi']) . '</td>';
        echo '<td>' . htmlspecialchars($row['rack_no'] ?? 'N/A') . '</td>';
        echo '<td>' . ($row['tanggal_pembuatan'] ? date('d/m/Y', strtotime($row['tanggal_pembuatan'])) : '-') . '</td>';
        echo '<td>' . ($row['tanggal_kedaluwarsa'] ? date('d/m/Y', strtotime($row['tanggal_kedaluwarsa'])) : '-') . '</td>';
        echo '<td>' . htmlspecialchars($row['keterangan'] ?? '') . '</td>';
        echo '</tr>';
    }
    
    echo '</tbody>';
    echo '</table>';
    echo '</body>';
    echo '</html>';
    exit();
}

// Get buyers for filter - only buyers that have color data
$buyers_query = "SELECT DISTINCT b.id, b.nama_buyer, b.kode_buyer 
                 FROM buyers b 
                 INNER JOIN master_color_panel mcp ON b.id = mcp.buyer_id
                 INNER JOIN color_stock_items csi ON mcp.id = csi.color_id
                 ORDER BY b.nama_buyer";
$buyers_result = $conn->query($buyers_query);

// Set page title
$page_title = "Print Data Stock";

// Log activity
create_audit_log($conn, 'Print Data Access', $it_id, 'it', 'IT user accessed print data 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-2">Print Data Stock</h2>
        <p class="text-gray-600 mb-4">Export data color stock dalam format Excel (Master Color & Copy Panel)</p>
    </div>

    <!-- Print Form -->
    <div class="bg-white rounded-lg shadow-md p-6">
        <form method="POST" action="" id="printForm">
            <input type="hidden" name="print_action" value="1">
            
            <!-- Buyer Filter -->
            <div class="mb-6">
                <label for="buyer_id" class="block text-sm font-medium text-gray-700 mb-2">
                    <i class="fas fa-filter mr-2"></i>Filter Buyer:
                </label>
                <select 
                    name="buyer_id" 
                    id="buyer_id" 
                    class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    onchange="updatePreview()"
                >
                    <option value="0">Semua Buyer</option>
                    <?php 
                    $buyers_result->data_seek(0); // Reset result pointer
                    while ($buyer = $buyers_result->fetch_assoc()): 
                    ?>
                        <option value="<?php echo $buyer['id']; ?>">
                            <?php echo htmlspecialchars($buyer['kode_buyer'] . ' - ' . $buyer['nama_buyer']); ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>

            <!-- Preview Info -->
            <div id="previewInfo" class="mb-6 p-4 bg-blue-50 border-l-4 border-blue-500 rounded">
                <p class="text-sm text-gray-700">
                    <i class="fas fa-info-circle mr-2"></i>
                    <span id="previewText">Memuat informasi preview...</span>
                </p>
            </div>

            <!-- Export Button -->
            <div class="mb-6">
                <button 
                    type="submit" 
                    class="w-full flex items-center justify-center px-6 py-4 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors duration-200 shadow-md hover:shadow-lg"
                >
                    <i class="fas fa-file-excel text-3xl mr-3"></i>
                    <div class="text-left">
                        <div class="font-semibold text-lg">Export ke Excel</div>
                        <div class="text-sm opacity-90">Download data dalam format .xls</div>
                    </div>
                </button>
            </div>

            <!-- Information Box -->
            <div class="bg-yellow-50 border-l-4 border-yellow-400 p-4 rounded">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <i class="fas fa-exclamation-triangle text-yellow-400 text-xl"></i>
                    </div>
                    <div class="ml-3">
                        <h3 class="text-sm font-medium text-yellow-800">Informasi Export Data</h3>
                        <div class="mt-2 text-sm text-yellow-700">
                            <ul class="list-disc list-inside space-y-1">
                                <li>Data mencakup Master Color dan Copy Panel dengan semua detail</li>
                                <li>Termasuk informasi buyer, collection, component, dan stock details</li>
                                <li>File Excel dapat dibuka dengan Microsoft Excel atau aplikasi spreadsheet lainnya</li>
                                <li>Pilih buyer untuk memfilter data, atau pilih "Semua Buyer" untuk export semua data</li>
                                <li>Header tabel akan memiliki background warna hijau untuk kemudahan membaca</li>
                                <li>Nama file akan menyertakan kode buyer dan timestamp</li>
                                <li>Data diurutkan berdasarkan buyer, color panel, dan component</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <!-- Data Structure Info -->
    <div class="bg-white rounded-lg shadow-md p-6 mt-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">
            <i class="fas fa-table mr-2"></i>Struktur Data Export
        </h3>
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
                <h4 class="font-medium text-gray-700 mb-2">Informasi Master:</h4>
                <ul class="text-sm text-gray-600 space-y-1">
                    <li>• Buyer & Collection</li>
                    <li>• Master Color Code & Name</li>
                    <li>• Panel Code & Description</li>
                    <li>• Lemari & Lemari Number</li>
                </ul>
            </div>
            <div>
                <h4 class="font-medium text-gray-700 mb-2">Detail Stock Item:</h4>
                <ul class="text-sm text-gray-600 space-y-1">
                    <li>• Component Name</li>
                    <li>• Kode Barang & Stock Number</li>
                    <li>• Status, Lokasi, Rack Number</li>
                    <li>• Tanggal Pembuatan & Kedaluwarsa</li>
                </ul>
            </div>
        </div>
    </div>
</main>

<script>
// Update preview information
function updatePreview() {
    const buyerId = document.getElementById('buyer_id').value;
    const previewText = document.getElementById('previewText');
    
    // Show loading
    previewText.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Memuat preview...';
    
    // Fetch preview data
    fetch('get_print_preview.php?buyer_id=' + buyerId)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                previewText.innerHTML = `
                    Data yang akan di-export: 
                    <strong>${data.total_items.toLocaleString()}</strong> stock items dari 
                    <strong>${data.total_panels.toLocaleString()}</strong> color panels dan
                    <strong>${data.total_master_colors.toLocaleString()}</strong> master colors
                    ${data.buyer_name ? ' (Buyer: <strong>' + data.buyer_name + '</strong>)' : ' (Semua Buyer)'}
                `;
            } else {
                previewText.innerHTML = 'Gagal memuat preview: ' + (data.message || 'Unknown error');
            }
        })
        .catch(error => {
            previewText.innerHTML = 'Error memuat preview';
            console.error('Error:', error);
        });
}

// Load preview on page load
document.addEventListener('DOMContentLoaded', function() {
    updatePreview();
});

// Form submission handling
document.getElementById('printForm').addEventListener('submit', function(e) {
    const buyerId = document.getElementById('buyer_id').value;
    const buyerSelect = document.getElementById('buyer_id');
    const buyerText = buyerSelect.options[buyerSelect.selectedIndex].text;
    
    // Show confirmation
    const confirmMsg = buyerId === '0' 
        ? 'Export data untuk SEMUA BUYER?\n\nData akan mencakup semua master color dan copy panel.' 
        : 'Export data untuk buyer: ' + buyerText + '?\n\nData akan mencakup master color dan copy panel untuk buyer ini.';
    
    if (!confirm(confirmMsg)) {
        e.preventDefault();
        return false;
    }
    
    // Show processing state
    const submitBtn = e.target.querySelector('button[type="submit"]');
    const originalHTML = submitBtn.innerHTML;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin text-3xl mr-3"></i><div class="text-left"><div class="font-semibold text-lg">Processing...</div><div class="text-sm opacity-90">Sedang membuat file Excel...</div></div>';
    submitBtn.disabled = true;
    
    // Re-enable button after 3 seconds (in case something goes wrong)
    setTimeout(() => {
        submitBtn.innerHTML = originalHTML;
        submitBtn.disabled = false;
    }, 3000);
});
</script>

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