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

// ============================================================
// AJAX HANDLERS (Must be before any HTML output)
// ============================================================

// AJAX: Load panels for a master color
if (isset($_GET['ajax']) && $_GET['ajax'] === 'load_panels' && isset($_GET['master_id'])) {
    header('Content-Type: application/json');
    
    $master_id = intval($_GET['master_id']);
    
    $panels_query = "
        SELECT 
            mcp.*,
            mc.code_color as master_code,
            mc.name_color as master_name,
            (SELECT COUNT(*) FROM color_stock_items WHERE color_id = mcp.id) as item_count,
            (SELECT COUNT(*) FROM color_stock_items WHERE color_id = mcp.id AND item_type = 'master_color') as master_item_count,
            (SELECT COUNT(*) FROM color_stock_items WHERE color_id = mcp.id AND item_type = 'copy_panel') as copy_item_count
        FROM master_color_panel mcp
        LEFT JOIN master_color mc ON mcp.master_color_id = mc.id
        WHERE mcp.master_color_id = ?
        ORDER BY mcp.panel_type DESC, mcp.code_color
    ";
    
    $stmt = $conn->prepare($panels_query);
    $stmt->bind_param("i", $master_id);
    $stmt->execute();
    $panels_result = $stmt->get_result();
    
    if ($panels_result->num_rows === 0) {
        echo json_encode([
            'success' => false,
            'message' => 'Tidak ada panel untuk master color ini'
        ]);
        exit();
    }
    
    $html = '';
    while ($panel = $panels_result->fetch_assoc()) {
        $panel_type_badge = $panel['panel_type'] === 'master_color' 
            ? '<span class="px-2 py-1 bg-blue-100 text-blue-800 text-xs font-semibold rounded-full"><i class="fas fa-crown mr-1"></i> Master Panel</span>'
            : '<span class="px-2 py-1 bg-green-100 text-green-800 text-xs font-semibold rounded-full"><i class="fas fa-copy mr-1"></i> Copy Panel</span>';
        
        $status_class = $panel['status'] == 'Hijau' ? 'bg-green-100 text-green-800' : 
                       ($panel['status'] == 'Kuning' ? 'bg-yellow-100 text-yellow-800' : 'bg-red-100 text-red-800');
        
        $html .= '
        <div class="bg-white rounded-lg shadow border-l-4 ' . ($panel['panel_type'] === 'master_color' ? 'border-blue-400' : 'border-green-400') . ' overflow-hidden">
            <div class="p-3 cursor-pointer hover:bg-gray-50 transition" onclick="togglePanel(' . $panel['id'] . ')">
                <div class="flex items-center justify-between">
                    <div class="flex items-center space-x-3">
                        <div class="flex-shrink-0">
                            <div class="w-12 h-12 rounded border-2 border-gray-200 flex items-center justify-center" style="background-color: ' . (!empty($panel['kode_warna_hex']) ? '#' . $panel['kode_warna_hex'] : '#CCCCCC') . '">
                                ' . (empty($panel['kode_warna_hex']) ? '<i class="fas fa-palette text-white"></i>' : '') . '
                            </div>
                        </div>
                        <div>
                            <div class="flex items-center space-x-2 mb-1">
                                ' . $panel_type_badge . '
                                <span class="font-bold text-gray-800">' . htmlspecialchars($panel['code_color']) . '</span>
                            </div>
                            <p class="text-sm font-medium text-gray-700">' . htmlspecialchars($panel['deskripsi']) . '</p>
                            <div class="flex items-center space-x-2 text-xs text-gray-500 mt-1">
                                <span>Lemari: ' . htmlspecialchars($panel['lemari']) . '</span>
                                <span class="px-2 py-0.5 rounded-full text-xs font-semibold ' . $status_class . '">' . htmlspecialchars($panel['status']) . '</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="flex items-center space-x-3">
                        <div class="text-right text-sm">
                            <div class="text-gray-600">
                                <i class="fas fa-box mr-1"></i>
                                <span class="font-semibold">' . $panel['item_count'] . '</span> Items
                            </div>
                            <div class="text-xs text-gray-500 mt-1">
                                <span class="text-blue-600">' . $panel['master_item_count'] . ' Master</span>
                                <span class="mx-1">•</span>
                                <span class="text-green-600">' . $panel['copy_item_count'] . ' Copy</span>
                            </div>
                        </div>
                        <i class="fas fa-chevron-down text-gray-400 transform transition-transform" id="icon-panel-' . $panel['id'] . '"></i>
                    </div>
                </div>
            </div>
            
            <div id="panel-' . $panel['id'] . '" class="hidden bg-gray-50 p-3">
                <div class="items-container" data-panel-id="' . $panel['id'] . '">
                    <div class="text-center py-4">
                        <i class="fas fa-spinner fa-spin text-gray-400"></i>
                        <p class="text-gray-500 text-xs mt-2">Loading items...</p>
                    </div>
                </div>
            </div>
        </div>';
    }
    
    echo json_encode([
        'success' => true,
        'html' => $html
    ]);
    exit();
}

