<?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 = "Rename Color Code";

// Log activity
log_activity($conn, $it_id, 'it', 'Rename Color Code Access', 'IT user accessed rename color code page');

// 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']);
    $exclude_id = isset($_GET['exclude_id']) ? intval($_GET['exclude_id']) : 0;
    
    $check_query = "SELECT COUNT(*) as count FROM master_color_panel_surabaya WHERE code_color = ? AND id != ?";
    $check_stmt = $conn->prepare($check_query);
    $check_stmt->bind_param("si", $color_code, $exclude_id);
    $check_stmt->execute();
    $result = $check_stmt->get_result();
    $count = $result->fetch_assoc()['count'];
    
    echo json_encode(['exists' => $count > 0]);
    exit();
}

// Handle AJAX request for getting color details
if (isset($_GET['get_color_details']) && !empty($_GET['get_color_details'])) {
    header('Content-Type: application/json');
    
    $color_id = intval($_GET['get_color_details']);
    
    $color_query = "SELECT c.id, c.code_color, c.deskripsi, c.lemari, c.status, c.kode_warna_hex,
                           b.nama_buyer, col.nama_collection_surabaya,
                           (SELECT COUNT(*) FROM color_stock_items_surabaya WHERE color_id = c.id) as stock_count
                    FROM master_color_panel_surabaya c
                    JOIN buyers_surabaya b ON c.buyer_id = b.id
                    JOIN collection_surabayas col ON c.collection_surabaya_id = col.id
                    WHERE c.id = ?";
    
    $color_stmt = $conn->prepare($color_query);
    $color_stmt->bind_param("i", $color_id);
    $color_stmt->execute();
    $color_result = $color_stmt->get_result();
    
    if ($color_result->num_rows > 0) {
        $color_data = $color_result->fetch_assoc();
        echo json_encode(['success' => true, 'data' => $color_data]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Color not found']);
    }
    exit();
}

// Handle form submission for renaming color code
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'rename') {
    header('Content-Type: application/json');
    
    try {
        // Start transaction
        $conn->begin_transaction();
        
        $color_id = intval($_POST['color_id']);
        $old_color_code = trim($_POST['old_color_code']);
        $new_color_code = trim($_POST['new_color_code']);
        
        // Validate inputs
        if (empty($new_color_code)) {
            throw new Exception("Color code baru tidak boleh kosong");
        }
        
        if ($color_id <= 0) {
            throw new Exception("ID color tidak valid");
        }
        
        // Check if color exists
        $check_color_stmt = $conn->prepare("SELECT code_color FROM master_color_panel_surabaya WHERE id = ?");
        $check_color_stmt->bind_param("i", $color_id);
        $check_color_stmt->execute();
        $check_result = $check_color_stmt->get_result();
        
        if ($check_result->num_rows == 0) {
            throw new Exception("Data color tidak ditemukan");
        }
        
        $current_color = $check_result->fetch_assoc();
        
        // Verify old color code matches
        if ($current_color['code_color'] !== $old_color_code) {
            throw new Exception("Color code lama tidak sesuai");
        }
        
        // Check if new color code already exists
        $check_duplicate_stmt = $conn->prepare("SELECT COUNT(*) as count FROM master_color_panel_surabaya WHERE code_color = ? AND id != ?");
        $check_duplicate_stmt->bind_param("si", $new_color_code, $color_id);
        $check_duplicate_stmt->execute();
        $duplicate_result = $check_duplicate_stmt->get_result();
        $duplicate_count = $duplicate_result->fetch_assoc()['count'];
        
        if ($duplicate_count > 0) {
            throw new Exception("Color code '$new_color_code' sudah ada di dalam database");
        }
        
        // Update color code in master_color_panel_surabaya
        $update_color_stmt = $conn->prepare("UPDATE master_color_panel_surabaya SET code_color = ? WHERE id = ?");
        $update_color_stmt->bind_param("si", $new_color_code, $color_id);
        $update_color_stmt->execute();
        
        // Get buyer info for updating keterangan in stock items
        $buyer_query = "SELECT b.kode_buyer 
                       FROM buyers_surabaya b 
                       JOIN master_color_panel_surabaya c ON b.id = c.buyer_id 
                       WHERE c.id = ?";
        $buyer_stmt = $conn->prepare($buyer_query);
        $buyer_stmt->bind_param("i", $color_id);
        $buyer_stmt->execute();
        $buyer_result = $buyer_stmt->get_result();
        $buyer_data = $buyer_result->fetch_assoc();
        
        // Update keterangan in stock items to reflect new color code
        $update_stock_stmt = $conn->prepare("
            UPDATE color_stock_items_surabaya csi
            JOIN color_components_surabaya cc ON csi.component_id = cc.id
            SET csi.keterangan = CONCAT(?, ' ', ?, ' ', cc.component_name, 
                CASE 
                    WHEN csi.stock_number > 1 THEN CONCAT(' ', csi.stock_number)
                    ELSE ''
                END)
            WHERE csi.color_id = ?
        ");
        $update_stock_stmt->bind_param("ssi", $buyer_data['kode_buyer'], $new_color_code, $color_id);
        $update_stock_stmt->execute();
        
        $affected_stock_items = $update_stock_stmt->affected_rows;
        
        // Commit transaction
        $conn->commit();
        
        // Log activity
        log_activity($conn, $it_id, 'it', 'Rename Color Code', "IT user renamed color code from '$old_color_code' to '$new_color_code' (ID: $color_id)");
        
        echo json_encode([
            'success' => true, 
            'message' => "Color code berhasil diubah dari '$old_color_code' menjadi '$new_color_code'. $affected_stock_items item stok diperbarui."
        ]);
        
    } catch (Exception $e) {
        // Rollback transaction
        $conn->rollback();
        
        echo json_encode([
            'success' => false, 
            'message' => $e->getMessage()
        ]);
    }
    exit();
}

// Get all buyers_surabaya for filter
$buyers_surabaya_query = "SELECT id, nama_buyer FROM buyers_surabaya ORDER BY nama_buyer";
$buyers_surabaya_result = $conn->query($buyers_surabaya_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';
        }, 5000);
    </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';
        }, 5000);
    </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">
            <i class="fas fa-edit mr-2"></i>
            Rename Color Code
        </h2>
        <p class="text-gray-600">
            Halaman ini digunakan untuk mengubah penamaan color code jika terjadi kesalahan penamaan. Perubahan akan mempengaruhi semua stock items yang terkait.
        </p>
    </div>
    
    <!-- Color Selection -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h3 class="text-xl font-semibold text-gray-800 mb-4">Pilih Color Code yang akan direname</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 max-w-md 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 Buyer --</option>
                <?php while ($buyer = $buyers_surabaya_result->fetch_assoc()): ?>
                    <option value="<?php echo $buyer['id']; ?>"><?php echo htmlspecialchars($buyer['nama_buyer']); ?></option>
                <?php endwhile; ?>
            </select>
        </div>
        
        <!-- Color Search -->
        <div class="mb-4">
            <label for="color_search" class="block text-sm font-medium text-gray-700 mb-1">Cari Color Code:</label>
            <input type="text" id="color_search" placeholder="Ketik untuk mencari color code..." class="mt-1 block w-full max-w-md 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">
        </div>
        
        <!-- Color List Table -->
        <div class="overflow-x-auto">
            <table class="min-w-full bg-white border border-gray-200">
                <thead class="bg-gray-100">
                    <tr>
                        <th class="py-3 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                        <th class="py-3 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Color Code</th>
                        <th class="py-3 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Deskripsi</th>
                        <th class="py-3 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Pembeli</th>
                        <th class="py-3 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Koleksi</th>
                        <th class="py-3 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Lemari</th>
                        <th class="py-3 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                        <th class="py-3 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Stok Items</th>
                        <th class="py-3 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200" id="colorTableBody">
                <?php
                // Get all color panels
                $colors_query = "SELECT c.id, c.code_color, c.deskripsi, c.lemari, c.status, c.kode_warna_hex,
                               b.nama_buyer, b.id as buyer_id, col.nama_collection_surabaya,
                               (SELECT COUNT(*) FROM color_stock_items_surabaya WHERE color_id = c.id) as stock_count
                            FROM master_color_panel_surabaya c
                            JOIN buyers_surabaya b ON c.buyer_id = b.id
                            JOIN collection_surabayas col ON c.collection_surabaya_id = col.id
                            ORDER BY b.nama_buyer, c.code_color";
                $colors_result = $conn->query($colors_query);
                
                if ($colors_result->num_rows > 0) {
                    while ($color = $colors_result->fetch_assoc()) {
                        echo '<tr class="color-row" data-buyer-id="' . $color['buyer_id'] . '" data-color-code="' . htmlspecialchars($color['code_color']) . '">';
                        echo '<td class="py-3 px-4 text-sm text-gray-500">' . $color['id'] . '</td>';
                        echo '<td class="py-3 px-4 text-sm font-medium text-gray-900">' . htmlspecialchars($color['code_color']) . '</td>';
                        echo '<td class="py-3 px-4 text-sm text-gray-500">' . htmlspecialchars($color['deskripsi']) . '</td>';
                        echo '<td class="py-3 px-4 text-sm text-gray-500">' . htmlspecialchars($color['nama_buyer']) . '</td>';
                        echo '<td class="py-3 px-4 text-sm text-gray-500">' . htmlspecialchars($color['nama_collection_surabaya']) . '</td>';
                        echo '<td class="py-3 px-4 text-sm text-gray-500">' . htmlspecialchars($color['lemari']) . '</td>';
                        
                        $status_class = '';
                        if ($color['status'] == 'Hijau') {
                            $status_class = 'bg-green-100 text-green-800';
                        } else if ($color['status'] == 'Kuning') {
                            $status_class = 'bg-yellow-100 text-yellow-800';
                        } else if ($color['status'] == 'Merah') {
                            $status_class = 'bg-red-100 text-red-800';
                        }
                        
                        echo '<td class="py-3 px-4">';
                        echo '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ' . $status_class . '">';
                        echo htmlspecialchars($color['status']);
                        echo '</span>';
                        echo '</td>';
                        
                        echo '<td class="py-3 px-4 text-sm text-center">';
                        echo '<span class="bg-purple-100 text-purple-800 text-xs font-semibold px-2.5 py-0.5 rounded">' . $color['stock_count'] . '</span>';
                        echo '</td>';
                        
                        echo '<td class="py-3 px-4 text-sm">';
                        echo '<button onclick="selectColor(' . $color['id'] . ', \'' . htmlspecialchars($color['code_color'], ENT_QUOTES) . '\')" class="bg-blue-500 hover:bg-blue-600 text-white text-xs py-1 px-3 rounded">';
                        echo '<i class="fas fa-edit mr-1"></i> Rename';
                        echo '</button>';
                        echo '</td>';
                        
                        echo '</tr>';
                    }
                } else {
                    echo '<tr><td colspan="9" class="py-3 px-4 text-center text-gray-500">Tidak ada data warna</td></tr>';
                }
                ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- Rename Form (Initially Hidden) -->
    <div id="renameForm" class="bg-white rounded-lg shadow-md p-6 hidden">
        <h3 class="text-xl font-semibold text-gray-800 mb-4">
            <i class="fas fa-edit mr-2"></i>
            Rename Color Code
        </h3>
        
        <!-- Selected Color Info -->
        <div id="selectedColorInfo" class="mb-6 p-4 bg-gray-100 rounded-md">
            <h4 class="font-semibold mb-2">Color yang dipilih:</h4>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <p><span class="font-medium">ID:</span> <span id="info-id"></span></p>
                    <p><span class="font-medium">Color Code Lama:</span> <span id="info-old-code" class="font-mono bg-yellow-100 px-2 py-1 rounded"></span></p>
                    <p><span class="font-medium">Deskripsi:</span> <span id="info-desc"></span></p>
                    <p><span class="font-medium">Pembeli:</span> <span id="info-buyer"></span></p>
                </div>
                <div>
                    <p><span class="font-medium">Koleksi:</span> <span id="info-collection_surabaya"></span></p>
                    <p><span class="font-medium">Lemari:</span> <span id="info-lemari"></span></p>
                    <p><span class="font-medium">Status:</span> <span id="info-status"></span></p>
                    <p><span class="font-medium">Jumlah Stok Items:</span> <span id="info-stock-count" class="bg-purple-100 px-2 py-1 rounded text-purple-800 font-semibold"></span></p>
                </div>
            </div>
        </div>
        
        <!-- Rename Form -->
        <form id="renameColorForm" class="space-y-4">
            <input type="hidden" id="rename_color_id" name="color_id">
            <input type="hidden" id="rename_old_color_code" name="old_color_code">
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label for="new_color_code" class="block text-sm font-medium text-gray-700 mb-1">Color Code Baru</label>
                    <div class="relative">
                        <input type="text" id="new_color_code" name="new_color_code" 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 placeholder="Masukkan color code baru">
                        <div id="new-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="new-color-code-loading"></i>
                            <i class="fas fa-check text-green-500 hidden" id="new-color-code-available"></i>
                            <i class="fas fa-times text-red-500 hidden" id="new-color-code-exists"></i>
                        </div>
                    </div>
                    <div id="new-color-code-message" class="mt-1 text-sm hidden">
                        <p id="new-color-code-error" class="text-red-600 hidden">
                            <i class="fas fa-exclamation-triangle mr-1"></i>
                            Color code sudah ada di dalam database
                        </p>
                        <p id="new-color-code-success" class="text-green-600 hidden">
                            <i class="fas fa-check mr-1"></i>
                            Color code tersedia
                        </p>
                    </div>
                </div>
                
                <div class="flex items-end">
                    <div class="w-full">
                        <label class="block text-sm font-medium text-gray-700 mb-1">Preview Perubahan</label>
                        <div class="p-3 bg-blue-50 border border-blue-200 rounded-md">
                            <div class="flex items-center justify-between">
                                <span class="text-sm">
                                    <span class="font-mono bg-red-100 px-2 py-1 rounded text-red-800" id="preview-old"></span>
                                    <i class="fas fa-arrow-right mx-2 text-blue-600"></i>
                                    <span class="font-mono bg-green-100 px-2 py-1 rounded text-green-800" id="preview-new">-</span>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="bg-yellow-50 border-l-4 border-yellow-400 p-4">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <i class="fas fa-exclamation-triangle text-yellow-400"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm text-yellow-700">
                            <strong>Peringatan:</strong> Mengubah color code akan mempengaruhi:
                        </p>
                        <ul class="mt-2 text-sm text-yellow-700 list-disc list-inside">
                            <li>Semua stock items yang terkait dengan color ini</li>
                            <li>Keterangan pada stock items akan diperbarui secara otomatis</li>
                            <li>Data audit log akan mencatat perubahan ini</li>
                        </ul>
                    </div>
                </div>
            </div>
            
            <div class="flex justify-end space-x-3 pt-4">
                <button type="button" id="cancelRenameBtn" 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="submit" id="saveRenameBtn" class="py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-orange-600 hover:bg-orange-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-orange-500" disabled>
                    <i class="fas fa-save mr-2"></i> Simpan Perubahan
                </button>
            </div>
        </form>
    </div>
