<?php
require_once "config/connection.php";

// Get filter parameters
$buyer_id = isset($_POST['buyer']) ? $_POST['buyer'] : '';
$color_id = isset($_POST['color']) ? $_POST['color'] : '';
$component_id = isset($_POST['component']) ? $_POST['component'] : '';
$status = isset($_POST['status']) ? $_POST['status'] : '';
$search = isset($_POST['search']) ? trim($_POST['search']) : '';

// Build WHERE clause for filters
$where_conditions = [];
$params = [];
$types = "";

if (!empty($buyer_id)) {
    $where_conditions[] = "mcp.buyer_id = ?";
    $params[] = $buyer_id;
    $types .= "i";
}

if (!empty($color_id)) {
    $where_conditions[] = "mcp.id = ?";
    $params[] = $color_id;
    $types .= "i";
}

if (!empty($component_id)) {
    $where_conditions[] = "csi.component_id = ?";
    $params[] = $component_id;
    $types .= "i";
}

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

// Enhanced search logic
$search_condition = "";
$search_order = "";
$search_priority = "0"; // Default priority

if (!empty($search)) {
    // Check if search is for kode_barang (starts with "CP.") or color_code
    $is_kode_barang_search = (strpos(strtoupper($search), 'CP.') === 0 || preg_match('/^CP\.\d+/', strtoupper($search)));
    
    if ($is_kode_barang_search) {
        // Search for kode_barang - only show exact matches or colors that contain matching items
        $search_condition = " AND csi.kode_barang LIKE ?";
        $search_param = "%{$search}%";
        $params[] = $search_param;
        $types .= "s";
        
        // Priority: exact kode_barang matches first
        $search_priority = "CASE WHEN csi.kode_barang LIKE ? THEN 1 ELSE 2 END";
        $params[] = $search_param;
        $types .= "s";
    } else {
        // Search for color_code - only show colors that match
        $search_condition = " AND mcp.code_color LIKE ?";
        $search_param = "%{$search}%";
        $params[] = $search_param;
        $types .= "s";
        
        // Priority: exact color_code matches first
        $search_priority = "CASE WHEN mcp.code_color LIKE ? THEN 1 ELSE 2 END";
        $params[] = $search_param;
        $types .= "s";
    }
    
    $search_order = ", " . $search_priority;
}

// Build the main query
$base_where = !empty($where_conditions) ? "WHERE " . implode(" AND ", $where_conditions) : "";
$full_where = $base_where . $search_condition;

// Updated query with better ordering for search results
$query = "
    SELECT 
        mcp.id as color_id,
        mcp.code_color,
        mcp.deskripsi,
        mcp.lemari,
        mcp.status as color_status,
        b.nama_buyer,
        csi.id as stock_id,
        csi.kode_barang,
        csi.stock_number,
        csi.status,
        csi.lokasi,
        csi.rack_no,
        csi.qr_code,
        csi.tanggal_pembuatan,
        csi.tanggal_kedaluwarsa,
        csi.keterangan,
        cc.component_name,
        cc.id as component_id
    FROM master_color_panel mcp
    LEFT JOIN buyers b ON mcp.buyer_id = b.id
    LEFT JOIN color_stock_items csi ON mcp.id = csi.color_id
    LEFT JOIN color_components cc ON csi.component_id = cc.id
    $full_where
    ORDER BY " . (!empty($search) ? $search_priority : "1") . ", b.nama_buyer, mcp.code_color, cc.component_name, csi.stock_number
";

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

// Group data by color - only include colors that have matching results
$colors = [];
$search_matches = [];

