<?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 = "Data Warna Yang Ada";

// Log activity
log_activity($conn, $it_id, 'it', 'Color List', 'IT user accessed color list page');

// Handle AJAX request for checking duplicate color code (for editing purposes)
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();
}

// 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';
        }, 3000);
    </script>
    <?php endif; ?>

    <?php if (!empty($error_message)): ?>
    <div id="error-alert" class="mb-4 bg-red-100 border-l-4 border-red-500 text-red-700 p-4 rounded shadow-md">
        <div class="flex">
            <div class="flex-shrink-0">
                <i class="fas fa-exclamation-circle text-red-500"></i>
            </div>
            <div class="ml-3">
                <p class="text-sm"><?php echo $error_message; ?></p>
            </div>
            <div class="ml-auto pl-3">
                <button type="button" onclick="document.getElementById('error-alert').style.display='none'">
                    <i class="fas fa-times text-red-500"></i>
                </button>
            </div>
        </div>
    </div>
    <script>
        setTimeout(function() {
            document.getElementById('error-alert').style.display = 'none';
        }, 3000);
    </script>
    <?php endif; ?>

    <!-- Page Header -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h2 class="text-2xl font-bold text-gray-800 mb-4">Manajemen Data Warna</h2>
        <p class="text-gray-600 mb-4">
            Halaman ini digunakan untuk mengelola data warna dalam sistem.
        </p>
        
        <div class="flex flex-wrap gap-3">
            <a href="new_data_it.php" class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition">
                <i class="fas fa-plus mr-2"></i> Pembuatan Data Baru
            </a>
            <a href="add_component_it.php" class="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700 transition">
                <i class="fas fa-puzzle-piece mr-2"></i> Penambahan Component & Code Barang
            </a>
            <a href="color_list_it.php" class="px-4 py-2 bg-purple-600 text-white rounded hover:bg-purple-700 transition">
                <i class="fas fa-list mr-2"></i> Data Warna Yang Ada
            </a>
        </div>
    </div>
    
    <!-- Color Data List -->
    <div class="bg-white rounded-lg shadow-md p-6">
        <h3 class="text-xl font-semibold text-gray-800 mb-6">Data Warna yang Ada</h3>
        
        <!-- Buyer Filter -->
        <div class="mb-4">
            <label for="buyer_filter" class="block text-sm font-medium text-gray-700 mb-1">Filter Berdasarkan Pembeli:</label>
            <select id="buyer_filter" class="mt-1 block w-full 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 Pembeli --</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>
        
        <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">Kode Warna</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">Warna</th>
                        <th class="py-3 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Komponen</th>
                        <th class="py-3 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Stok</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_panel_components_surabaya WHERE color_id = c.id) as component_count,
                               (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-id="' . $color['id'] . '">';
                        echo '<td class="py-3 px-4 text-sm text-gray-500">' . $color['id'] . '</td>';
                        echo '<td class="py-3 px-4 text-sm text-gray-500">';
                        echo '<a href="#" class="show-details text-blue-600 hover:text-blue-800 hover:underline" data-color-id="' . $color['id'] . '">' . htmlspecialchars($color['code_color']) . '</a>';
                        echo '</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">';
                        if (!empty($color['kode_warna_hex'])) {
                            echo '<div class="flex items-center">';
                            echo '<div class="w-6 h-6 mr-2 rounded border border-gray-300" style="background-color: #' . htmlspecialchars($color['kode_warna_hex']) . '"></div>';
                            echo '<span class="text-sm text-gray-500">#' . htmlspecialchars($color['kode_warna_hex']) . '</span>';
                            echo '</div>';
                        } else {
                            echo '<span class="text-sm text-gray-400">-</span>';
                        }
                        echo '</td>';
                        
                        echo '<td class="py-3 px-4 text-sm text-gray-500">';
                        echo '<span class="bg-blue-100 text-blue-800 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded">' . $color['component_count'] . '</span>';
                        echo '</td>';
                        
                        echo '<td class="py-3 px-4 text-sm text-gray-500">';
                        echo '<span class="bg-purple-100 text-purple-800 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded">' . $color['stock_count'] . '</span>';
                        echo '</td>';
                        
                        // Add action buttons
                        echo '<td class="py-3 px-4 text-sm">';
                        echo '<div class="flex space-x-2">';
                        echo '<button onclick="editColor(' . $color['id'] . ')" class="text-blue-600 hover:text-blue-900" title="Edit">';
                        echo '<i class="fas fa-edit"></i>';
                        echo '</button>';
                        echo '<button onclick="confirmDeleteColor(' . $color['id'] . ', \'' . htmlspecialchars($color['code_color'], ENT_QUOTES) . '\')" class="text-red-600 hover:text-red-900" title="Hapus">';
                        echo '<i class="fas fa-trash"></i>';
                        echo '</button>';
                        echo '</div>';
                        echo '</td>';
                        
                        echo '</tr>';
                    }
                } else {
                    echo '<tr><td colspan="11" class="py-3 px-4 text-center text-gray-500">Tidak ada data warna</td></tr>';
                }
                ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Edit Color Modal -->
    <div id="editColorModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden flex items-center justify-center z-50">
        <div class="bg-white rounded-lg shadow-xl mx-4 md:mx-auto w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            <div class="border-b px-6 py-4 flex items-center justify-between">
                <h3 class="text-xl font-bold text-gray-800">Edit Data Warna</h3>
                <button id="closeEditModal" class="text-gray-600 hover:text-gray-800">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="p-6">
                <form id="editColorForm" class="space-y-4">
                    <input type="hidden" id="edit_color_id" name="color_id">
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label for="edit_code_color" class="block text-sm font-medium text-gray-700 mb-1">Kode Warna</label>
                            <div class="relative">
                                <input type="text" id="edit_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="edit-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="edit-color-code-loading"></i>
                                    <i class="fas fa-check text-green-500 hidden" id="edit-color-code-available"></i>
                                    <i class="fas fa-times text-red-500 hidden" id="edit-color-code-exists"></i>
                                </div>
                            </div>
                            <div id="edit-color-code-message" class="mt-1 text-sm hidden">
                                <p id="edit-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="edit-color-code-success" class="text-green-600 hidden">
                                    <i class="fas fa-check mr-1"></i>
                                    Kode warna tersedia
                                </p>
                            </div>
                        </div>
                        
                        <div>
                            <label for="edit_deskripsi" class="block text-sm font-medium text-gray-700 mb-1">Deskripsi</label>
                            <input type="text" id="edit_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>
                        
                        <div>
                            <label for="edit_lemari" class="block text-sm font-medium text-gray-700 mb-1">Lemari</label>
                            <input type="text" id="edit_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>
                        </div>
                        
                        <div>
                            <label for="edit_status" class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                            <select id="edit_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>
                        
                        <div>
                            <label for="edit_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="edit_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>
                        </div>
                        
                        <div class="md:col-span-2">
                            <label for="edit_keterangan_warna" class="block text-sm font-medium text-gray-700 mb-1">Keterangan Warna</label>
                            <textarea id="edit_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>
                    
                    <div class="flex justify-end space-x-3 pt-4">
                        <button type="button" id="cancelEditBtn" 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="saveEditBtn" class="py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                            <i class="fas fa-save mr-2"></i> Simpan
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Color Details Modal -->
    <div id="colorDetailsModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden flex items-center justify-center z-50">
        <div class="bg-white rounded-lg shadow-xl mx-4 md:mx-auto w-full max-w-4xl max-h-[90vh] overflow-y-auto">
            <div class="border-b px-6 py-4 flex items-center justify-between">
                <h3 class="text-xl font-bold text-gray-800">Detail Warna <span id="modal-color-code" class="font-semibold"></span></h3>
                <button id="closeModal" class="text-gray-600 hover:text-gray-800">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="p-6">
                <div class="mb-4 border-b pb-4">
                    <h4 class="text-lg font-semibold mb-2">Informasi Dasar</h4>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <p><span class="font-medium">Kode Warna:</span> <span id="modal-code"></span></p>
                            <p><span class="font-medium">Deskripsi:</span> <span id="modal-desc"></span></p>
                            <p><span class="font-medium">Pembeli:</span> <span id="modal-buyer"></span></p>
                        </div>
                        <div>
                            <p><span class="font-medium">Koleksi:</span> <span id="modal-collection_surabaya"></span></p>
                            <p><span class="font-medium">Lemari:</span> <span id="modal-lemari"></span></p>
                            <p><span class="font-medium">Status:</span> <span id="modal-status"></span></p>
                            <div class="flex items-center mt-2" id="modal-hex-container">
                                <span class="font-medium mr-2">Warna:</span>
                                <div id="modal-color-box" class="w-6 h-6 rounded border border-gray-300 mr-2"></div>
                                <span id="modal-hex"></span>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="mb-4 border-b pb-4">
                    <h4 class="text-lg font-semibold mb-2">Komponen</h4>
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nama Komponen</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Jumlah</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tersedia</th>
                                </tr>
                            </thead>
                            <tbody id="modal-components" class="bg-white divide-y divide-gray-200">
                                <!-- Components will be populated here -->
                            </tbody>
                        </table>
                    </div>
                </div>
                
                <div>
                    <h4 class="text-lg font-semibold mb-2">Stok Barang</h4>
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kode Barang</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Komponen</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Stok #</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Lokasi</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Rak</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
                                </tr>
                            </thead>
                            <tbody id="modal-stock" class="bg-white divide-y divide-gray-200">
                                <!-- Stock items will be populated here -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<script>