// AJAX: Load copy panel items for a panel
if (isset($_GET['ajax']) && $_GET['ajax'] === 'load_items' && isset($_GET['panel_id'])) {
    header('Content-Type: application/json');
    
    $panel_id = intval($_GET['panel_id']);
    
    $items_query = "
        SELECT 
            csi.*,
            cc.component_name,
            mcp.code_color as panel_code,
            mcp.deskripsi as panel_desc
        FROM color_stock_items csi
        JOIN color_components cc ON csi.component_id = cc.id
        JOIN master_color_panel mcp ON csi.color_id = mcp.id
        WHERE csi.color_id = ?
        ORDER BY csi.item_type DESC, csi.kode_barang
    ";
    
    $stmt = $conn->prepare($items_query);
    $stmt->bind_param("i", $panel_id);
    $stmt->execute();
    $items_result = $stmt->get_result();
    
    if ($items_result->num_rows === 0) {
        echo json_encode([
            'success' => false,
            'message' => 'Tidak ada item untuk panel ini'
        ]);
        exit();
    }
    
    $html = '<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">';
    
    while ($item = $items_result->fetch_assoc()) {
        $item_type_badge = $item['item_type'] === 'master_color'
            ? '<span class="px-2 py-1 bg-blue-600 text-white text-xs font-bold rounded"><i class="fas fa-crown mr-1"></i> MASTER</span>'
            : '<span class="px-2 py-1 bg-green-600 text-white text-xs font-bold rounded"><i class="fas fa-copy mr-1"></i> COPY</span>';
        
        $status_badge_class = '';
        $status_icon = '';
        
        switch($item['status']) {
            case 'Tersedia':
                $status_badge_class = 'bg-green-100 text-green-800';
                $status_icon = 'fa-check-circle';
                break;
            case 'Dipinjam':
                $status_badge_class = 'bg-yellow-100 text-yellow-800';
                $status_icon = 'fa-hand-holding';
                break;
            case 'Rusak':
                $status_badge_class = 'bg-red-100 text-red-800';
                $status_icon = 'fa-exclamation-triangle';
                break;
            case 'Expired':
                $status_badge_class = 'bg-gray-100 text-gray-800';
                $status_icon = 'fa-clock';
                break;
            case 'Renew':
                $status_badge_class = 'bg-orange-100 text-orange-800';
                $status_icon = 'fa-sync';
                break;
            case 'Hilang':
                $status_badge_class = 'bg-purple-100 text-purple-800';
                $status_icon = 'fa-search';
                break;
            default:
                $status_badge_class = 'bg-gray-100 text-gray-800';
                $status_icon = 'fa-question-circle';
        }
        
        $can_borrow = $item['item_type'] === 'copy_panel' && $item['status'] === 'Tersedia';
        $borrow_badge = $can_borrow 
            ? '<span class="px-2 py-1 bg-green-50 text-green-700 text-xs font-medium rounded border border-green-200"><i class="fas fa-unlock mr-1"></i> Dapat Dipinjam</span>'
            : '<span class="px-2 py-1 bg-red-50 text-red-700 text-xs font-medium rounded border border-red-200"><i class="fas fa-lock mr-1"></i> Tidak Dapat Dipinjam</span>';
        
        $html .= '
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-3 hover:shadow-md transition">
            <div class="flex items-start justify-between mb-2">
                ' . $item_type_badge . '
                <span class="px-2 py-1 rounded text-xs font-semibold ' . $status_badge_class . '">
                    <i class="fas ' . $status_icon . ' mr-1"></i>' . htmlspecialchars($item['status']) . '
                </span>
            </div>
            
            <div class="mb-2">
                <p class="text-lg font-bold text-gray-800">' . htmlspecialchars($item['kode_barang']) . '</p>
                <p class="text-sm text-gray-600">' . htmlspecialchars($item['component_name']) . '</p>
            </div>
            
            <div class="space-y-1 text-xs text-gray-600 mb-2">
                <div class="flex items-center">
                    <i class="fas fa-map-marker-alt w-4"></i>
                    <span>' . htmlspecialchars($item['lokasi']) . '</span>
                </div>
                <div class="flex items-center">
                    <i class="fas fa-layer-group w-4"></i>
                    <span>Rack: ' . htmlspecialchars($item['rack_no']) . '</span>
                </div>
                <div class="flex items-center">
                    <i class="fas fa-calendar w-4"></i>
                    <span>Dibuat: ' . date('d-m-Y', strtotime($item['tanggal_pembuatan'])) . '</span>
                </div>
                ' . (!empty($item['tanggal_kedaluwarsa']) ? '
                <div class="flex items-center">
                    <i class="fas fa-hourglass-end w-4"></i>
                    <span>Exp: ' . date('d-m-Y', strtotime($item['tanggal_kedaluwarsa'])) . '</span>
                </div>' : '') . '
            </div>
            
            <div class="pt-2 border-t border-gray-100">
                ' . $borrow_badge . '
            </div>
            
            ' . (!empty($item['keterangan']) ? '
            <div class="mt-2 p-2 bg-gray-50 rounded text-xs text-gray-600">
                <i class="fas fa-info-circle mr-1"></i>' . htmlspecialchars($item['keterangan']) . '
            </div>' : '') . '
        </div>';
    }
    
    $html .= '</div>';
    
    echo json_encode([
        'success' => true,
        'html' => $html
    ]);
    exit();
}