while ($row = $result->fetch_assoc()) {
    $color_id = $row['color_id'];
    
    // Skip if this color doesn't match search criteria
    if (!empty($search)) {
        $is_kode_barang_search = (strpos(strtoupper($search), 'CP.') === 0 || preg_match('/^CP\.\d+/', strtoupper($search)));
        
        if ($is_kode_barang_search) {
            // For kode_barang search, only include if there's a matching item
            $has_matching_item = false;
            if ($row['stock_id'] && $row['kode_barang'] && stripos($row['kode_barang'], $search) !== false) {
                $has_matching_item = true;
            }
            if (!$has_matching_item) {
                continue; // Skip this color if no matching kode_barang
            }
        } else {
            // For color_code search, only include if color code matches
            if (!$row['code_color'] || stripos($row['code_color'], $search) === false) {
                continue; // Skip this color if color code doesn't match
            }
        }
    }
    
    if (!isset($colors[$color_id])) {
        $colors[$color_id] = [
            'color_id' => $color_id,
            'code_color' => $row['code_color'],
            'deskripsi' => $row['deskripsi'],
            'lemari' => $row['lemari'],
            'color_status' => $row['color_status'],
            'buyer_name' => $row['nama_buyer'],
            'components' => [],
            'has_search_match' => false
        ];
    }
    
    // Only add stock items that exist
    if ($row['stock_id']) {
        $component_key = $row['component_id'] . '_' . $row['component_name'];
        
        if (!isset($colors[$color_id]['components'][$component_key])) {
            $colors[$color_id]['components'][$component_key] = [
                'component_id' => $row['component_id'],
                'component_name' => $row['component_name'],
                'items' => []
            ];
        }
        
        $colors[$color_id]['components'][$component_key]['items'][] = [
            'stock_id' => $row['stock_id'],
            'kode_barang' => $row['kode_barang'],
            'stock_number' => $row['stock_number'],
            'status' => $row['status'],
            'lokasi' => $row['lokasi'],
            'rack_no' => $row['rack_no'],
            'qr_code' => $row['qr_code'],
            'tanggal_pembuatan' => $row['tanggal_pembuatan'],
            'tanggal_kedaluwarsa' => $row['tanggal_kedaluwarsa'],
            'keterangan' => $row['keterangan']
        ];
        
        // Mark if this color has search matches
        if (!empty($search)) {
            $is_kode_barang_search = (strpos(strtoupper($search), 'CP.') === 0 || preg_match('/^CP\.\d+/', strtoupper($search)));
            
            if ($is_kode_barang_search && stripos($row['kode_barang'], $search) !== false) {
                $colors[$color_id]['has_search_match'] = true;
            } elseif (!$is_kode_barang_search && stripos($row['code_color'], $search) !== false) {
                $colors[$color_id]['has_search_match'] = true;
            }
        }
    }
}

// Function to highlight search terms with better accuracy
function highlightSearch($text, $search) {
    if (empty($search) || empty($text)) return htmlspecialchars($text);
    
    $text = htmlspecialchars($text);
    $search = trim($search);
    
    // Escape special regex characters in search term
    $searchEscaped = preg_quote($search, '/');
    
    // Use case-insensitive search with word boundaries for better accuracy
    $pattern = '/(' . $searchEscaped . ')/i';
    
    $highlighted = preg_replace($pattern, '<span class="search-highlight bg-yellow-300 text-yellow-900 px-1 py-0.5 rounded font-semibold animate-pulse">$1</span>', $text);
    
    return $highlighted;
}

// Function to check if text contains search term (case-insensitive)
function containsSearch($text, $search) {
    if (empty($search) || empty($text)) return false;
    return stripos($text, trim($search)) !== false;
}

// Function to get status badge class
function getStatusBadgeClass($status) {
    switch ($status) {
        case 'Tersedia':
            return 'bg-green-100 text-green-800';
        case 'Dipinjam':
            return 'bg-blue-100 text-blue-800';
        case 'Rusak':
            return 'bg-red-100 text-red-800';
        case 'Expired':
            return 'bg-gray-100 text-gray-800';
        case 'Renew':
            return 'bg-purple-100 text-purple-800';
        case 'Hilang':
            return 'bg-yellow-100 text-yellow-800';
        default:
            return 'bg-gray-100 text-gray-800';
    }
}

// Function to get color status badge
function getColorStatusBadge($status) {
    switch ($status) {
        case 'Hijau':
            return '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">Hijau</span>';
        case 'Kuning':
            return '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">Kuning</span>';
        case 'Merah':
            return '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">Merah</span>';
        default:
            return '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">-</span>';
    }
}

