<!-- add_component_it.php -->
<?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 = "Penambahan Component & Code Barang";

// Log activity
log_activity($conn, $it_id, 'it', 'Add Component Form', 'IT user accessed add component form');

// Get all color panels
$colors_query = "SELECT c.id, c.code_color, c.deskripsi, c.lemari, c.status, c.kode_warna_hex, c.panel_type,
                b.nama_buyer, b.id as buyer_id, col.nama_collection, mc.code_color as master_code
            FROM master_color_panel c
            JOIN buyers b ON c.buyer_id = b.id
            JOIN collections col ON c.collection_id = col.id
            LEFT JOIN master_color mc ON c.master_color_id = mc.id
            ORDER BY b.nama_buyer, c.code_color";
$colors_result = $conn->query($colors_query);

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

// Get all components
$components_query = "SELECT id, component_name, description FROM color_components ORDER BY component_name";
$components_result = $conn->query($components_query);

// 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() {
            document.getElementById('success-alert').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() {
            document.getElementById('error-alert').style.display = 'none';
        }, 3000);
    </script>
    <?php endif; ?>

    <!-- Page Header -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h2 class="text-2xl font-bold text-gray-800 mb-4">Manajemen Data Warna</h2>
        <p class="text-gray-600 mb-4">
            Halaman ini digunakan untuk mengelola data warna dalam sistem.
        </p>
        
        <div class="flex flex-wrap gap-3">
            <a href="new_data_it.php" class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition">
                <i class="fas fa-plus mr-2"></i> Pembuatan Data Baru
            </a>
            <a href="add_component_it.php" class="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700 transition">
                <i class="fas fa-puzzle-piece mr-2"></i> Penambahan Component & Code Barang
            </a>
            <a href="color_list_it.php" class="px-4 py-2 bg-purple-600 text-white rounded hover:bg-purple-700 transition">
                <i class="fas fa-list mr-2"></i> Data Warna Yang Ada
            </a>
        </div>
    </div>
    
    <!-- Color Selection Form -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h3 class="text-xl font-semibold text-gray-800 mb-4">Tambah Component Pada Warna Yang Ada</h3>
        
        <!-- Buyer Filter -->
        <div class="mb-4">
            <label for="buyer_filter" class="block text-sm font-medium text-gray-700 mb-1">Filter Berdasarkan Pembeli:</label>
            <select id="buyer_filter" class="mt-1 block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                <option value="">-- Semua Pembeli --</option>
                <?php while ($buyer = $buyers_result->fetch_assoc()): ?>
                    <option value="<?php echo $buyer['id']; ?>"><?php echo htmlspecialchars($buyer['nama_buyer']); ?></option>
                <?php endwhile; ?>
            </select>
        </div>
        
        <!-- Color Selection -->
        <form id="colorSelectionForm" action="process_add_component.php" method="POST" class="space-y-6">
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <?php 
                if ($colors_result->num_rows > 0) {
                    $current_buyer = "";
                    while ($color = $colors_result->fetch_assoc()): 
                        $status_class = '';
                        if ($color['status'] == 'Hijau') {
                            $status_class = 'bg-green-100 text-green-800 border-green-200';
                        } else if ($color['status'] == 'Kuning') {
                            $status_class = 'bg-yellow-100 text-yellow-800 border-yellow-200';
                        } else if ($color['status'] == 'Merah') {
                            $status_class = 'bg-red-100 text-red-800 border-red-200';
                        }
                        
                        // Add badge for panel type
                        $panel_badge = '';
                        if ($color['panel_type'] == 'master_color') {
                            $panel_badge = '<span class="inline-block px-2 py-1 text-xs font-semibold text-blue-800 bg-blue-200 rounded-full">Master</span>';
                        } else {
                            $panel_badge = '<span class="inline-block px-2 py-1 text-xs font-semibold text-green-800 bg-green-200 rounded-full">Copy</span>';
                        }
                ?>
                <div class="color-card border rounded-lg p-4 shadow-sm hover:shadow-md transition-shadow <?php echo $status_class; ?>" data-buyer-id="<?php echo $color['buyer_id']; ?>">
                    <div class="flex items-center justify-between mb-2">
                        <div>
                            <h4 class="font-semibold"><?php echo htmlspecialchars($color['code_color']); ?></h4>
                            <?php if (!empty($color['master_code'])): ?>
                            <p class="text-xs text-gray-600">Master: <?php echo htmlspecialchars($color['master_code']); ?></p>
                            <?php endif; ?>
                        </div>
                        <div class="flex items-center space-x-2">
                            <?php echo $panel_badge; ?>
                            <?php if (!empty($color['kode_warna_hex'])): ?>
                            <div class="w-6 h-6 rounded border border-gray-300" style="background-color: #<?php echo htmlspecialchars($color['kode_warna_hex']); ?>"></div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <p class="text-sm mb-2"><?php echo htmlspecialchars($color['deskripsi']); ?></p>
                    <p class="text-xs mb-2">Pembeli: <?php echo htmlspecialchars($color['nama_buyer']); ?></p>
                    <p class="text-xs mb-1">Koleksi: <?php echo htmlspecialchars($color['nama_collection']); ?></p>
                    <div class="mt-3 flex justify-between items-center">
                        <span class="text-xs">Lemari: <?php echo htmlspecialchars($color['lemari']); ?></span>
                        <button type="button" class="select-color-btn bg-blue-500 hover:bg-blue-600 text-white text-xs py-1 px-2 rounded" 
                                data-color-id="<?php echo $color['id']; ?>" 
                                data-color-code="<?php echo htmlspecialchars($color['code_color']); ?>"
                                data-color-desc="<?php echo htmlspecialchars($color['deskripsi']); ?>"
                                data-buyer-name="<?php echo htmlspecialchars($color['nama_buyer']); ?>"
                                data-lemari="<?php echo htmlspecialchars($color['lemari']); ?>"
                                data-panel-type="<?php echo htmlspecialchars($color['panel_type']); ?>"
                                data-master-color-id="<?php echo $color['master_color_id'] ?? ''; ?>">
                            Pilih
                        </button>
                    </div>
                </div>
                <?php 
                    endwhile;
                } else {
                    echo '<div class="col-span-3 text-center text-gray-500 py-6">Tidak ada data warna</div>';
                }
                ?>
            </div>
        </form>
    </div>
    
    <!-- Component Form (Initially Hidden) -->
    <div id="componentForm" class="bg-white rounded-lg shadow-md p-6 mb-6 hidden">
        <h3 class="text-xl font-semibold text-gray-800 mb-4">Tambah Component</h3>
        <div id="colorInfo" class="mb-4 p-3 bg-gray-100 rounded-md">
            <p>Warna: <span id="selectedColorCode" class="font-semibold"></span> - <span id="selectedColorDesc"></span></p>
            <p>Pembeli: <span id="selectedBuyerName"></span></p>
            <p>Lemari: <span id="selectedLemari"></span></p>
            <p>Tipe: <span id="selectedPanelType" class="font-semibold"></span></p>
        </div>
        
        <form id="addComponentForm" action="process_add_component.php" method="POST" class="space-y-6">
            <input type="hidden" id="color_id" name="color_id">
            <input type="hidden" id="panel_type" name="panel_type">
            <input type="hidden" id="master_color_id" name="master_color_id">
            
            <div id="component-container" class="space-y-4">
                <div class="component-row grid grid-cols-1 md:grid-cols-4 gap-4 p-4 border border-gray-200 rounded-md">
                    <!-- Component Selection -->
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-1">Komponen</label>
                        <div class="flex space-x-2">
                            <select name="components[]" class="component-select flex-1 mt-1 block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" required>
                                <option value="">-- Pilih Komponen --</option>
                                <?php 
                                $components_result->data_seek(0);
                                while ($component = $components_result->fetch_assoc()): 
                                ?>
                                    <option value="<?php echo $component['id']; ?>"><?php echo htmlspecialchars($component['component_name']); ?></option>
                                <?php endwhile; ?>
                                <option value="new">+ Tambah Komponen Baru</option>
                            </select>
                            <button type="button" class="delete-component mt-1 py-2 px-3 border border-gray-300 bg-red-100 text-red-600 rounded-md hover:bg-red-200 focus:outline-none focus:ring-red-500 focus:border-red-500 sm:text-sm">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                        <div class="new-component-input hidden mt-2">
                            <input type="text" name="new_components[]" placeholder="Nama komponen baru" class="block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                            <textarea name="new_component_descriptions[]" placeholder="Deskripsi komponen" class="mt-2 block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"></textarea>
                        </div>
                    </div>
                    
                    <!-- Quantity -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Jumlah</label>
                        <input type="number" name="quantities[]" class="quantity-input mt-1 block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" min="1" value="1" required>
                    </div>
                    
                    <!-- Available Quantity -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Jumlah Tersedia</label>
                        <input type="number" name="available_quantities[]" class="available-quantity-input mt-1 block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" min="0" value="1" required>
                    </div>
                </div>
            </div>
            
            <div class="flex justify-center">
                <button type="button" id="add-component" class="py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                    <i class="fas fa-plus mr-2"></i> Tambah Komponen
                </button>
            </div>
            
            <hr class="my-6 border-gray-200" />
            
            <div class="flex justify-end space-x-3">
                <button type="button" id="cancelBtn" class="py-2 px-4 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                    <i class="fas fa-times mr-2"></i> Batal
                </button>
                <button type="reset" class="py-2 px-4 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                    <i class="fas fa-redo mr-2"></i> Reset
                </button>
                <button type="submit" class="py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500">
                    <i class="fas fa-save mr-2"></i> Simpan
                </button>
            </div>
        </form>
    </div>
