<?php
// Start session
session_start();

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

// Redirect if not IT user
if (!isset($_SESSION['user_type']) || $_SESSION['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_surabaya';
    if ($selected_buyer > 0) {
        $buyer_stmt = $conn->prepare("SELECT kode_buyer FROM buyers_surabaya 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
    $query = "
        SELECT 
            b.nama_buyer,
            b.kode_buyer,
            mcp.code_color,
            mcp.deskripsi,
            mcp.lemari,
            cc.component_name,
            csi.kode_barang,
            csi.status,
            csi.lokasi,
            csi.rack_no,
            csi.tanggal_pembuatan,
            csi.tanggal_kedaluwarsa,
            csi.keterangan
        FROM color_stock_items_surabaya csi
        JOIN master_color_panel_surabaya mcp ON csi.color_id = mcp.id
        JOIN buyers_surabaya b ON mcp.buyer_id = b.id
        JOIN color_components_surabaya cc ON csi.component_id = cc.id
    ";
    
    if ($selected_buyer > 0) {
        $query .= " WHERE mcp.buyer_id = ?";
    }
    
    $query .= " ORDER BY b.nama_buyer, mcp.code_color, cc.component_name";
    
    $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
    $log_stmt = $conn->prepare("INSERT INTO audit_logs_surabaya (action_type, user_id, user_type, details, ip_address) VALUES (?, ?, ?, ?, ?)");
    $action = 'Print Data';
    $user_type = 'it';
    $details = 'IT user printed data in Excel format for buyer ID: ' . $selected_buyer;
    $ip = $_SERVER['REMOTE_ADDR'];
    $log_stmt->bind_param("sisss", $action, $it_id, $user_type, $details, $ip);
    $log_stmt->execute();
    $log_stmt->close();
    
    // 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; }';
    echo 'th { background-color: #4CAF50; color: white; font-weight: bold; }';
    echo '</style>';
    echo '</head>';
    echo '<body>';
    
    echo '<h2>Color Stock Data Report</h2>';
    echo '<p>Tanggal Print: ' . date('d/m/Y H:i:s') . '</p>';
    echo '<p>Total Data: ' . count($data) . ' items</p>';
    
    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;">Kode Buyer</th>';
    echo '<th style="background-color: #4CAF50;">Code Color</th>';
    echo '<th style="background-color: #4CAF50;">Deskripsi</th>';
    echo '<th style="background-color: #4CAF50;">Lemari</th>';
    echo '<th style="background-color: #4CAF50;">Component</th>';
    echo '<th style="background-color: #4CAF50;">Code Barang</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['kode_buyer']) . '</td>';
        echo '<td>' . htmlspecialchars($row['code_color']) . '</td>';
        echo '<td>' . htmlspecialchars($row['deskripsi']) . '</td>';
        echo '<td>' . htmlspecialchars($row['lemari']) . '</td>';
        echo '<td>' . htmlspecialchars($row['component_name']) . '</td>';
        echo '<td>' . htmlspecialchars($row['kode_barang']) . '</td>';
        echo '<td>' . htmlspecialchars($row['status']) . '</td>';
        echo '<td>' . htmlspecialchars($row['lokasi']) . '</td>';
        echo '<td>' . htmlspecialchars($row['rack_no']) . '</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_surabaya for filter
$buyers_surabaya_query = "SELECT id, nama_buyer, kode_buyer FROM buyers_surabaya ORDER BY nama_buyer";
$buyers_surabaya_result = $conn->query($buyers_surabaya_query);

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

// Log activity
$log_stmt = $conn->prepare("INSERT INTO audit_logs_surabaya (action_type, user_id, user_type, details, ip_address) VALUES (?, ?, ?, ?, ?)");
$action = 'Print Data Access';
$user_type = 'it';
$details = 'IT user accessed print data page';
$ip = $_SERVER['REMOTE_ADDR'];
$log_stmt->bind_param("sisss", $action, $it_id, $user_type, $details, $ip);
$log_stmt->execute();
$log_stmt->close();

// 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</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_surabaya_result->data_seek(0); // Reset result pointer
                    while ($buyer = $buyers_surabaya_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 Penting</h3>
                        <div class="mt-2 text-sm text-yellow-700">
                            <ul class="list-disc list-inside space-y-1">
                                <li>Data yang di-export mencakup semua informasi stock item</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</li>
                                <li>Nama file akan menyertakan kode buyer yang dipilih</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </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}</strong> item dari 
                    <strong>${data.total_colors}</strong> color panel
                    ${data.buyer_name ? ' (Buyer: <strong>' + data.buyer_name + '</strong>)' : ' (Semua Buyer)'}
                `;
            } else {
                previewText.innerHTML = 'Gagal memuat preview';
            }
        })
        .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 buyers_surabayaelect = document.getElementById('buyer_id');
    const buyerText = buyers_surabayaelect.options[buyers_surabayaelect.selectedIndex].text;
    
    // Show confirmation
    const confirmMsg = buyerId === '0' 
        ? 'Export data untuk SEMUA BUYER?' 
        : 'Export data untuk buyer: ' + buyerText + '?';
    
    if (!confirm(confirmMsg)) {
        e.preventDefault();
        return false;
    }
});
</script>

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