// Sort colors by search relevance if search is active
if (!empty($search)) {
    // Sort colors to show exact matches first
    uasort($colors, function($a, $b) use ($search) {
        $is_kode_barang_search = (strpos(strtoupper($search), 'CP.') === 0 || preg_match('/^CP\.\d+/', strtoupper($search)));
        
        if ($is_kode_barang_search) {
            // For kode_barang search, prioritize colors with exact kode_barang matches
            $a_has_exact = false;
            $b_has_exact = false;
            
            foreach ($a['components'] as $component) {
                foreach ($component['items'] as $item) {
                    if (stripos($item['kode_barang'], $search) !== false) {
                        $a_has_exact = true;
                        break 2;
                    }
                }
            }
            
            foreach ($b['components'] as $component) {
                foreach ($component['items'] as $item) {
                    if (stripos($item['kode_barang'], $search) !== false) {
                        $b_has_exact = true;
                        break 2;
                    }
                }
            }
            
            if ($a_has_exact && !$b_has_exact) return -1;
            if (!$a_has_exact && $b_has_exact) return 1;
        } else {
            // For color_code search, prioritize exact color matches
            $a_exact = (stripos($a['code_color'], $search) !== false);
            $b_exact = (stripos($b['code_color'], $search) !== false);
            
            if ($a_exact && !$b_exact) return -1;
            if (!$a_exact && $b_exact) return 1;
        }
        
        return strcasecmp($a['code_color'], $b['code_color']);
    });
}

