<?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 = "Tambah Data Warna Baru";

// Log activity
log_activity($conn, $it_id, 'it', 'New Color Data Form', 'IT user accessed new color data form');

// Handle AJAX request for checking duplicate color code
if (isset($_GET['check_color_code']) && !empty($_GET['check_color_code'])) {
    header('Content-Type: application/json');
    
    $color_code = trim($_GET['check_color_code']);
    $check_query = "SELECT COUNT(*) as count FROM master_color_panel_semarang WHERE code_color = ?";
    $check_stmt = $conn->prepare($check_query);
    $check_stmt->bind_param("s", $color_code);
    $check_stmt->execute();
    $result = $check_stmt->get_result();
    $count = $result->fetch_assoc()['count'];
    
    echo json_encode(['exists' => $count > 0]);
    exit();
}

// Get all buyers_semarang
$buyers_semarang_query = "SELECT id, nama_buyer FROM buyers_semarang ORDER BY nama_buyer";
$buyers_semarang_result = $conn->query($buyers_semarang_query);

// Get all collection_semarangs
$collection_semarangs_query = "SELECT id, nama_collection_semarang, buyer_id FROM collection_semarangs ORDER BY nama_collection_semarang";
$collection_semarangs_result = $conn->query($collection_semarangs_query);

// Store collection_semarangs in an array for later use with JavaScript
$collection_semarangs = [];
while ($collection_semarang = $collection_semarangs_result->fetch_assoc()) {
    $collection_semarangs[] = $collection_semarang;
}
$collection_semarangs_result->data_seek(0); // Reset pointer

// Get all components
$components_query = "SELECT id, component_name, description FROM color_components_semarang 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>
    
    <!-- New Color Form -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <form id="colorForm" action="process_new_data.php" method="POST" class="space-y-6">
            <h3 class="text-xl font-semibold text-gray-800 mb-4">Data Warna</h3>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Buyer Selection -->
                <div>
                    <label for="buyer_id" class="block text-sm font-medium text-gray-700 mb-1">Pembeli</label>
                    <select id="buyer_id" name="buyer_id" 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" required>
                        <option value="">-- Pilih Pembeli --</option>
                        <?php while ($buyer = $buyers_semarang_result->fetch_assoc()): ?>
                            <option value="<?php echo $buyer['id']; ?>"><?php echo htmlspecialchars($buyer['nama_buyer']); ?></option>
                        <?php endwhile; ?>
                    </select>
                </div>
                
                <!-- collection_semarang Selection -->
                <div>
                    <label for="collection_semarang_id" class="block text-sm font-medium text-gray-700 mb-1">Koleksi</label>
                    <select id="collection_semarang_id" name="collection_semarang_id" 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" required disabled>
                        <option value="">-- Pilih Koleksi --</option>
                    </select>
                </div>
                
                <!-- Color Code -->
                <div>
                    <label for="code_color" class="block text-sm font-medium text-gray-700 mb-1">Kode Warna</label>
                    <div class="relative">
                        <input type="text" id="code_color" name="code_color" 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" required>
                        <div id="color-code-status" class="hidden absolute right-2 top-1/2 transform -translate-y-1/2">
                            <i class="fas fa-spinner fa-spin text-gray-400" id="color-code-loading"></i>
                            <i class="fas fa-check text-green-500 hidden" id="color-code-available"></i>
                            <i class="fas fa-times text-red-500 hidden" id="color-code-exists"></i>
                        </div>
                    </div>
                    <div id="color-code-message" class="mt-1 text-sm hidden">
                        <p id="color-code-error" class="text-red-600 hidden">
                            <i class="fas fa-exclamation-triangle mr-1"></i>
                            Kode warna ini sudah ada di dalam database
                        </p>
                        <p id="color-code-success" class="text-green-600 hidden">
                            <i class="fas fa-check mr-1"></i>
                            Kode warna tersedia
                        </p>
                    </div>
                </div>
                
                <!-- Color Description -->
                <div>
                    <label for="deskripsi" class="block text-sm font-medium text-gray-700 mb-1">Deskripsi Warna</label>
                    <input type="text" id="deskripsi" name="deskripsi" 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" required>
                </div>
                
                <!-- Cabinet -->
                <div>
                    <label for="lemari" class="block text-sm font-medium text-gray-700 mb-1">Lemari</label>
                    <input type="text" id="lemari" name="lemari" maxlength="1" 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" required>
                    <p class="text-xs text-gray-500 mt-1">Masukkan 1 huruf abjad (A-Z)</p>
                </div>
                
                <!-- Color Status -->
                <div>
                    <label for="status" class="block text-sm font-medium text-gray-700 mb-1">Status Warna</label>
                    <select id="status" name="status" 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" required>
                        <option value="Hijau">Hijau</option>
                        <option value="Kuning">Kuning</option>
                        <option value="Merah">Merah</option>
                    </select>
                </div>
                
                <!-- Color Hex Code -->
                <div>
                    <label for="kode_warna_hex" class="block text-sm font-medium text-gray-700 mb-1">Kode Warna Hex</label>
                    <div class="flex">
                        <span class="inline-flex items-center px-3 rounded-l-md border border-r-0 border-gray-300 bg-gray-50 text-gray-500 sm:text-sm">
                            #
                        </span>
                        <input type="text" id="kode_warna_hex" name="kode_warna_hex" pattern="[0-9A-Fa-f]{6}" class="flex-1 min-w-0 block w-full px-3 py-2 rounded-none rounded-r-md border border-gray-300 focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" placeholder="e.g. 8B4513">
                    </div>
                    <p class="text-xs text-gray-500 mt-1">Format: 6 karakter hex (misalnya: 8B4513)</p>
                </div>
                
                <!-- Color Notes -->
                <div class="md:col-span-2">
                    <label for="keterangan_warna" class="block text-sm font-medium text-gray-700 mb-1">Keterangan Warna</label>
                    <textarea id="keterangan_warna" name="keterangan_warna" rows="2" 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"></textarea>
                </div>
            </div>
            
            <hr class="my-6 border-gray-200" />
            
            <h3 class="text-xl font-semibold text-gray-800 mb-4">Komponen Warna</h3>
            
            <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); ?>
                                <?php 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[]" min="1" value="1" 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" 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[]" min="0" value="1" 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" 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">
                <a href="dashboard_it.php" 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-arrow-left mr-2"></i> Kembali
                </a>
                <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" id="submit-btn" 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>
