<?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 Master Color";

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

// Function to get next sequential code
function getNextSequentialCode($conn) {
    $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
    $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);
    }
    
    $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
$collections = [];
while ($collection = $collections_result->fetch_assoc()) {
    $collections[] = $collection;
}

// 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 master color 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 Master Color Baru
            </a>
            <a href="add_component_panel.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 & Copy Panel
            </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 Master 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 Master Color</h3>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Hidden Panel Type (always master_color) -->
                <input type="hidden" name="panel_type" value="master_color">
                
                <!-- Next Code Preview -->
                <div class="md:col-span-2 bg-blue-50 p-4 rounded-lg border-2 border-blue-200">
                    <p class="text-sm text-gray-700 mb-2">
                        <i class="fas fa-barcode mr-2"></i>
                        <strong>Kode Master Color yang akan di-generate:</strong>
                    </p>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div class="bg-white p-3 rounded border">
                            <p class="text-xs text-gray-600">Master Color Code</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">Master Color Panel Code</p>
                            <p class="text-lg font-bold text-green-600"><?php echo sprintf("%05d", $next_code_number + 1); ?></p>
                        </div>
                    </div>
                    <input type="hidden" name="next_code_number" value="<?php echo $next_code_number; ?>">
                    <p class="text-xs text-blue-600 mt-2">
                        <i class="fas fa-info-circle mr-1"></i>
                        Master Color adalah wadah asli warna yang tidak dapat dipinjam
                    </p>
                </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 $buyers_result->data_seek(0); ?>
                        <?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>
                
                <!-- Lemari Number Selection -->
                <div>
                    <label for="lemari_number" class="block text-sm font-medium text-gray-700 mb-1">
                        Lemari <span class="text-red-500">*</span>
                    </label>
                    <select id="lemari_number" name="lemari_number" 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 Lemari --</option>
                        <option value="1">Lemari 1</option>
                        <option value="2">Lemari 2</option>
                    </select>
                    <p class="text-xs text-gray-500 mt-1">Pilih lemari 1 atau 2 untuk lokasi penyimpanan master color</p>
                </div>
                
                <!-- Cabinet Letter -->
                <div>
                    <label for="lemari" class="block text-sm font-medium text-gray-700 mb-1">
                        Huruf 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) untuk posisi di lemari</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>
            
            <!-- Preview Lokasi -->
            <div id="lokasi-preview" class="bg-gray-50 p-4 rounded-lg border hidden">
                <h4 class="font-semibold text-gray-800 mb-2">Preview Lokasi Penyimpanan:</h4>
                <p class="text-sm text-gray-600">
                    <i class="fas fa-map-marker-alt mr-2"></i>
                    <span id="preview-text">Pilih lemari dan huruf untuk melihat lokasi</span>
                </p>
            </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 Master Color
                </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;
    }
}

// Function to update location preview
function updateLokasiPreview() {
    var lemariNumber = document.getElementById('lemari_number').value;
    var lemariLetter = document.getElementById('lemari').value.toUpperCase();
    var previewDiv = document.getElementById('lokasi-preview');
    var previewText = document.getElementById('preview-text');
    
    if (lemariNumber && lemariLetter) {
        previewDiv.classList.remove('hidden');
        previewText.innerHTML = '<strong>Lemari ' + lemariNumber + ' - Posisi ' + lemariLetter + '</strong> (Master Color akan disimpan di lokasi ini)';
    } else {
        previewDiv.classList.add('hidden');
    }
}

// Add event listeners
document.getElementById('buyer_id').addEventListener('change', updateCollections);
document.getElementById('lemari_number').addEventListener('change', updateLokasiPreview);
document.getElementById('lemari').addEventListener('input', function() {
    this.value = this.value.toUpperCase();
    updateLokasiPreview();
});

// Form validation
document.getElementById('colorForm').addEventListener('submit', function(event) {
    try {
        var lemariNumber = document.getElementById('lemari_number').value;
        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 false;
        }
        
        // Validate lemari_number is selected
        if (!lemariNumber) {
            alert('Silakan pilih lemari (1 atau 2)');
            event.preventDefault();
            return false;
        }
        
        // Validate lemari (should be a single letter A-Z)
        if (!/^[A-Za-z]$/.test(lemari)) {
            alert('Huruf lemari harus berupa 1 huruf abjad (A-Z)');
            event.preventDefault();
            return false;
        }
        
        // 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 false;
        }
        
        return true;
        
    } catch (error) {
        console.error('Form validation error:', error);
        alert('Terjadi kesalahan validasi form. Silakan coba lagi.');
        event.preventDefault();
        return false;
    }
});

// Reset form handler
document.querySelector('button[type="reset"]').addEventListener('click', function() {
    setTimeout(function() {
        document.getElementById('collection_id').disabled = true;
        document.getElementById('lokasi-preview').classList.add('hidden');
    }, 50);
});
</script>

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