// ============================================================
// REGULAR PAGE RENDERING (After AJAX handlers)
// ============================================================

// Log activity
log_activity($conn, $it_id, 'it', 'Master List Data', 'IT user accessed master list data page');

// Set page title
$page_title = "Master List Data Warna";

// Get filter parameters
$buyer_filter = isset($_GET['buyer_id']) ? intval($_GET['buyer_id']) : 0;
$search_filter = isset($_GET['search']) ? trim($_GET['search']) : '';

// Get all buyers for filter
$buyers_query = "SELECT id, nama_buyer FROM buyers ORDER BY nama_buyer";
$buyers_result = $conn->query($buyers_query);

// Build WHERE clause for filters
$where_clauses = [];
$params = [];
$types = '';

if ($buyer_filter > 0) {
    $where_clauses[] = "mc.buyer_id = ?";
    $params[] = $buyer_filter;
    $types .= 'i';
}

if (!empty($search_filter)) {
    $where_clauses[] = "(mc.code_color LIKE ? OR mc.name_color LIKE ?)";
    $search_param = "%{$search_filter}%";
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= 'ss';
}

$where_sql = '';
if (count($where_clauses) > 0) {
    $where_sql = 'WHERE ' . implode(' AND ', $where_clauses);
}

// Get all master colors with counts
$master_colors_query = "
    SELECT 
        mc.*,
        b.nama_buyer,
        b.kode_buyer,
        col.nama_collection,
        (SELECT COUNT(*) FROM master_color_panel WHERE master_color_id = mc.id) as panel_count,
        (SELECT COUNT(*) FROM color_stock_items WHERE master_color_id = mc.id) as item_count
    FROM master_color mc
    JOIN buyers b ON mc.buyer_id = b.id
    JOIN collections col ON mc.collection_id = col.id
    {$where_sql}
    ORDER BY mc.code_color DESC