</main>

<script>
// Filter colors based on selected buyer
document.getElementById('buyer_filter').addEventListener('change', function() {
    const buyerId = this.value;
    const colorCards = document.querySelectorAll('.color-card');
    
    colorCards.forEach(function(card) {
        if (!buyerId || card.dataset.buyerId === buyerId) {
            card.style.display = 'block';
        } else {
            card.style.display = 'none';
        }
    });
});

// Function to sync quantity with available quantity
function syncQuantities(quantityInput) {
    const row = quantityInput.closest('.component-row');
    const availableQuantityInput = row.querySelector('.available-quantity-input');
    availableQuantityInput.value = quantityInput.value;
}

// Add event listeners to all existing quantity inputs
function addQuantityListeners() {
    document.querySelectorAll('.quantity-input').forEach(function(input) {
        input.addEventListener('input', function() {
            syncQuantities(this);
        });
    });
}

// Initialize quantity listeners
addQuantityListeners();

// Handle component select change
function handleComponentSelectChange(select) {
    const row = select.closest('.component-row');
    const newComponentInput = row.querySelector('.new-component-input');
    
    if (select.value === 'new') {
        // Show input fields for new component
        newComponentInput.classList.remove('hidden');
        // Make the input and textarea required
        newComponentInput.querySelector('input').required = true;
    } else {
        // Hide input fields for new component
        newComponentInput.classList.add('hidden');
        // Remove the required attribute
        const inputEl = newComponentInput.querySelector('input');
        if (inputEl) inputEl.required = false;
    }
}