// Variables for color code checking in edit form
let editColorCodeCheckTimeout;
let isEditColorCodeValid = false;
let currentEditColorId = 0;

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

// Modal functionality
const modal = document.getElementById('colorDetailsModal');
const closeModal = document.getElementById('closeModal');
const editModal = document.getElementById('editColorModal');
const closeEditModal = document.getElementById('closeEditModal');
const cancelEditBtn = document.getElementById('cancelEditBtn');

closeModal.addEventListener('click', function() {
    modal.classList.add('hidden');
});

closeEditModal.addEventListener('click', function() {
    editModal.classList.add('hidden');
});

cancelEditBtn.addEventListener('click', function() {
    editModal.classList.add('hidden');
});

// Close modals when clicking outside the modal content
modal.addEventListener('click', function(event) {
    if (event.target === modal) {
        modal.classList.add('hidden');
    }
});

editModal.addEventListener('click', function(event) {
    if (event.target === editModal) {
        editModal.classList.add('hidden');
    }
});

// Function to check if color code exists (for edit form)
function checkEditColorCode(colorCode, excludeId) {
    if (!colorCode.trim()) {
        hideEditColorCodeStatus();
        return;
    }
    
    showEditColorCodeLoading();
    
    fetch(`color_list_it.php?check_color_code=${encodeURIComponent(colorCode.trim())}&exclude_id=${excludeId}`)
        .then(response => response.json())
        .then(data => {
            if (data.exists) {
                showEditColorCodeExists();
                isEditColorCodeValid = false;
            } else {
                showEditColorCodeAvailable();
                isEditColorCodeValid = true;
            }
        })
        .catch(error => {
            console.error('Error checking color code:', error);
            hideEditColorCodeStatus();
            isEditColorCodeValid = false;
        });
}