";

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

// Calculate statistics based on current filter
$stats_where = $where_sql;
if (!empty($stats_where)) {
    // Count total panels with filter
    $panel_count_query = "
        SELECT COUNT(*) as count 
        FROM master_color_panel mcp
        JOIN master_color mc ON mcp.master_color_id = mc.id
        JOIN buyers b ON mc.buyer_id = b.id
        JOIN collections col ON mc.collection_id = col.id
        {$stats_where}
    ";
    
    if (!empty($types)) {
        $stmt_panels = $conn->prepare($panel_count_query);
        $stmt_panels->bind_param($types, ...$params);
        $stmt_panels->execute();
        $total_panels = $stmt_panels->get_result()->fetch_assoc()['count'];
    } else {
        $total_panels = $conn->query($panel_count_query)->fetch_assoc()['count'];
    }
    
    // Count total items with filter
    $item_count_query = "
        SELECT COUNT(*) as count 
        FROM color_stock_items csi
        JOIN master_color mc ON csi.master_color_id = mc.id
        JOIN buyers b ON mc.buyer_id = b.id
        JOIN collections col ON mc.collection_id = col.id
        {$stats_where}
    ";
    
    if (!empty($types)) {
        $stmt_items = $conn->prepare($item_count_query);
        $stmt_items->bind_param($types, ...$params);
        $stmt_items->execute();
        $total_items = $stmt_items->get_result()->fetch_assoc()['count'];
    } else {
        $total_items = $conn->query($item_count_query)->fetch_assoc()['count'];
    }
} else {
    // No filter, get all counts
    $total_panels = $conn->query("SELECT COUNT(*) as count FROM master_color_panel")->fetch_assoc()['count'];
    $total_items = $conn->query("SELECT COUNT(*) as count FROM color_stock_items")->fetch_assoc()['count'];
}

// Include header
include '../template_it/header.php';

// Check for notification messages
$success_message = isset($_SESSION['success_message']) ? $_SESSION['success_message'] : '';
$error_message = isset($_SESSION['error_message']) ? $_SESSION['error_message'] : '';

// Clear session messages
unset($_SESSION['success_message']);
unset($_SESSION['error_message']);
?>

