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

// Function to get next sequential code
function getNextSequentialCode($conn) {
    // Get highest code from all three tables
    $codes = [];
    
    // From master_color
    $query1 = "SELECT code_color FROM master_color ORDER BY id DESC LIMIT 1";
    $result1 = $conn->query($query1);
    if ($result1->num_rows > 0) {
        $codes[] = intval($result1->fetch_assoc()['code_color']);
    }
    
    // From master_color_panel
    $query2 = "SELECT code_color FROM master_color_panel ORDER BY id DESC LIMIT 1";
    $result2 = $conn->query($query2);
    if ($result2->num_rows > 0) {
        $codes[] = intval($result2->fetch_assoc()['code_color']);
    }
    
    // From color_stock_items (now without CP. prefix, just numbers)
    $query3 = "SELECT kode_barang FROM color_stock_items ORDER BY id DESC LIMIT 1";
    $result3 = $conn->query($query3);
    if ($result3->num_rows > 0) {
        $last_code = $result3->fetch_assoc()['kode_barang'];
        $codes[] = intval($last_code); // Direct conversion since no prefix
    }
    
    // Get the maximum and add 1
    $next_number = empty($codes) ? 1 : max($codes) + 1;
    
    return $next_number;
}

$next_code_number = getNextSequentialCode($conn);

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

// Get all collections
$collections_query = "SELECT id, nama_collection, buyer_id FROM collections ORDER BY nama_collection";
$collections_result = $conn->query($collections_query);

// Store collections in an array for later use with JavaScript
$collections = [];
while ($collection = $collections_result->fetch_assoc()) {
    $collections[] = $collection;
}
$collections_result->data_seek(0);

// 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>
    
    <!-- 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">
                <!-- Panel Type Selection -->
                <div class="md:col-span-2">
                    <label class="block text-sm font-medium text-gray-700 mb-3">
                        Tipe Panel <span class="text-red-500">*</span>
                    </label>
                    <div class="flex space-x-4">
                        <label class="flex items-center p-4 border-2 border-blue-300 rounded-lg cursor-pointer hover:bg-blue-50 transition">
                            <input type="radio" name="panel_type" value="master_color" class="mr-3 w-5 h-5" required>
                            <div>
                                <div class="font-semibold text-blue-700">Master Color</div>
                                <div class="text-xs text-gray-600">Wadah asli warna (tidak dapat dipinjam)</div>
                            </div>
                        </label>
                        <label class="flex items-center p-4 border-2 border-green-300 rounded-lg cursor-pointer hover:bg-green-50 transition">
                            <input type="radio" name="panel_type" value="copy_panel" class="mr-3 w-5 h-5" checked required>
                            <div>
                                <div class="font-semibold text-green-700">Copy Panel</div>
                                <div class="text-xs text-gray-600">Salinan panel (dapat dipinjam)</div>
                            </div>
                        </label>
                    </div>
                    <p class="text-xs text-gray-500 mt-2">
                        <i class="fas fa-info-circle mr-1"></i>
                        Pilih Master Color untuk wadah asli atau Copy Panel untuk panel yang dapat dipinjam
                    </p>
                </div>
                
                <!-- Next Code Preview -->
                <div class="md:col-span-2 bg-gray-50 p-4 rounded-lg">
                    <p class="text-sm text-gray-700 mb-2">
                        <i class="fas fa-barcode mr-2"></i>
                        <strong>Kode yang akan di-generate:</strong>
                    </p>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
                        <div class="bg-white p-3 rounded border">
                            <p class="text-xs text-gray-600">Master Color</p>
                            <p class="text-lg font-bold text-blue-600"><?php echo sprintf("%05d", $next_code_number); ?></p>
                        </div>
                        <div class="bg-white p-3 rounded border">
                            <p class="text-xs text-gray-600">Color Code</p>
                            <p class="text-lg font-bold text-green-600"><?php echo sprintf("%05d", $next_code_number + 1); ?></p>
                        </div>
                        <div id="copy-panel-preview" class="bg-white p-3 rounded border">
                            <p class="text-xs text-gray-600">Copy Panel (per item)</p>
                            <p class="text-lg font-bold text-purple-600"><?php echo sprintf("%05d", $next_code_number + 2); ?>+</p>
                        </div>
                    </div>
                    <input type="hidden" name="next_code_number" value="<?php echo $next_code_number; ?>">
                </div>
                
                <!-- Buyer Selection -->
                <div>
                    <label for="buyer_id" class="block text-sm font-medium text-gray-700 mb-1">
                        Pembeli <span class="text-red-500">*</span>
                    </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_result->fetch_assoc()): ?>
                            <option value="<?php echo $buyer['id']; ?>"><?php echo htmlspecialchars($buyer['nama_buyer']); ?></option>
                        <?php endwhile; ?>
                    </select>
                </div>
                
                <!-- Collection Selection -->
                <div>
                    <label for="collection_id" class="block text-sm font-medium text-gray-700 mb-1">
                        Koleksi <span class="text-red-500">*</span>
                    </label>
                    <select id="collection_id" name="collection_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 Description -->
                <div>
                    <label for="name_color" class="block text-sm font-medium text-gray-700 mb-1">
                        Nama Warna <span class="text-red-500">*</span>
                    </label>
                    <input type="text" id="name_color" name="name_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>
                
                <!-- Cabinet -->
                <div>
                    <label for="lemari" class="block text-sm font-medium text-gray-700 mb-1">
                        Lemari <span class="text-red-500">*</span>
                    </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 <span class="text-red-500">*</span>
                    </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 <span class="text-red-500">*</span>
                    </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 <span class="text-red-500">*</span>
                    </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 <span class="text-red-500">*</span>
                    </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">
            <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 collections data
var collections = <?php echo json_encode($collections); ?>;

// Function to filter collections based on selected buyer
function updateCollections() {
    var buyerId = document.getElementById('buyer_id').value;
    var collectionSelect = document.getElementById('collection_id');
    
    // Clear existing options
    collectionSelect.innerHTML = '<option value="">-- Pilih Koleksi --</option>';
    
    if (buyerId) {
        // Enable the collection select
        collectionSelect.disabled = false;
        
        // Filter collections for selected buyer
        var filteredCollections = collections.filter(function(collection) {
            return collection.buyer_id == buyerId;
        });
        
        // Add filtered collections to select
        filteredCollections.forEach(function(collection) {
            var option = document.createElement('option');
            option.value = collection.id;
            option.textContent = collection.nama_collection;
            collectionSelect.appendChild(option);
        });
    } else {
        // Disable the collection select if no buyer is selected
        collectionSelect.disabled = true;
    }
}

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

// Update copy panel preview based on panel type selection
document.querySelectorAll('input[name="panel_type"]').forEach(function(radio) {
    radio.addEventListener('change', function() {
        var copyPanelPreview = document.getElementById('copy-panel-preview');
        if (this.value === 'master_color') {
            copyPanelPreview.style.display = 'none';
        } else {
            copyPanelPreview.style.display = 'block';
        }
    });
});

// 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 nameColor = document.getElementById('name_color').value.trim();
    
    // Validate name_color is not empty
    if (nameColor === '') {
        alert('Nama warna tidak boleh kosong');
        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'; ?>