if (empty($colors)) {
    if (!empty($search)) {
        echo '<div class="text-center py-8">
                <i class="fas fa-search text-gray-400 text-4xl mb-4"></i>
                <p class="text-gray-500 text-lg">Tidak ada hasil untuk pencarian "' . htmlspecialchars($search) . '"</p>
                <p class="text-gray-400 text-sm mt-2">Coba gunakan kata kunci lain atau periksa ejaan</p>
              </div>';
    } else {
        echo '<div class="text-center py-8">
                <i class="fas fa-search text-gray-400 text-4xl mb-4"></i>
                <p class="text-gray-500 text-lg">Tidak ada data yang ditemukan</p>
                <p class="text-gray-400 text-sm mt-2">Coba ubah filter atau kata kunci pencarian</p>
              </div>';
    }
} else {
    foreach ($colors as $color) {
        $total_items = 0;
        $tersedia_count = 0;
        $dipinjam_count = 0;
        
        // Count total items and status
        foreach ($color['components'] as $component) {
            foreach ($component['items'] as $item) {
                $total_items++;
                if ($item['status'] == 'Tersedia') $tersedia_count++;
                if ($item['status'] == 'Dipinjam') $dipinjam_count++;
            }
        }
        
        // Determine if this color should be automatically expanded for search
        $auto_expand = false;
        $has_color_match = false;
        $has_item_match = false;
        
        if (!empty($search)) {
            $is_kode_barang_search = (strpos(strtoupper($search), 'CP.') === 0 || preg_match('/^CP\.\d+/', strtoupper($search)));
            
            if ($is_kode_barang_search) {
                // For kode_barang search, expand if any item matches
                foreach ($color['components'] as $component) {
                    foreach ($component['items'] as $item) {
                        if (containsSearch($item['kode_barang'], $search)) {
                            $auto_expand = true;
                            $has_item_match = true;
                            break 2;
                        }
                    }
                }
            } else {
                // For color_code search, expand if color matches
                if (containsSearch($color['code_color'], $search)) {
                    $auto_expand = true;
                    $has_color_match = true;
                }
            }
        }
        
        echo '<div class="color-item border border-gray-200 rounded-lg mb-4 overflow-hidden">';
        
        // Color Header
        echo '<div class="color-header bg-gradient-to-r from-blue-50 to-indigo-50 p-4 cursor-pointer hover:from-blue-100 hover:to-indigo-100 transition-colors duration-200" data-color-id="' . $color['color_id'] . '">';
        echo '<div class="flex items-center justify-between">';
        echo '<div class="flex items-center space-x-4">';
        echo '<i class="toggle-icon fas ' . ($auto_expand ? 'fa-chevron-down' : 'fa-chevron-right') . ' text-gray-600 text-lg"></i>';
        echo '<div>';
        echo '<h3 class="text-lg font-semibold text-gray-800">' . highlightSearch($color['code_color'], $search) . '</h3>';
        echo '<p class="text-sm text-gray-600">' . htmlspecialchars($color['deskripsi']) . ' • ' . htmlspecialchars($color['buyer_name']) . '</p>';
        echo '</div>';
        echo '</div>';
        
        echo '<div class="flex items-center space-x-4">';
        echo '<div class="text-right">';
        echo '<div class="flex items-center space-x-2 mb-1">';
        echo '<span class="text-xs text-gray-500">Lemari:</span>';
        echo '<span class="font-mono text-sm font-medium bg-gray-100 px-2 py-1 rounded">' . htmlspecialchars($color['lemari']) . '</span>';
        echo getColorStatusBadge($color['color_status']);
        echo '</div>';
        echo '<div class="text-xs text-gray-500">';
        echo '<span class="text-green-600 font-medium">' . $tersedia_count . ' Tersedia</span>';
        echo ' • ';
        echo '<span class="text-blue-600 font-medium">' . $dipinjam_count . ' Dipinjam</span>';
        echo ' • ';
        echo '<span class="text-gray-600 font-medium">Total: ' . $total_items . '</span>';
        echo '</div>';
        echo '</div>';
        echo '</div>';
        echo '</div>';
        echo '</div>';
        
        // Components Table
        echo '<div id="components-' . $color['color_id'] . '" class="' . ($auto_expand ? '' : 'hidden') . '">';
        
        if (!empty($color['components'])) {
            echo '<div class="overflow-x-auto">';
            echo '<table class="min-w-full divide-y divide-gray-200">';
            echo '<thead class="bg-gray-50">';
            echo '<tr>';
            echo '<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Component</th>';
            echo '<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kode Barang</th>';
            echo '<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Stock #</th>';
            echo '<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>';
            echo '<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Lokasi</th>';
            echo '<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Rack No</th>';
            echo '<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tanggal Expired</th>';
            echo '<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">QR Code</th>';
            echo '</tr>';
            echo '</thead>';
            echo '<tbody class="bg-white divide-y divide-gray-200">';
            
            foreach ($color['components'] as $component) {
                // Filter items based on search if it's a kode_barang search
                $filtered_items = $component['items'];
                if (!empty($search)) {
                    $is_kode_barang_search = (strpos(strtoupper($search), 'CP.') === 0 || preg_match('/^CP\.\d+/', strtoupper($search)));
                    
                    if ($is_kode_barang_search) {
                        // Only show items that match the search
                        $filtered_items = array_filter($component['items'], function($item) use ($search) {
                            return containsSearch($item['kode_barang'], $search);
                        });
                    }
                }
                
                // Skip component if no items match
                if (empty($filtered_items)) {
                    continue;
                }
                
                foreach ($filtered_items as $index => $item) {
                    echo '<tr class="component-row hover:bg-gray-50">';
                    
                    // Component name (only show for first item of each component)
                    if ($index === 0) {
                        $component_row_count = count($filtered_items);
                        echo '<td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900" rowspan="' . $component_row_count . '">';
                        echo '<div class="bg-blue-50 px-3 py-2 rounded-lg border border-blue-200">';
                        echo htmlspecialchars($component['component_name']);
                        echo '</div>';
                        echo '</td>';
                    }
                    
                    // Kode Barang
                    echo '<td class="px-6 py-4 whitespace-nowrap text-sm font-mono font-medium text-gray-900">';
                    if ($item['status'] === 'Dipinjam') {
                        echo '<button onclick="showBorrowedItemDetail(\'' . $item['kode_barang'] . '\')" class="text-blue-600 hover:text-blue-800 hover:underline">';
                        echo highlightSearch($item['kode_barang'], $search);
                        echo '</button>';
                    } else {
                        echo highlightSearch($item['kode_barang'], $search);
                    }
                    echo '</td>';
                    
                    // Stock Number
                    echo '<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">';
                    echo htmlspecialchars($item['stock_number']);
                    echo '</td>';
                    
                    // Status
                    echo '<td class="px-6 py-4 whitespace-nowrap">';
                    echo '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ' . getStatusBadgeClass($item['status']) . '">';
                    echo htmlspecialchars($item['status']);
                    echo '</span>';
                    echo '</td>';
                    
                    // Lokasi
                    echo '<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">';
                    echo htmlspecialchars($item['lokasi']);
                    echo '</td>';
                    
                    // Rack No
                    echo '<td class="px-6 py-4 whitespace-nowrap text-sm font-mono text-gray-900">';
                    echo htmlspecialchars($item['rack_no']);
                    echo '</td>';
                    
                    // Tanggal Expired
                    echo '<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">';
                    if ($item['tanggal_kedaluwarsa']) {
                        $expired_date = new DateTime($item['tanggal_kedaluwarsa']);
                        $today = new DateTime();
                        $days_diff = $today->diff($expired_date)->days;
                        $is_expired = $today > $expired_date;
                        
                        if ($is_expired) {
                            echo '<span class="text-red-600 font-medium">';
                            echo $expired_date->format('d/m/Y') . ' (Expired)';
                            echo '</span>';
                        } else if ($days_diff <= 7) {
                            echo '<span class="text-yellow-600 font-medium">';
                            echo $expired_date->format('d/m/Y') . ' (' . $days_diff . ' hari)';
                            echo '</span>';
                        } else {
                            echo $expired_date->format('d/m/Y');
                        }
                    } else {
                        echo '-';
                    }
                    echo '</td>';
                    
                    // QR Code
                    echo '<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">';
                    if ($item['qr_code']) {
                        echo '<button onclick="showQRModal(\'' . addslashes($item['qr_code']) . '\', \'' . addslashes($item['kode_barang']) . '\', \'' . addslashes($component['component_name']) . '\', \'' . addslashes($item['status']) . '\', \'' . addslashes($item['lokasi']) . '\', \'' . addslashes($item['rack_no']) . '\')" class="bg-blue-100 hover:bg-blue-200 text-blue-700 p-2 rounded-md transition duration-150 ease-in-out">';
                        echo '<i class="fas fa-qrcode"></i>';
                        echo '</button>';
                    } else {
                        echo '-';
                    }
                    echo '</td>';
                    
                    echo '</tr>';
                }
            }
            
            echo '</tbody>';
            echo '</table>';
            echo '</div>';
        } else {
            echo '<div class="p-6 text-center text-gray-500">';
            echo '<i class="fas fa-inbox text-3xl mb-2"></i>';
            echo '<p>Tidak ada stock item untuk color ini</p>';
            echo '</div>';
        }
        
        echo '</div>'; // End components container
        echo '</div>'; // End color item
    }
}
?>