<!-- Main Content Area -->
<main class="flex-1 p-6 overflow-auto bg-gradient-to-br from-blue-100 via-teal-100 to-green-100">
    
    <!-- Notification messages -->
    <?php if (!empty($success_message)): ?>
    <div id="success-alert" class="mb-4 bg-green-100 border-l-4 border-green-500 text-green-700 p-4 rounded shadow-md">
        <div class="flex">
            <div class="flex-shrink-0">
                <i class="fas fa-check-circle text-green-500"></i>
            </div>
            <div class="ml-3">
                <p class="text-sm"><?php echo $success_message; ?></p>
            </div>
            <div class="ml-auto pl-3">
                <button type="button" onclick="document.getElementById('success-alert').style.display='none'">
                    <i class="fas fa-times text-green-500"></i>
                </button>
            </div>
        </div>
    </div>
    <script>
        setTimeout(function() {
            var el = document.getElementById('success-alert');
            if(el) el.style.display = 'none';
        }, 3000);
    </script>
    <?php endif; ?>

    <?php if (!empty($error_message)): ?>
    <div id="error-alert" class="mb-4 bg-red-100 border-l-4 border-red-500 text-red-700 p-4 rounded shadow-md">
        <div class="flex">
            <div class="flex-shrink-0">
                <i class="fas fa-exclamation-circle text-red-500"></i>
            </div>
            <div class="ml-3">
                <p class="text-sm"><?php echo $error_message; ?></p>
            </div>
            <div class="ml-auto pl-3">
                <button type="button" onclick="document.getElementById('error-alert').style.display='none'">
                    <i class="fas fa-times text-red-500"></i>
                </button>
            </div>
        </div>
    </div>
    <script>
        setTimeout(function() {
            var el = document.getElementById('error-alert');
            if(el) el.style.display = 'none';
        }, 3000);
    </script>
    <?php endif; ?>

    <!-- Page Header -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <div class="flex items-center justify-between mb-4">
            <div>
                <h2 class="text-2xl font-bold text-gray-800 mb-2">
                    <i class="fas fa-database mr-2 text-blue-600"></i>
                    Master List Data Warna
                </h2>
                <p class="text-gray-600 text-sm">
                    <i class="fas fa-sitemap mr-2"></i>
                    Hierarki: <span class="font-semibold text-blue-600">Master Color</span> → 
                    <span class="font-semibold text-green-600">Master Color Panel</span> → 
                    <span class="font-semibold text-purple-600">Copy Panel Items</span>
                </p>
            </div>
            <div class="flex gap-3">
                <a href="new_data_it.php" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition shadow-md">
                    <i class="fas fa-plus mr-2"></i> Buat Data Baru
                </a>
                <a href="color_list_it.php" class="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition shadow-md">
                    <i class="fas fa-list mr-2"></i> List Biasa
                </a>
            </div>
        </div>
        
        <!-- Filter Section -->
        <form method="GET" action="" class="grid grid-cols-1 md:grid-cols-3 gap-4 mt-4 p-4 bg-gradient-to-r from-gray-50 to-blue-50 rounded-lg border border-gray-200">
            <div>
                <label for="buyer_id" class="block text-sm font-medium text-gray-700 mb-1">
                    <i class="fas fa-user mr-1"></i> Buyer
                </label>
                <select id="buyer_id" name="buyer_id" class="w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm">
                    <option value="">-- Semua Buyer --</option>
                    <?php 
                    $buyers_result->data_seek(0);
                    while ($buyer = $buyers_result->fetch_assoc()): 
                    ?>
                        <option value="<?php echo $buyer['id']; ?>" <?php echo $buyer_filter == $buyer['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($buyer['nama_buyer']); ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>
            
            <div>
                <label for="search" class="block text-sm font-medium text-gray-700 mb-1">
                    <i class="fas fa-search mr-1"></i> Cari
                </label>
                <input type="text" id="search" name="search" value="<?php echo htmlspecialchars($search_filter); ?>" placeholder="Code / Nama Warna" class="w-full py-2 px-3 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm">
            </div>
            
            <div class="flex items-end gap-2">
                <button type="submit" class="flex-1 py-2 px-4 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition shadow-md font-medium">
                    <i class="fas fa-filter mr-2"></i> Filter
                </button>
                <a href="master_list_data.php" class="py-2 px-4 bg-gray-500 text-white rounded-md hover:bg-gray-600 transition shadow-md">
                    <i class="fas fa-redo"></i>
                </a>
            </div>
        </form>
    </div>

    <!-- Statistics Summary -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
        <div class="bg-white rounded-lg shadow-md p-4 border-l-4 border-blue-500">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm font-medium">Total Master Colors</p>
                    <p class="text-3xl font-bold text-blue-600"><?php echo $master_colors_result->num_rows; ?></p>
                    <?php if ($buyer_filter > 0 || !empty($search_filter)): ?>
                        <p class="text-xs text-gray-500 mt-1">
                            <i class="fas fa-filter mr-1"></i>Hasil Filter
                        </p>
                    <?php endif; ?>
                </div>
                <div class="bg-blue-100 p-3 rounded-full">
                    <i class="fas fa-crown text-blue-600 text-2xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-md p-4 border-l-4 border-green-500">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm font-medium">Total Panels</p>
                    <p class="text-3xl font-bold text-green-600"><?php echo $total_panels; ?></p>
                    <?php if ($buyer_filter > 0 || !empty($search_filter)): ?>
                        <p class="text-xs text-gray-500 mt-1">
                            <i class="fas fa-filter mr-1"></i>Hasil Filter
                        </p>
                    <?php endif; ?>
                </div>
                <div class="bg-green-100 p-3 rounded-full">
                    <i class="fas fa-layer-group text-green-600 text-2xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-md p-4 border-l-4 border-purple-500">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm font-medium">Total Items</p>
                    <p class="text-3xl font-bold text-purple-600"><?php echo $total_items; ?></p>
                    <?php if ($buyer_filter > 0 || !empty($search_filter)): ?>
                        <p class="text-xs text-gray-500 mt-1">
                            <i class="fas fa-filter mr-1"></i>Hasil Filter
                        </p>
                    <?php endif; ?>
                </div>
                <div class="bg-purple-100 p-3 rounded-full">
                    <i class="fas fa-boxes text-purple-600 text-2xl"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Active Filter Info -->
    <?php if ($buyer_filter > 0 || !empty($search_filter)): ?>
    <div class="bg-blue-50 border-l-4 border-blue-500 p-4 mb-6 rounded-lg shadow-sm">
        <div class="flex items-center justify-between">
            <div class="flex items-center">
                <i class="fas fa-info-circle text-blue-600 text-xl mr-3"></i>
                <div>
                    <p class="text-sm font-semibold text-blue-800">Filter Aktif:</p>
                    <div class="flex flex-wrap gap-2 mt-1">
                        <?php if ($buyer_filter > 0): 
                            $buyer_name_query = $conn->prepare("SELECT nama_buyer FROM buyers WHERE id = ?");
                            $buyer_name_query->bind_param("i", $buyer_filter);
                            $buyer_name_query->execute();
                            $buyer_name = $buyer_name_query->get_result()->fetch_assoc()['nama_buyer'];
                        ?>
                            <span class="px-3 py-1 bg-blue-600 text-white text-xs font-medium rounded-full">
                                <i class="fas fa-user mr-1"></i><?php echo htmlspecialchars($buyer_name); ?>
                            </span>
                        <?php endif; ?>
                        
                        <?php if (!empty($search_filter)): ?>
                            <span class="px-3 py-1 bg-purple-600 text-white text-xs font-medium rounded-full">
                                <i class="fas fa-search mr-1"></i>"<?php echo htmlspecialchars($search_filter); ?>"
                            </span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <a href="master_list_data.php" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition text-sm font-medium">
                <i class="fas fa-times mr-2"></i>Hapus Filter
            </a>
        </div>
    </div>
    <?php endif; ?>

    <!-- Master Colors List -->
    <div class="space-y-4">
        <?php if ($master_colors_result->num_rows > 0): ?>
            <?php while ($master_color = $master_colors_result->fetch_assoc()): ?>
                <div class="bg-white rounded-lg shadow-md overflow-hidden border-l-4 border-blue-500 hover:shadow-lg transition">
                    <!-- Master Color Card Header -->
                    <div class="p-4 bg-gradient-to-r from-blue-50 to-indigo-50 cursor-pointer hover:from-blue-100 hover:to-indigo-100 transition" onclick="toggleMasterColor(<?php echo $master_color['id']; ?>)">
                        <div class="flex items-center justify-between">
                            <div class="flex items-center space-x-4">
                                <div class="flex-shrink-0">
                                    <div class="w-16 h-16 rounded-lg border-4 border-white shadow-lg flex items-center justify-center" style="background: linear-gradient(135deg, <?php echo !empty($master_color['kode_warna_hex']) ? '#' . $master_color['kode_warna_hex'] : '#CCCCCC'; ?> 0%, <?php echo !empty($master_color['kode_warna_hex']) ? '#' . $master_color['kode_warna_hex'] . 'CC' : '#999999'; ?> 100%);">
                                        <?php if (empty($master_color['kode_warna_hex'])): ?>
                                            <i class="fas fa-palette text-white text-2xl"></i>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div>
                                    <div class="flex items-center space-x-2 mb-1">
                                        <span class="px-3 py-1 bg-gradient-to-r from-blue-600 to-blue-700 text-white text-xs font-bold rounded-full shadow-md">
                                            <i class="fas fa-crown mr-1"></i> MASTER COLOR
                                        </span>
                                        <span class="text-2xl font-bold text-gray-800"><?php echo htmlspecialchars($master_color['code_color']); ?></span>
                                    </div>
                                    <h3 class="text-lg font-bold text-gray-800"><?php echo htmlspecialchars($master_color['name_color']); ?></h3>
                                    <div class="flex items-center space-x-4 text-sm text-gray-600 mt-2">
                                        <span>
                                            <i class="fas fa-user text-blue-500 mr-1"></i> 
                                            <?php echo htmlspecialchars($master_color['nama_buyer']); ?>
                                        </span>
                                        <span>
                                            <i class="fas fa-folder text-green-500 mr-1"></i> 
                                            <?php echo htmlspecialchars($master_color['nama_collection']); ?>
                                        </span>
                                        <span>
                                            <i class="fas fa-archive text-purple-500 mr-1"></i> 
                                            Lemari: <strong><?php echo htmlspecialchars($master_color['lemari']); ?></strong>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="flex items-center space-x-4">
                                <div class="text-right">
                                    <div class="flex items-center space-x-2 mb-2">
                                        <span class="px-3 py-1 rounded-full text-xs font-bold shadow-sm <?php 
                                            echo $master_color['status'] == 'Hijau' ? 'bg-green-100 text-green-800' : 
                                                ($master_color['status'] == 'Kuning' ? 'bg-yellow-100 text-yellow-800' : 
                                                'bg-red-100 text-red-800'); 
                                        ?>">
                                            <i class="fas fa-circle mr-1"></i>
                                            <?php echo htmlspecialchars($master_color['status']); ?>
                                        </span>
                                    </div>
                                    <div class="space-y-1">
                                        <div class="text-sm text-gray-600">
                                            <i class="fas fa-layer-group text-green-500 mr-1"></i>
                                            <span class="font-bold text-green-600"><?php echo $master_color['panel_count']; ?></span> Panels
                                        </div>
                                        <div class="text-sm text-gray-600">
                                            <i class="fas fa-boxes text-purple-500 mr-1"></i>
                                            <span class="font-bold text-purple-600"><?php echo $master_color['item_count']; ?></span> Items
                                        </div>
                                    </div>
                                </div>
                                <i class="fas fa-chevron-down text-gray-400 transform transition-transform duration-300" id="icon-master-<?php echo $master_color['id']; ?>"></i>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Master Color Panels Container -->
                    <div id="master-<?php echo $master_color['id']; ?>" class="hidden bg-gradient-to-b from-gray-50 to-gray-100 p-4 border-t-2 border-blue-200">
                        <div class="flex items-center justify-between mb-4 pb-2 border-b border-gray-300">
                            <h4 class="text-sm font-bold text-gray-700 uppercase flex items-center">
                                <i class="fas fa-layer-group mr-2 text-green-600"></i> 
                                Master Color Panels
                            </h4>
                            <span class="text-xs text-gray-500 bg-white px-3 py-1 rounded-full shadow-sm">
                                Total: <span class="font-bold text-green-600"><?php echo $master_color['panel_count']; ?></span> panels
                            </span>
                        </div>
                        
                        <div class="panels-container space-y-3" data-master-id="<?php echo $master_color['id']; ?>">
                            <!-- Panels will be loaded here via AJAX -->
                            <div class="text-center py-8 bg-white rounded-lg shadow-sm">
                                <i class="fas fa-spinner fa-spin text-gray-400 text-3xl mb-2"></i>
                                <p class="text-gray-500 text-sm">Loading panels...</p>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endwhile; ?>
        <?php else: ?>
            <div class="bg-white rounded-lg shadow-md p-12 text-center">
                <div class="max-w-md mx-auto">
                    <i class="fas fa-inbox text-gray-300 text-8xl mb-4"></i>
                    <h3 class="text-2xl font-bold text-gray-600 mb-2">Tidak Ada Data</h3>
                    <p class="text-gray-500 mb-6">
                        <?php if ($buyer_filter > 0 || !empty($search_filter)): ?>
                            Tidak ada master color yang ditemukan dengan filter yang dipilih. Silakan coba kombinasi filter yang berbeda.
                        <?php else: ?>
                            Belum ada master color yang terdaftar dalam sistem.
                        <?php endif; ?>
                    </p>
                    <div class="flex justify-center gap-3">
                        <?php if ($buyer_filter > 0 || !empty($search_filter)): ?>
                            <a href="master_list_data.php" class="inline-block px-6 py-3 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition shadow-md">
                                <i class="fas fa-redo mr-2"></i> Reset Filter
                            </a>
                        <?php endif; ?>
                        <a href="new_data_it.php" class="inline-block px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition shadow-md">
                            <i class="fas fa-plus mr-2"></i> Buat Data Baru
                        </a>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</main>

<script>
// ============================================================
// JAVASCRIPT FUNCTIONS
// ============================================================

// Toggle master color accordion
function toggleMasterColor(masterId) {
    const content = document.getElementById('master-' + masterId);
    const icon = document.getElementById('icon-master-' + masterId);
    const panelsContainer = content.querySelector('.panels-container');
    
    if (content.classList.contains('hidden')) {
        // Close all other accordions
        document.querySelectorAll('[id^="master-"]').forEach(el => {
            if (el.id !== 'master-' + masterId) {
                el.classList.add('hidden');
                const otherId = el.id.replace('master-', '');
                const otherIcon = document.getElementById('icon-master-' + otherId);
                if (otherIcon) {
                    otherIcon.classList.remove('rotate-180');
                }
            }
        });
        
        content.classList.remove('hidden');
        icon.classList.add('rotate-180');
        
        // Load panels if not loaded yet
        if (panelsContainer.dataset.loaded !== 'true') {
            loadPanels(masterId);
        }
    } else {
        content.classList.add('hidden');
        icon.classList.remove('rotate-180');
    }
}

// Load panels via AJAX
function loadPanels(masterId) {
    const container = document.querySelector(`.panels-container[data-master-id="${masterId}"]`);
    
    fetch(`master_list_data.php?ajax=load_panels&master_id=${masterId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                container.innerHTML = data.html;
                container.dataset.loaded = 'true';
            } else {
                container.innerHTML = `
                    <div class="text-center py-8 bg-white rounded-lg shadow-sm">
                        <i class="fas fa-exclamation-circle text-yellow-400 text-3xl mb-2"></i>
                        <p class="text-yellow-600 text-sm">${data.message}</p>
                    </div>
                `;
            }
        })
        .catch(error => {
            console.error('Error loading panels:', error);
            container.innerHTML = `
                <div class="text-center py-8 bg-white rounded-lg shadow-sm">
                    <i class="fas fa-times-circle text-red-400 text-3xl mb-2"></i>
                    <p class="text-red-500 text-sm">Terjadi kesalahan saat memuat data panel</p>
                </div>
            `;
        });
}

// Toggle panel accordion
function togglePanel(panelId) {
    const content = document.getElementById('panel-' + panelId);
    const icon = document.getElementById('icon-panel-' + panelId);
    const itemsContainer = content.querySelector('.items-container');
    
    if (content.classList.contains('hidden')) {
        content.classList.remove('hidden');
        icon.classList.add('rotate-180');
        
        // Load items if not loaded yet
        if (itemsContainer.dataset.loaded !== 'true') {
            loadCopyPanels(panelId);
        }
    } else {
        content.classList.add('hidden');
        icon.classList.remove('rotate-180');
    }
}

// Load copy panel items via AJAX
function loadCopyPanels(panelId) {
    const container = document.querySelector(`.items-container[data-panel-id="${panelId}"]`);
    
    fetch(`master_list_data.php?ajax=load_items&panel_id=${panelId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                container.innerHTML = data.html;
                container.dataset.loaded = 'true';
            } else {
                container.innerHTML = `
                    <div class="text-center py-6 bg-white rounded shadow-sm">
                        <i class="fas fa-info-circle text-blue-400 text-2xl mb-2"></i>
                        <p class="text-blue-600 text-sm">${data.message}</p>
                    </div>
                `;
            }
        })
        .catch(error => {
            console.error('Error loading copy panels:', error);
            container.innerHTML = `
                <div class="text-center py-6 bg-white rounded shadow-sm">
                    <i class="fas fa-times-circle text-red-400 text-2xl mb-2"></i>
                    <p class="text-red-500 text-sm">Terjadi kesalahan saat memuat data items</p>
                </div>
            `;
        });
}
</script>

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