// Edit form color code status functions
function showEditColorCodeLoading() {
    document.getElementById('edit-color-code-status').classList.remove('hidden');
    document.getElementById('edit-color-code-loading').classList.remove('hidden');
    document.getElementById('edit-color-code-available').classList.add('hidden');
    document.getElementById('edit-color-code-exists').classList.add('hidden');
    document.getElementById('edit-color-code-message').classList.add('hidden');
    document.getElementById('edit-color-code-error').classList.add('hidden');
    document.getElementById('edit-color-code-success').classList.add('hidden');
}

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

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

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

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

// 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 3 seconds
    setTimeout(() => {
        notification.remove();
    }, 3000);
}

// Function to edit color
function editColor(colorId) {
    currentEditColorId = colorId;
    
    // Fetch color details
    fetch('color_details_it.php?id=' + colorId)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            // Populate edit form
            document.getElementById('edit_color_id').value = data.color.id;
            document.getElementById('edit_code_color').value = data.color.code_color;
            document.getElementById('edit_deskripsi').value = data.color.deskripsi;
            document.getElementById('edit_lemari').value = data.color.lemari;
            document.getElementById('edit_status').value = data.color.status;
            document.getElementById('edit_kode_warna_hex').value = data.color.kode_warna_hex || '';
            document.getElementById('edit_keterangan_warna').value = data.color.keterangan_warna || '';
            
            // Reset validation status
            hideEditColorCodeStatus();
            isEditColorCodeValid = true; // Assume valid for existing code
            
            // Show edit modal
            editModal.classList.remove('hidden');
        })
        .catch(error => {
            console.error('Error fetching color details:', error);
            showNotification('red', 'Terjadi kesalahan saat mengambil detail warna');
        });
}