</main>

<script>
// Variables for color code checking
let newColorCodeCheckTimeout;
let isNewColorCodeValid = false;
let currentSelectedColorId = 0;

// Filter and search functionality
document.getElementById('buyer_filter').addEventListener('change', filterColors);
document.getElementById('color_search').addEventListener('input', filterColors);

function filterColors() {
    const buyerId = document.getElementById('buyer_filter').value;
    const searchTerm = document.getElementById('color_search').value.toLowerCase();
    const colorRows = document.querySelectorAll('.color-row');
    
    colorRows.forEach(function(row) {
        const colorCode = row.dataset.colorCode.toLowerCase();
        const buyerMatch = !buyerId || row.dataset.buyerId === buyerId;
        const searchMatch = !searchTerm || colorCode.includes(searchTerm);
        
        if (buyerMatch && searchMatch) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    });
}

// Function to select color for renaming
function selectColor(colorId, colorCode) {
    currentSelectedColorId = colorId;
    
    // Fetch color details
    fetch(`rename_color_code.php?get_color_details=${colorId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const color = data.data;
                
                // Populate color info
                document.getElementById('info-id').textContent = color.id;
                document.getElementById('info-old-code').textContent = color.code_color;
                document.getElementById('info-desc').textContent = color.deskripsi;
                document.getElementById('info-buyer').textContent = color.nama_buyer;
                document.getElementById('info-collection_surabaya').textContent = color.nama_collection_surabaya;
                document.getElementById('info-lemari').textContent = color.lemari;
                document.getElementById('info-status').textContent = color.status;
                document.getElementById('info-stock-count').textContent = color.stock_count;
                
                // Set form values
                document.getElementById('rename_color_id').value = color.id;
                document.getElementById('rename_old_color_code').value = color.code_color;
                document.getElementById('new_color_code').value = '';
                
                // Set preview
                document.getElementById('preview-old').textContent = color.code_color;
                document.getElementById('preview-new').textContent = '-';
                
                // Reset validation
                hideNewColorCodeStatus();
                document.getElementById('saveRenameBtn').disabled = true;
                
                // Show rename form
                document.getElementById('renameForm').classList.remove('hidden');
                document.getElementById('renameForm').scrollIntoView({ behavior: 'smooth' });
            } else {
                showNotification('red', 'Gagal mengambil detail color: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('red', 'Terjadi kesalahan saat mengambil detail color');
        });
}

// Function to check if new color code exists
function checkNewColorCode(colorCode) {
    if (!colorCode.trim()) {
        hideNewColorCodeStatus();
        return;
    }
    
    showNewColorCodeLoading();
    
    fetch(`rename_color_code.php?check_color_code=${encodeURIComponent(colorCode.trim())}&exclude_id=${currentSelectedColorId}`)
        .then(response => response.json())
        .then(data => {
            if (data.exists) {
                showNewColorCodeExists();
                isNewColorCodeValid = false;
            } else {
                showNewColorCodeAvailable();
                isNewColorCodeValid = true;
            }
            updateSaveButton();
        })
        .catch(error => {
            console.error('Error checking color code:', error);
            hideNewColorCodeStatus();
            isNewColorCodeValid = false;
            updateSaveButton();
        });
}

// Color code validation status functions
function showNewColorCodeLoading() {
    document.getElementById('new-color-code-status').classList.remove('hidden');
    document.getElementById('new-color-code-loading').classList.remove('hidden');
    document.getElementById('new-color-code-available').classList.add('hidden');
    document.getElementById('new-color-code-exists').classList.add('hidden');
    document.getElementById('new-color-code-message').classList.add('hidden');
    document.getElementById('new-color-code-error').classList.add('hidden');
    document.getElementById('new-color-code-success').classList.add('hidden');
}

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

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

function hideNewColorCodeStatus() {
    document.getElementById('new-color-code-status').classList.add('hidden');
    document.getElementById('new-color-code-message').classList.add('hidden');
    
    // Reset input border color
    document.getElementById('new_color_code').classList.remove('border-red-300', 'focus:border-red-500', 'focus:ring-red-500');
    document.getElementById('new_color_code').classList.add('border-gray-300', 'focus:border-indigo-500', 'focus:ring-indigo-500');
    
    isNewColorCodeValid = false;
}

// Function to update save button state
function updateSaveButton() {
    const newColorCode = document.getElementById('new_color_code').value.trim();
    const oldColorCode = document.getElementById('rename_old_color_code').value;
    const saveBtn = document.getElementById('saveRenameBtn');
    
    if (newColorCode && isNewColorCodeValid && newColorCode !== oldColorCode) {
        saveBtn.disabled = false;
        saveBtn.classList.remove('opacity-50', 'cursor-not-allowed');
    } else {
        saveBtn.disabled = true;
        saveBtn.classList.add('opacity-50', 'cursor-not-allowed');
    }
}

// Add event listener to new color code input
document.getElementById('new_color_code').addEventListener('input', function() {
    const colorCode = this.value;
    const oldColorCode = document.getElementById('rename_old_color_code').value;
    
    // Update preview
    document.getElementById('preview-new').textContent = colorCode || '-';
    
    // Clear the previous timeout
    if (newColorCodeCheckTimeout) {
        clearTimeout(newColorCodeCheckTimeout);
    }
    
    // Set a new timeout to check after user stops typing (debouncing)
    if (colorCode.trim() && colorCode.trim() !== oldColorCode) {
        newColorCodeCheckTimeout = setTimeout(function() {
            checkNewColorCode(colorCode);
        }, 500);
    } else {
        hideNewColorCodeStatus();
        isNewColorCodeValid = colorCode.trim() === oldColorCode ? false : true;
        updateSaveButton();
    }
});

// Cancel button
document.getElementById('cancelRenameBtn').addEventListener('click', function() {
    document.getElementById('renameForm').classList.add('hidden');
    document.getElementById('new_color_code').value = '';
    hideNewColorCodeStatus();
});

// Form submission
document.getElementById('renameColorForm').addEventListener('submit', function(event) {
    event.preventDefault();
    
    const newColorCode = document.getElementById('new_color_code').value.trim();
    const oldColorCode = document.getElementById('rename_old_color_code').value;
    
    if (!newColorCode) {
        showNotification('red', 'Color code baru tidak boleh kosong');
        return;
    }
    
    if (newColorCode === oldColorCode) {
        showNotification('red', 'Color code baru harus berbeda dari yang lama');
        return;
    }
    
    if (!isNewColorCodeValid) {
        showNotification('red', 'Color code sudah ada di dalam database');
        return;
    }
    
    if (!confirm(`Apakah Anda yakin ingin mengubah color code dari "${oldColorCode}" menjadi "${newColorCode}"?`)) {
        return;
    }
    
    // Submit form via AJAX
    const formData = new FormData(this);
    formData.append('action', 'rename');
    
    // Disable submit button
    const saveBtn = document.getElementById('saveRenameBtn');
    saveBtn.disabled = true;
    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> Menyimpan...';
    
    fetch('rename_color_code.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('green', data.message);
            
            // Update table row
            updateTableRow(currentSelectedColorId, newColorCode);
            
            // Hide form
            document.getElementById('renameForm').classList.add('hidden');
        } else {
            showNotification('red', data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('red', 'Terjadi kesalahan saat menyimpan perubahan');
    })
    .finally(() => {
        // Reset submit button
        saveBtn.disabled = false;
        saveBtn.innerHTML = '<i class="fas fa-save mr-2"></i> Simpan Perubahan';
    });
});

// Function to update table row after successful rename
function updateTableRow(colorId, newColorCode) {
    const rows = document.querySelectorAll('.color-row');
    rows.forEach(row => {
        const colorCodeCell = row.querySelector('td:nth-child(2)');
        if (colorCodeCell && row.querySelector('button[onclick*="' + colorId + '"]')) {
            colorCodeCell.textContent = newColorCode;
            row.dataset.colorCode = newColorCode;
            
            // Update button onclick
            const button = row.querySelector('button[onclick*="' + colorId + '"]');
            button.setAttribute('onclick', `selectColor(${colorId}, '${newColorCode}')`);
        }
    });
}

// Helper function to show notifications
function showNotification(type, message) {
    const notification = document.createElement('div');
    notification.className = `fixed top-4 right-4 bg-${type}-100 border-l-4 border-${type}-500 text-${type}-700 p-4 rounded shadow-md z-50`;
    
    let iconClass = type === 'green' ? 'fa-check-circle' : 'fa-exclamation-circle';
    
    notification.innerHTML = `
        <div class="flex">
            <div class="flex-shrink-0">
                <i class="fas ${iconClass} text-${type}-500"></i>
            </div>
            <div class="ml-3">
                <p class="text-sm">${message}</p>
            </div>
        </div>
    `;
    
    document.body.appendChild(notification);
    
    // Remove notification after 5 seconds
    setTimeout(() => {
        notification.remove();
    }, 5000);
}
</script>

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