<?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'];

// Set page title
$page_title = "Report Code Barang";

// Log activity
create_audit_log($conn, 'Report Code Barang Access', $it_id, 'it', 'IT user accessed code barang report');

// Handle Excel Export
if (isset($_GET['export']) && $_GET['export'] == 'excel') {
    $export_type = isset($_GET['export_type']) ? $_GET['export_type'] : 'filtered';
    $filename_suffix = $export_type == 'full' ? 'Full_Report' : 'Filtered_Report';
    
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="Report_Code_Barang_' . $filename_suffix . '_' . date('Y-m-d_H-i-s') . '.xls"');
    header('Cache-Control: max-age=0');
    
    echo '<table border="1">';
    echo '<tr>';
    echo '<th>Kode Barang</th>';
    echo '<th>Color Code</th>';
    echo '<th>Component</th>';
    echo '<th>Buyer</th>';
    echo '<th>Collection</th>';
    echo '<th>Status</th>';
    echo '<th>Lokasi</th>';
    echo '<th>Rack No</th>';
    echo '<th>Tanggal Pembuatan</th>';
    echo '<th>Tanggal Kedaluwarsa</th>';
    echo '<th>Keterangan</th>';
    echo '</tr>';
    
    // Build export query based on type
    if ($export_type == 'full') {
        // Full report - no filters
        $export_query = "SELECT csi.kode_barang, mcp.code_color, cc.component_name, 
                                b.nama_buyer, col.nama_collection, csi.status, 
                                csi.lokasi, csi.rack_no, csi.tanggal_pembuatan, 
                                csi.tanggal_kedaluwarsa, csi.keterangan
                         FROM color_stock_items csi
                         JOIN master_color_panel mcp ON csi.color_id = mcp.id
                         JOIN color_components cc ON csi.component_id = cc.id
                         JOIN buyers b ON mcp.buyer_id = b.id
                         JOIN collections col ON mcp.collection_id = col.id
                         ORDER BY b.nama_buyer, mcp.code_color, csi.kode_barang ASC";
        $export_result = $conn->query($export_query);
    } else {
        // Filtered report - use same filters as display
        $buyer_filter = isset($_GET['buyer']) ? $_GET['buyer'] : '';
        $where_conditions = [];
        $export_params = [];
        $export_param_types = '';

        if (!empty($status_filter)) {
            $where_conditions[] = "csi.status = ?";
            $export_params[] = $status_filter;
            $export_param_types .= 's';
        }

        if (!empty($color_filter)) {
            $where_conditions[] = "mcp.code_color LIKE ?";
            $export_params[] = '%' . $color_filter . '%';
            $export_param_types .= 's';
        }

        if (!empty($date_from)) {
            $where_conditions[] = "csi.tanggal_pembuatan >= ?";
            $export_params[] = $date_from;
            $export_param_types .= 's';
        }

        if (!empty($date_to)) {
            $where_conditions[] = "csi.tanggal_pembuatan <= ?";
            $export_params[] = $date_to;
            $export_param_types .= 's';
        }

        if (!empty($buyer_filter)) {
            $where_conditions[] = "b.id = ?";
            $export_params[] = $buyer_filter;
            $export_param_types .= 'i';
        }

        $export_where_clause = '';
        if (!empty($where_conditions)) {
            $export_where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
        }

        $export_query = "SELECT csi.kode_barang, mcp.code_color, cc.component_name, 
                                b.nama_buyer, col.nama_collection, csi.status, 
                                csi.lokasi, csi.rack_no, csi.tanggal_pembuatan, 
                                csi.tanggal_kedaluwarsa, csi.keterangan
                         FROM color_stock_items csi
                         JOIN master_color_panel mcp ON csi.color_id = mcp.id
                         JOIN color_components cc ON csi.component_id = cc.id
                         JOIN buyers b ON mcp.buyer_id = b.id
                         JOIN collections col ON mcp.collection_id = col.id
                         $export_where_clause
                         ORDER BY b.nama_buyer, mcp.code_color, csi.kode_barang ASC";

        $export_stmt = $conn->prepare($export_query);
        if (!empty($export_params)) {
            $export_stmt->bind_param($export_param_types, ...$export_params);
        }
        $export_stmt->execute();
        $export_result = $export_stmt->get_result();
    }
    
    while ($row = $export_result->fetch_assoc()) {
        echo '<tr>';
        echo '<td>' . htmlspecialchars($row['kode_barang']) . '</td>';
        echo '<td>' . htmlspecialchars($row['code_color']) . '</td>';
        echo '<td>' . htmlspecialchars($row['component_name']) . '</td>';
        echo '<td>' . htmlspecialchars($row['nama_buyer']) . '</td>';
        echo '<td>' . htmlspecialchars($row['nama_collection']) . '</td>';
        echo '<td>' . htmlspecialchars($row['status']) . '</td>';
        echo '<td>' . htmlspecialchars($row['lokasi']) . '</td>';
        echo '<td>' . htmlspecialchars($row['rack_no']) . '</td>';
        echo '<td>' . htmlspecialchars($row['tanggal_pembuatan']) . '</td>';
        echo '<td>' . htmlspecialchars($row['tanggal_kedaluwarsa']) . '</td>';
        echo '<td>' . htmlspecialchars($row['keterangan']) . '</td>';
        echo '</tr>';
    }
    
    echo '</table>';
    exit();
}