// Handle edit form submission
document.getElementById('editColorForm').addEventListener('submit', function(event) {
    event.preventDefault();
    
    const colorCode = document.getElementById('edit_code_color').value.trim();
    
    // Check if color code is valid (client-side validation)
    if (!isEditColorCodeValid && colorCode) {
        alert('Kode warna sudah ada di dalam database. Silakan gunakan kode warna yang berbeda.');
        return;
    }
    
    // Validate lemari (should be a single letter A-Z)
    const lemari = document.getElementById('edit_lemari').value;
    if (!/^[A-Za-z]$/.test(lemari)) {
        alert('Lemari harus berupa 1 huruf abjad (A-Z)');
        return;
    }
    
    // Validate color_hex (if provided)
    const hexCode = document.getElementById('edit_kode_warna_hex').value;
    if (hexCode && !/^[0-9A-Fa-f]{6}$/.test(hexCode)) {
        alert('Kode warna hex harus berupa 6 karakter hexadecimal');
        return;
    }
    
    // Submit form via AJAX
    const formData = new FormData(this);
    
    fetch('update_color_data.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('green', data.message);
            editModal.classList.add('hidden');
            // Reload the page to refresh the table
            location.reload();
        } else {
            showNotification('red', data.message);
        }
    })
    .catch(error => {
        console.error('Error updating color:', error);
        showNotification('red', 'Terjadi kesalahan saat mengupdate data warna');
    });
});