// Add event listeners to all existing component selects
document.querySelectorAll('.component-select').forEach(function(select) {
    select.addEventListener('change', function() {
        handleComponentSelectChange(this);
    });
});

// Function to update delete buttons visibility
function updateDeleteButtons() {
    const deleteButtons = document.querySelectorAll('.delete-component');
    if (deleteButtons.length <= 1) {
        deleteButtons.forEach(function(btn) {
            btn.style.visibility = 'hidden';
        });
    } else {
        deleteButtons.forEach(function(btn) {
            btn.style.visibility = 'visible';
        });
    }
}

// Initialize delete buttons visibility
updateDeleteButtons();

// Add event listener to add component button
document.getElementById('add-component').addEventListener('click', function() {
    const container = document.getElementById('component-container');
    const componentRowTemplate = container.querySelector('.component-row').cloneNode(true);
    
    // Reset values in the cloned template
    componentRowTemplate.querySelector('select[name="components[]"]').value = '';
    const quantityInput = componentRowTemplate.querySelector('input[name="quantities[]"]');
    quantityInput.value = 1;
    componentRowTemplate.querySelector('input[name="available_quantities[]"]').value = 1;
    
    // Hide new component input in the cloned template
    const newComponentInput = componentRowTemplate.querySelector('.new-component-input');
    newComponentInput.classList.add('hidden');
    
    // Remove required attribute from new component inputs
    const inputEl = newComponentInput.querySelector('input');
    if (inputEl) inputEl.required = false;
    
    // Add event listener to component select
    const select = componentRowTemplate.querySelector('.component-select');
    select.addEventListener('change', function() {
        handleComponentSelectChange(this);
    });
    
    // Add event listener to quantity input
    quantityInput.addEventListener('input', function() {
        syncQuantities(this);
    });
    
    // Add event listener to delete button
    const deleteButton = componentRowTemplate.querySelector('.delete-component');
    deleteButton.addEventListener('click', function() {
        this.closest('.component-row').remove();
        updateDeleteButtons();
    });
    
    // Append the cloned template to the container
    container.appendChild(componentRowTemplate);
    
    // Update delete buttons visibility
    updateDeleteButtons();
});