// Filter parameters
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$color_filter = isset($_GET['color']) ? $_GET['color'] : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$buyer_filter = isset($_GET['buyer']) ? $_GET['buyer'] : '';

// Build query with filters
$where_conditions = [];
$params = [];
$param_types = '';

if (!empty($status_filter)) {
    $where_conditions[] = "csi.status = ?";
    $params[] = $status_filter;
    $param_types .= 's';
}

if (!empty($color_filter)) {
    $where_conditions[] = "mcp.code_color LIKE ?";
    $params[] = '%' . $color_filter . '%';
    $param_types .= 's';
}

if (!empty($date_from)) {
    $where_conditions[] = "csi.tanggal_pembuatan >= ?";
    $params[] = $date_from;
    $param_types .= 's';
}

if (!empty($date_to)) {
    $where_conditions[] = "csi.tanggal_pembuatan <= ?";
    $params[] = $date_to;
    $param_types .= 's';
}

if (!empty($buyer_filter)) {
    $where_conditions[] = "b.id = ?";
    $params[] = $buyer_filter;
    $param_types .= 'i';
}

$where_clause = '';
if (!empty($where_conditions)) {
    $where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
}

$query = "SELECT csi.kode_barang, mcp.code_color, cc.component_name, csi.status, 
                 csi.lokasi, csi.rack_no, csi.tanggal_pembuatan, csi.tanggal_kedaluwarsa, 
                 csi.keterangan, b.nama_buyer, col.nama_collection
          FROM color_stock_items csi
          JOIN master_color_panel mcp ON csi.color_id = mcp.id
          JOIN color_components cc ON csi.component_id = cc.id
          JOIN buyers b ON mcp.buyer_id = b.id
          JOIN collections col ON mcp.collection_id = col.id
          $where_clause
          ORDER BY b.nama_buyer, mcp.code_color, csi.kode_barang ASC";