<style>
.search-highlight {
    animation: highlight-pulse 2s ease-in-out infinite;
    box-shadow: 0 0 0 2px rgba(251, 191, 36, 0.3);
    border-radius: 4px;
}

@keyframes highlight-pulse {
    0%, 100% {
        background-color: rgb(253 224 71); /* yellow-300 */
        color: rgb(133 77 14); /* yellow-900 */
    }
    50% {
        background-color: rgb(254 240 138); /* yellow-200 */
        color: rgb(146 64 14); /* yellow-800 */
    }
}

.color-header:hover {
    background: linear-gradient(135deg, rgb(239 246 255) 0%, rgb(224 242 254) 100%);
}

.component-row:hover {
    background-color: rgb(248 250 252);
}

/* Enhanced table styling */
.min-w-full th {
    background: linear-gradient(135deg, rgb(249 250 251) 0%, rgb(243 244 246) 100%);
    font-weight: 600;
    letter-spacing: 0.05em;
}

.min-w-full td {
    border-bottom: 1px solid rgb(243 244 246);
}

/* Improved status badges */
.inline-flex.items-center.px-2\.5.py-0\.5 {
    font-weight: 500;
    letter-spacing: 0.025em;
    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
}

/* Better QR button styling */
.bg-blue-100.hover\:bg-blue-200 {
    transition: all 0.2s ease-in-out;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
}

.bg-blue-100.hover\:bg-blue-200:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}
</style>