// Handle delete confirmation with AJAX for stock items
function confirmDelete(stockId, kodeBarang) {
    if (confirm(`Apakah Anda yakin ingin menghapus item stok ${kodeBarang}?`)) {
        console.log(`Attempting to delete stock ID: ${stockId}, Code: ${kodeBarang}`);
        
        // Use fetch API for AJAX request
        fetch(`delete_stock_item.php?id=${stockId}`, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => {
            console.log("Response received:", response);
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            console.log("Parsed data:", data);
            if (data.success) {
                // Show success notification
                showNotification('green', data.message);
                
                // Remove the row from the modal
                const stockItem = document.querySelector(`tr[data-stock-id="${stockId}"]`);
                if (stockItem) {
                    stockItem.remove();
                }
                
                // If no more items, show "no items" message
                const stockBody = document.getElementById('modal-stock');
                if (stockBody.querySelectorAll('tr').length === 0) {
                    const row = document.createElement('tr');
                    row.innerHTML = '<td colspan="7" class="px-6 py-4 text-center text-sm text-gray-500">Tidak ada stok barang</td>';
                    stockBody.appendChild(row);
                }
                
                // Refresh the color details to update components count too
                if (data.color_id) {
                    refreshColorDetails(data.color_id);
                }
            } else {
                // Show error notification
                showNotification('red', data.message || 'Terjadi kesalahan saat menghapus item');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('red', 'Terjadi kesalahan saat menghapus item. Periksa konsol untuk detail.');
        });
    }
}

// Handle delete confirmation with AJAX for entire color data
function confirmDeleteColor(colorId, colorCode) {
    if (confirm(`Apakah Anda yakin ingin menghapus data warna ${colorCode}?`)) {
        console.log(`Attempting to delete color ID: ${colorId}, Code: ${colorCode}`);
        
        // Use fetch API for AJAX request
        fetch(`delete_color_data.php?id=${colorId}`, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => {
            console.log("Response received:", response);
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            console.log("Parsed data:", data);
            if (data.success) {
                // Show success notification
                showNotification('green', data.message);
                
                // Remove the row from the main table
                const colorRow = document.querySelector(`tr[data-color-id="${colorId}"]`);
                if (colorRow) {
                    colorRow.remove();
                }
                
                // Close the modal if it's open
                if (!modal.classList.contains('hidden')) {
                    modal.classList.add('hidden');
                }
                
                // If no more colors, show "no colors" message
                const colorBody = document.getElementById('colorTableBody');
                if (colorBody.querySelectorAll('tr').length === 0) {
                    const row = document.createElement('tr');
                    row.innerHTML = '<td colspan="11" class="py-3 px-4 text-center text-gray-500">Tidak ada data warna</td>';
                    colorBody.appendChild(row);
                }
            } else {
                // Show error notification
                showNotification('red', data.message || 'Terjadi kesalahan saat menghapus data warna');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('red', 'Terjadi kesalahan saat menghapus data warna. Periksa konsol untuk detail.');
        });
    }
}

// Function to refresh color details
function refreshColorDetails(colorId) {
    fetch('color_details_it.php?id=' + colorId)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            // Update components table
            const componentsBody = document.getElementById('modal-components');
            componentsBody.innerHTML = '';
            
            if (data.components && data.components.length > 0) {
                data.components.forEach(comp => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${comp.component_name}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${comp.quantity}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${comp.available_quantity}</td>
                    `;
                    componentsBody.appendChild(row);
                });
            } else {
                const row = document.createElement('tr');
                row.innerHTML = '<td colspan="3" class="px-6 py-4 text-center text-sm text-gray-500">Tidak ada komponen</td>';
                componentsBody.appendChild(row);
            }
            
            // Update main table component and stock counts
            const mainTableRow = document.querySelector(`tr[data-color-id="${colorId}"]`);
            if (mainTableRow) {
                const componentCountSpan = mainTableRow.querySelector('td:nth-child(9) span');
                if (componentCountSpan) {
                    componentCountSpan.textContent = data.components ? data.components.length : 0;
                }
                
                const stockCountSpan = mainTableRow.querySelector('td:nth-child(10) span');
                if (stockCountSpan) {
                    stockCountSpan.textContent = data.stock_items ? data.stock_items.length : 0;
                }
            }
        })
        .catch(error => {
            console.error('Error refreshing color details:', error);
        });
}

// Show color details when clicking on a color code
document.querySelectorAll('.show-details').forEach(function(link) {
    link.addEventListener('click', function(e) {
        e.preventDefault();
        const colorId = this.dataset.colorId;
        
        // Fetch color details using AJAX
        fetch('color_details_it.php?id=' + colorId)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                // Populate modal with data
                document.getElementById('modal-color-code').textContent = data.color.code_color;
                document.getElementById('modal-code').textContent = data.color.code_color;
                document.getElementById('modal-desc').textContent = data.color.deskripsi;
                document.getElementById('modal-buyer').textContent = data.color.nama_buyer;
                document.getElementById('modal-collection_surabaya').textContent = data.color.nama_collection_surabaya;
                document.getElementById('modal-lemari').textContent = data.color.lemari;
                
                // Set status with appropriate styling
                const statusSpan = document.getElementById('modal-status');
                statusSpan.textContent = data.color.status;
                statusSpan.className = '';
                if (data.color.status === 'Hijau') {
                    statusSpan.classList.add('px-2', 'py-1', 'rounded-full', 'text-xs', 'bg-green-100', 'text-green-800');
                } else if (data.color.status === 'Kuning') {
                    statusSpan.classList.add('px-2', 'py-1', 'rounded-full', 'text-xs', 'bg-yellow-100', 'text-yellow-800');
                } else if (data.color.status === 'Merah') {
                    statusSpan.classList.add('px-2', 'py-1', 'rounded-full', 'text-xs', 'bg-red-100', 'text-red-800');
                }
                
                // Set color hex if available
                const hexContainer = document.getElementById('modal-hex-container');
                if (data.color.kode_warna_hex) {
                    hexContainer.classList.remove('hidden');
                    document.getElementById('modal-color-box').style.backgroundColor = '#' + data.color.kode_warna_hex;
                    document.getElementById('modal-hex').textContent = '#' + data.color.kode_warna_hex;
                } else {
                    hexContainer.classList.add('hidden');
                }
                
                // Populate components table
                const componentsBody = document.getElementById('modal-components');
                componentsBody.innerHTML = '';
                
                if (data.components && data.components.length > 0) {
                    data.components.forEach(comp => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${comp.component_name}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${comp.quantity}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${comp.available_quantity}</td>
                        `;
                        componentsBody.appendChild(row);
                    });
                } else {
                    const row = document.createElement('tr');
                    row.innerHTML = '<td colspan="3" class="px-6 py-4 text-center text-sm text-gray-500">Tidak ada komponen</td>';
                    componentsBody.appendChild(row);
                }
                
                // Populate stock items table
                const stockBody = document.getElementById('modal-stock');
                stockBody.innerHTML = '';
                
                if (data.stock_items && data.stock_items.length > 0) {
                    // Sort by rack_no for better organization
                    data.stock_items.sort((a, b) => a.rack_no.localeCompare(b.rack_no));
                    
                    data.stock_items.forEach(item => {
                        const row = document.createElement('tr');
                        // Add data-stock-id for AJAX deletion
                        row.setAttribute('data-stock-id', item.id);
                        
                        // Set status class
                        let statusClass = '';
                        if (item.status === 'Tersedia') {
                            statusClass = 'bg-green-100 text-green-800';
                        } else if (item.status === 'Dipinjam') {
                            statusClass = 'bg-blue-100 text-blue-800';
                        } else if (item.status === 'Rusak') {
                            statusClass = 'bg-red-100 text-red-800';
                        } else if (item.status === 'Expired') {
                            statusClass = 'bg-gray-100 text-gray-800';
                        } else if (item.status === 'Renew') {
                            statusClass = 'bg-yellow-100 text-yellow-800';
                        }
                        
                        // Determine if can delete
                        const canDelete = item.status === 'Tersedia';
                        const deleteButton = canDelete 
                            ? `<button onclick="confirmDelete(${item.id}, '${item.kode_barang}')" class="text-red-600 hover:text-red-900"><i class="fas fa-trash"></i> Hapus</button>` 
                            : `<span class="text-gray-400 cursor-not-allowed" title="Tidak dapat dihapus karena status bukan 'Tersedia'"><i class="fas fa-ban"></i> Tidak dapat dihapus</span>`;
                        
                        row.innerHTML = `
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${item.kode_barang}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${item.component_name}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${item.stock_number}</td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${statusClass}">
                                    ${item.status}
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${item.lokasi}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${item.rack_no}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm">
                                ${deleteButton}
                            </td>
                        `;
                        stockBody.appendChild(row);
                    });
                } else {
                    const row = document.createElement('tr');
                    row.innerHTML = '<td colspan="7" class="px-6 py-4 text-center text-sm text-gray-500">Tidak ada stok barang</td>';
                    stockBody.appendChild(row);
                }
                
                // Show modal
                modal.classList.remove('hidden');
            })
            .catch(error => {
                console.error('Error fetching color details:', error);
                showNotification('red', 'Terjadi kesalahan saat mengambil detail warna');
            });
    });
});
</script>

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