$stmt = $conn->prepare($query);
if (!empty($params)) {
    $stmt->bind_param($param_types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();

// 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">
    <!-- Page Header -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <div class="flex justify-between items-center">
            <div>
                <h2 class="text-2xl font-bold text-gray-800 mb-2">Report Code Barang</h2>
                <p class="text-gray-600">Laporan data code barang dan status inventory</p>
            </div>
            <div class="flex space-x-2">
                <div class="relative">
                    <button type="button" id="exportBtn" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-lg transition duration-200 flex items-center">
                        <i class="fas fa-file-excel mr-2"></i>Export Excel
                        <i class="fas fa-chevron-down ml-2"></i>
                    </button>
                    <div id="exportMenu" class="hidden absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg z-10 border">
                        <div class="py-1">
                            <a href="?export=excel&export_type=filtered<?php echo !empty($_SERVER['QUERY_STRING']) ? '&' . str_replace(['export=excel&', 'export_type=filtered&', 'export_type=full&'], '', $_SERVER['QUERY_STRING']) : ''; ?>" 
                               class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
                                <i class="fas fa-filter mr-2"></i>Export Data Terfilter
                            </a>
                            <a href="?export=excel&export_type=full" 
                               class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
                                <i class="fas fa-database mr-2"></i>Export Full Report
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filter Section -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">Filter Data</h3>
        <form method="GET" class="grid grid-cols-1 md:grid-cols-5 gap-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Buyer</label>
                <select name="buyer" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <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_row = $buyer_result->fetch_assoc()) {
                        $selected = $buyer_filter == $buyer_row['id'] ? 'selected' : '';
                        echo '<option value="' . $buyer_row['id'] . '" ' . $selected . '>' . htmlspecialchars($buyer_row['nama_buyer']) . '</option>';
                    }
                    ?>
                </select>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Status</label>
                <select name="status" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">Semua Status</option>
                    <option value="Tersedia" <?php echo $status_filter == 'Tersedia' ? 'selected' : ''; ?>>Tersedia</option>
                    <option value="Dipinjam" <?php echo $status_filter == 'Dipinjam' ? 'selected' : ''; ?>>Dipinjam</option>
                    <option value="Rusak" <?php echo $status_filter == 'Rusak' ? 'selected' : ''; ?>>Rusak</option>
                    <option value="Expired" <?php echo $status_filter == 'Expired' ? 'selected' : ''; ?>>Expired</option>
                    <option value="Renew" <?php echo $status_filter == 'Renew' ? 'selected' : ''; ?>>Renew</option>
                    <option value="Hilang" <?php echo $status_filter == 'Hilang' ? 'selected' : ''; ?>>Hilang</option>
                </select>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Color Code</label>
                <input type="text" name="color" value="<?php echo htmlspecialchars($color_filter); ?>" 
                       placeholder="Cari color code..." 
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Tanggal Dari</label>
                <input type="date" name="date_from" value="<?php echo htmlspecialchars($date_from); ?>" 
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Tanggal Sampai</label>
                <input type="date" name="date_to" value="<?php echo htmlspecialchars($date_to); ?>" 
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            
            <div class="md:col-span-5 flex space-x-2">
                <button type="submit" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg transition duration-200">
                    <i class="fas fa-filter mr-2"></i>Filter
                </button>
                <a href="report_code_barang.php" class="bg-gray-500 hover:bg-gray-600 text-white px-4 py-2 rounded-lg transition duration-200">
                    <i class="fas fa-refresh mr-2"></i>Reset
                </a>
            </div>
        </form>
    </div>

    <!-- Data Table -->
    <div class="bg-white rounded-lg shadow-md overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full table-auto">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kode Barang</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Color Code</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Component</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Buyer</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Lokasi</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Rack No</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tgl Pembuatan</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tgl Kedaluwarsa</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Keterangan</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if ($result->num_rows > 0): ?>
                        <?php while ($row = $result->fetch_assoc()): ?>
                            <tr class="hover:bg-gray-50">
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                                    <?php echo htmlspecialchars($row['kode_barang']); ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                    <?php echo htmlspecialchars($row['code_color']); ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                    <?php echo htmlspecialchars($row['component_name']); ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                    <div class="flex items-center">
                                        <span class="text-xs bg-blue-100 text-blue-800 px-2 py-1 rounded-full">
                                            <?php echo htmlspecialchars($row['nama_buyer']); ?>
                                        </span>
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm">
                                    <?php
                                    $status_class = '';
                                    switch($row['status']) {
                                        case 'Tersedia':
                                            $status_class = 'bg-green-100 text-green-800';
                                            break;
                                        case 'Dipinjam':
                                            $status_class = 'bg-yellow-100 text-yellow-800';
                                            break;
                                        case 'Rusak':
                                            $status_class = 'bg-red-100 text-red-800';
                                            break;
                                        case 'Expired':
                                            $status_class = 'bg-gray-100 text-gray-800';
                                            break;
                                        case 'Renew':
                                            $status_class = 'bg-blue-100 text-blue-800';
                                            break;
                                        case 'Hilang':
                                            $status_class = 'bg-purple-100 text-purple-800';
                                            break;
                                        default:
                                            $status_class = 'bg-gray-100 text-gray-800';
                                    }
                                    ?>
                                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full <?php echo $status_class; ?>">
                                        <?php echo htmlspecialchars($row['status']); ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                    <?php echo htmlspecialchars($row['lokasi']); ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                    <?php echo htmlspecialchars($row['rack_no']); ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                    <?php echo $row['tanggal_pembuatan'] ? date('d/m/Y', strtotime($row['tanggal_pembuatan'])) : '-'; ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                    <?php echo $row['tanggal_kedaluwarsa'] ? date('d/m/Y', strtotime($row['tanggal_kedaluwarsa'])) : '-'; ?>
                                </td>
                                <td class="px-6 py-4 text-sm text-gray-900">
                                    <?php echo htmlspecialchars($row['keterangan']); ?>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="10" class="px-6 py-4 text-center text-sm text-gray-500">
                                Tidak ada data yang ditemukan
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const exportBtn = document.getElementById('exportBtn');
    const exportMenu = document.getElementById('exportMenu');
    
    exportBtn.addEventListener('click', function() {
        exportMenu.classList.toggle('hidden');
    });
    
    // Close menu when clicking outside
    document.addEventListener('click', function(event) {
        if (!exportBtn.contains(event.target) && !exportMenu.contains(event.target)) {
            exportMenu.classList.add('hidden');
        }
    });
});
</script>

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