// Add event listener to existing delete buttons
document.querySelectorAll('.delete-component').forEach(function(button) {
    button.addEventListener('click', function() {
        this.closest('.component-row').remove();
        updateDeleteButtons();
    });
});

// Show component form when a color is selected
document.querySelectorAll('.select-color-btn').forEach(function(button) {
    button.addEventListener('click', function() {
        const colorId = this.dataset.colorId;
        const colorCode = this.dataset.colorCode;
        const colorDesc = this.dataset.colorDesc;
        const buyerName = this.dataset.buyerName;
        const lemari = this.dataset.lemari;
        const panelType = this.dataset.panelType;
        const masterColorId = this.dataset.masterColorId;
        
        document.getElementById('color_id').value = colorId;
        document.getElementById('panel_type').value = panelType;
        document.getElementById('master_color_id').value = masterColorId;
        document.getElementById('selectedColorCode').textContent = colorCode;
        document.getElementById('selectedColorDesc').textContent = colorDesc;
        document.getElementById('selectedBuyerName').textContent = buyerName;
        document.getElementById('selectedLemari').textContent = lemari;
        
        // Display panel type with badge
        const panelTypeSpan = document.getElementById('selectedPanelType');
        if (panelType === 'master_color') {
            panelTypeSpan.innerHTML = '<span class="px-2 py-1 text-xs font-semibold text-blue-800 bg-blue-200 rounded-full">Master Color</span>';
        } else {
            panelTypeSpan.innerHTML = '<span class="px-2 py-1 text-xs font-semibold text-green-800 bg-green-200 rounded-full">Copy Panel</span>';
        }
        
        document.getElementById('componentForm').classList.remove('hidden');
        document.getElementById('componentForm').scrollIntoView({ behavior: 'smooth' });
    });
});

// Hide component form when cancel button is clicked
document.getElementById('cancelBtn').addEventListener('click', function() {
    document.getElementById('componentForm').classList.add('hidden');
});

// Form validation
document.getElementById('addComponentForm').addEventListener('submit', function(event) {
    // Validate unique component selections
    const selects = document.querySelectorAll('select[name="components[]"]');
    const selectedComponents = [];
    
    for (let i = 0; i < selects.length; i++) {
        const select = selects[i];
        
        // Skip validation for 'new' option
        if (select.value === 'new') continue;
        
        // Check if component is already selected
        if (select.value && selectedComponents.includes(select.value)) {
            alert('Komponen tidak boleh duplikat. Pilih komponen yang berbeda untuk setiap baris.');
            event.preventDefault();
            return;
        }
        
        if (select.value) {
            selectedComponents.push(select.value);
        }
    }
});
</script>

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