// Store collection_semarangs data
var collection_semarangs = <?php echo json_encode($collection_semarangs); ?>;

// Variables for color code checking
let colorCodeCheckTimeout;
let isColorCodeValid = false;

// Function to filter collection_semarangs based on selected buyer
function updatecollection_semarangs() {
    var buyerId = document.getElementById('buyer_id').value;
    var collection_semarangSelect = document.getElementById('collection_semarang_id');
    
    // Clear existing options
    collection_semarangSelect.innerHTML = '<option value="">-- Pilih Koleksi --</option>';
    
    if (buyerId) {
        // Enable the collection_semarang select
        collection_semarangSelect.disabled = false;
        
        // Filter collection_semarangs for selected buyer
        var filteredcollection_semarangs = collection_semarangs.filter(function(collection_semarang) {
            return collection_semarang.buyer_id == buyerId;
        });
        
        // Add filtered collection_semarangs to select
        filteredcollection_semarangs.forEach(function(collection_semarang) {
            var option = document.createElement('option');
            option.value = collection_semarang.id;
            option.textContent = collection_semarang.nama_collection_semarang;
            collection_semarangSelect.appendChild(option);
        });
    } else {
        // Disable the collection_semarang select if no buyer is selected
        collection_semarangSelect.disabled = true;
    }
}

// Function to check if color code exists
function checkColorCode(colorCode) {
    if (!colorCode.trim()) {
        hideColorCodeStatus();
        return;
    }
    
    showColorCodeLoading();
    
    fetch(`new_data_it.php?check_color_code=${encodeURIComponent(colorCode.trim())}`)
        .then(response => response.json())
        .then(data => {
            if (data.exists) {
                showColorCodeExists();
                isColorCodeValid = false;
            } else {
                showColorCodeAvailable();
                isColorCodeValid = true;
            }
        })
        .catch(error => {
            console.error('Error checking color code:', error);
            hideColorCodeStatus();
            isColorCodeValid = false;
        });
}

// Function to show loading state
function showColorCodeLoading() {
    document.getElementById('color-code-status').classList.remove('hidden');
    document.getElementById('color-code-loading').classList.remove('hidden');
    document.getElementById('color-code-available').classList.add('hidden');
    document.getElementById('color-code-exists').classList.add('hidden');
    document.getElementById('color-code-message').classList.add('hidden');
    document.getElementById('color-code-error').classList.add('hidden');
    document.getElementById('color-code-success').classList.add('hidden');
}

// Function to show color code exists
function showColorCodeExists() {
    document.getElementById('color-code-status').classList.remove('hidden');
    document.getElementById('color-code-loading').classList.add('hidden');
    document.getElementById('color-code-available').classList.add('hidden');
    document.getElementById('color-code-exists').classList.remove('hidden');
    document.getElementById('color-code-message').classList.remove('hidden');
    document.getElementById('color-code-error').classList.remove('hidden');
    document.getElementById('color-code-success').classList.add('hidden');
    
    // Change input border color to red
    document.getElementById('code_color').classList.add('border-red-300', 'focus:border-red-500', 'focus:ring-red-500');
    document.getElementById('code_color').classList.remove('border-gray-300', 'focus:border-indigo-500', 'focus:ring-indigo-500');
}

// Function to show color code available
function showColorCodeAvailable() {
    document.getElementById('color-code-status').classList.remove('hidden');
    document.getElementById('color-code-loading').classList.add('hidden');
    document.getElementById('color-code-available').classList.remove('hidden');
    document.getElementById('color-code-exists').classList.add('hidden');
    document.getElementById('color-code-message').classList.remove('hidden');
    document.getElementById('color-code-error').classList.add('hidden');
    document.getElementById('color-code-success').classList.remove('hidden');
    
    // Reset input border color
    document.getElementById('code_color').classList.remove('border-red-300', 'focus:border-red-500', 'focus:ring-red-500');
    document.getElementById('code_color').classList.add('border-gray-300', 'focus:border-indigo-500', 'focus:ring-indigo-500');
}

// Function to hide color code status
function hideColorCodeStatus() {
    document.getElementById('color-code-status').classList.add('hidden');
    document.getElementById('color-code-message').classList.add('hidden');
    
    // Reset input border color
    document.getElementById('code_color').classList.remove('border-red-300', 'focus:border-red-500', 'focus:ring-red-500');
    document.getElementById('code_color').classList.add('border-gray-300', 'focus:border-indigo-500', 'focus:ring-indigo-500');
    
    isColorCodeValid = false;
}

// Add event listener to buyer select
document.getElementById('buyer_id').addEventListener('change', updatecollection_semarangs);

// Add event listener to color code input for real-time checking
document.getElementById('code_color').addEventListener('input', function() {
    const colorCode = this.value;
    
    // Clear the previous timeout
    if (colorCodeCheckTimeout) {
        clearTimeout(colorCodeCheckTimeout);
    }
    
    // Set a new timeout to check after user stops typing (debouncing)
    colorCodeCheckTimeout = setTimeout(function() {
        checkColorCode(colorCode);
    }, 500);
});

// Function to sync quantity with available quantity
function syncQuantities(quantityInput) {
    var row = quantityInput.closest('.component-row');
    var 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();

// Function to handle component select change
function handleComponentSelectChange(select) {
    var row = select.closest('.component-row');
    var 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
        var 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() {
    var 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() {
    var container = document.getElementById('component-container');
    var componentRowTemplate = container.querySelector('.component-row').cloneNode(true);
    
    // Reset values in the cloned template
    componentRowTemplate.querySelector('select[name="components[]"]').value = '';
    var 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
    var newComponentInput = componentRowTemplate.querySelector('.new-component-input');
    newComponentInput.classList.add('hidden');
    
    // Remove required attribute from new component inputs
    var inputEl = newComponentInput.querySelector('input');
    if (inputEl) inputEl.required = false;
    
    // Add event listener to component select
    var 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
    var 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();
    });
});

// Form validation
document.getElementById('colorForm').addEventListener('submit', function(event) {
    var lemari = document.getElementById('lemari').value;
    var colorCode = document.getElementById('code_color').value.trim();
    
    // Check if color code exists (client-side validation)
    if (!isColorCodeValid && colorCode) {
        alert('Kode warna sudah ada di dalam database. Silakan gunakan kode warna yang berbeda.');
        event.preventDefault();
        return;
    }
    
    // Validate lemari (should be a single letter A-Z)
    if (!/^[A-Za-z]$/.test(lemari)) {
        alert('Lemari harus berupa 1 huruf abjad (A-Z)');
        event.preventDefault();
        return;
    }
    
    // Validate color_hex (if provided)
    var hexCode = document.getElementById('kode_warna_hex').value;
    if (hexCode && !/^[0-9A-Fa-f]{6}$/.test(hexCode)) {
        alert('Kode warna hex harus berupa 6 karakter hexadecimal');
        event.preventDefault();
        return;
    }
    
    // Validate unique component selections
    var selects = document.querySelectorAll('select[name="components[]"]');
    var selectedComponents = [];
    
    for (var i = 0; i < selects.length; i++) {
        var 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'; ?>