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

// Log activity using audit_logs
create_audit_log($conn, 'Rename Master Color Access', $it_id, 'it', 'IT user accessed rename master color page');

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

// Handle form submission
$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $color_id = isset($_POST['color_id']) ? intval($_POST['color_id']) : 0;
    $new_code_color = isset($_POST['new_code_color']) ? trim($_POST['new_code_color']) : '';
    $new_deskripsi = isset($_POST['new_deskripsi']) ? trim($_POST['new_deskripsi']) : '';
    $new_buyer_id = isset($_POST['new_buyer_id']) ? intval($_POST['new_buyer_id']) : 0;
    $new_keterangan_warna = isset($_POST['new_keterangan_warna']) ? trim($_POST['new_keterangan_warna']) : '';

    if ($color_id > 0 && !empty($new_code_color) && $new_buyer_id > 0) {
        try {
            $conn->begin_transaction();

            // Get old data for audit log
            $old_data_query = "SELECT mcp.*, b.nama_buyer as old_buyer_name, c.nama_collection 
                              FROM master_color_panel mcp 
                              JOIN buyers b ON mcp.buyer_id = b.id 
                              JOIN collections c ON mcp.collection_id = c.id 
                              WHERE mcp.id = ?";
            $old_stmt = $conn->prepare($old_data_query);
            $old_stmt->bind_param("i", $color_id);
            $old_stmt->execute();
            $old_data = $old_stmt->get_result()->fetch_assoc();
            $old_stmt->close();

            if (!$old_data) {
                throw new Exception("Color panel tidak ditemukan");
            }

            // Check if new code_color already exists for the buyer (excluding current record)
            $check_query = "SELECT id FROM master_color_panel WHERE code_color = ? AND buyer_id = ? AND id != ?";
            $check_stmt = $conn->prepare($check_query);
            $check_stmt->bind_param("sii", $new_code_color, $new_buyer_id, $color_id);
            $check_stmt->execute();
            if ($check_stmt->get_result()->num_rows > 0) {
                $check_stmt->close();
                throw new Exception("Code color sudah ada untuk buyer yang dipilih");
            }
            $check_stmt->close();

            // Get collection_id for new buyer (assuming Standard Collection)
            $collection_query = "SELECT id FROM collections WHERE buyer_id = ? AND nama_collection = 'Standard Collection'";
            $collection_stmt = $conn->prepare($collection_query);
            $collection_stmt->bind_param("i", $new_buyer_id);
            $collection_stmt->execute();
            $collection_result = $collection_stmt->get_result();
            
            if ($collection_result->num_rows == 0) {
                $collection_stmt->close();
                throw new Exception("Collection tidak ditemukan untuk buyer yang dipilih");
            }
            
            $new_collection_id = $collection_result->fetch_assoc()['id'];
            $collection_stmt->close();

            // Update master_color_panel
            $update_query = "UPDATE master_color_panel 
                           SET code_color = ?, deskripsi = ?, buyer_id = ?, collection_id = ?, keterangan_warna = ?
                           WHERE id = ?";
            $update_stmt = $conn->prepare($update_query);
            $update_stmt->bind_param("ssiisi", $new_code_color, $new_deskripsi, $new_buyer_id, $new_collection_id, $new_keterangan_warna, $color_id);
            
            if (!$update_stmt->execute()) {
                $update_stmt->close();
                throw new Exception("Gagal mengupdate master color panel");
            }
            $update_stmt->close();

            // Update keterangan in color_stock_items
            $update_stock_query = "UPDATE color_stock_items 
                                 SET keterangan = REPLACE(keterangan, ?, ?)
                                 WHERE color_id = ?";
            $old_prefix = $old_data['old_buyer_name'] . ' ' . $old_data['code_color'];
            $new_buyer_query = "SELECT nama_buyer FROM buyers WHERE id = ?";
            $buyer_stmt = $conn->prepare($new_buyer_query);
            $buyer_stmt->bind_param("i", $new_buyer_id);
            $buyer_stmt->execute();
            $new_buyer_name = $buyer_stmt->get_result()->fetch_assoc()['nama_buyer'];
            $buyer_stmt->close();
            
            $new_prefix = $new_buyer_name . ' ' . $new_code_color;
            
            $stock_stmt = $conn->prepare($update_stock_query);
            $stock_stmt->bind_param("ssi", $old_prefix, $new_prefix, $color_id);
            $stock_stmt->execute();
            $stock_stmt->close();

            // Create audit log
            $audit_details = "Updated master color panel ID: $color_id\n";
            $audit_details .= "Old: {$old_data['code_color']} - {$old_data['deskripsi']} (Buyer: {$old_data['old_buyer_name']})\n";
            $audit_details .= "New: $new_code_color - $new_deskripsi (Buyer: $new_buyer_name)";
            
            create_audit_log($conn, 'Rename Master Color', $it_id, 'it', $audit_details);

            $conn->commit();
            $success_message = "Master color berhasil diupdate!";

        } catch (Exception $e) {
            $conn->rollback();
            $error_message = "Error: " . $e->getMessage();
        }
    } else {
        $error_message = "Semua field harus diisi!";
    }
}

// Include header
include '../template_it/header.php';
?>

<!-- Main Content Area -->
<main class="flex-1 p-6 overflow-auto bg-gradient-to-br from-blue-100 via-teal-100 to-green-100">
    <!-- 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">Rename Master Color</h2>
        <p class="text-gray-600">Ubah nama master color panel dan pindahkan ke buyer lain</p>
    </div>

    <!-- Alert Messages -->
    <?php if ($success_message): ?>
        <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-6">
            <div class="flex items-center">
                <i class="fas fa-check-circle mr-2"></i>
                <?php echo htmlspecialchars($success_message); ?>
            </div>
        </div>
    <?php endif; ?>

    <?php if ($error_message): ?>
        <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6">
            <div class="flex items-center">
                <i class="fas fa-exclamation-circle mr-2"></i>
                <?php echo htmlspecialchars($error_message); ?>
            </div>
        </div>
    <?php endif; ?>

    <!-- Search Section -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">Cari Master Color Panel</h3>
        
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
            <div>
                <label for="search_buyer" class="block text-sm font-medium text-gray-700 mb-2">Filter Buyer</label>
                <select id="search_buyer" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">Semua Buyer</option>
                    <?php 
                    $buyers_result->data_seek(0); // Reset pointer
                    while($buyer = $buyers_result->fetch_assoc()): 
                    ?>
                        <option value="<?php echo $buyer['id']; ?>"><?php echo htmlspecialchars($buyer['nama_buyer']); ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
            
            <div>
                <label for="search_code" class="block text-sm font-medium text-gray-700 mb-2">Cari Code Color</label>
                <input type="text" id="search_code" placeholder="Masukkan code color..." 
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            
            <div class="flex items-end">
                <button onclick="loadColorPanels()" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors">
                    <i class="fas fa-search mr-2"></i>Cari
                </button>
                <button onclick="resetSearch()" class="ml-2 px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700 transition-colors">
                    <i class="fas fa-refresh mr-2"></i>Reset
                </button>
            </div>
        </div>

        <!-- Color Panels List -->
        <div id="color-panels-container">
            <div class="text-center text-gray-500 py-8">
                Klik "Cari" untuk menampilkan daftar master color panel
            </div>
        </div>
    </div>

    <!-- Rename Form -->
    <div id="rename-form-container" class="bg-white rounded-lg shadow-md p-6" style="display: none;">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">Form Rename Master Color</h3>
        
        <form method="POST" id="rename-form">
            <input type="hidden" name="color_id" id="form_color_id">
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Current Data Column -->
                <div>
                    <h4 class="text-md font-semibold text-gray-700 mb-4">Data Saat Ini</h4>
                    
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Code Color Lama</label>
                            <input type="text" id="current_code_color" readonly 
                                   class="w-full px-3 py-2 bg-gray-100 border border-gray-300 rounded-md">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Deskripsi Lama</label>
                            <input type="text" id="current_deskripsi" readonly 
                                   class="w-full px-3 py-2 bg-gray-100 border border-gray-300 rounded-md">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Buyer Lama</label>
                            <input type="text" id="current_buyer" readonly 
                                   class="w-full px-3 py-2 bg-gray-100 border border-gray-300 rounded-md">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Keterangan Warna Lama</label>
                            <textarea id="current_keterangan" readonly rows="3"
                                      class="w-full px-3 py-2 bg-gray-100 border border-gray-300 rounded-md"></textarea>
                        </div>
                    </div>
                </div>
                
                <!-- New Data Column -->
                <div>
                    <h4 class="text-md font-semibold text-gray-700 mb-4">Data Baru</h4>
                    
                    <div class="space-y-4">
                        <div>
                            <label for="new_code_color" class="block text-sm font-medium text-gray-700 mb-2">
                                Code Color Baru <span class="text-red-500">*</span>
                            </label>
                            <input type="text" name="new_code_color" id="new_code_color" required
                                   class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                        </div>
                        
                        <div>
                            <label for="new_deskripsi" class="block text-sm font-medium text-gray-700 mb-2">
                                Deskripsi Baru <span class="text-red-500">*</span>
                            </label>
                            <input type="text" name="new_deskripsi" id="new_deskripsi" required
                                   class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                        </div>
                        
                        <div>
                            <label for="new_buyer_id" class="block text-sm font-medium text-gray-700 mb-2">
                                Buyer Baru <span class="text-red-500">*</span>
                            </label>
                            <select name="new_buyer_id" id="new_buyer_id" required
                                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <option value="">Pilih Buyer</option>
                                <?php 
                                $buyers_result->data_seek(0); // Reset pointer
                                while($buyer = $buyers_result->fetch_assoc()): 
                                ?>
                                    <option value="<?php echo $buyer['id']; ?>"><?php echo htmlspecialchars($buyer['nama_buyer']); ?></option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        
                        <div>
                            <label for="new_keterangan_warna" class="block text-sm font-medium text-gray-700 mb-2">
                                Keterangan Warna Baru
                            </label>
                            <textarea name="new_keterangan_warna" id="new_keterangan_warna" rows="3"
                                      class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Action Buttons -->
            <div class="mt-6 flex space-x-4">
                <button type="submit" class="px-6 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition-colors">
                    <i class="fas fa-save mr-2"></i>Update Master Color
                </button>
                <button type="button" onclick="cancelRename()" class="px-6 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700 transition-colors">
                    <i class="fas fa-times mr-2"></i>Cancel
                </button>
            </div>
        </form>
    </div>
</main>

<!-- Confirmation Modal -->
<div id="confirmModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-lg max-w-md w-full">
            <div class="p-4 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-800">Konfirmasi Update</h3>
            </div>
            <div class="p-4">
                <p class="text-gray-600 mb-4">
                    Apakah Anda yakin ingin mengupdate master color panel ini? 
                    Semua stock items terkait juga akan diupdate.
                </p>
                <div id="confirm-details" class="bg-gray-50 p-3 rounded text-sm">
                    <!-- Details will be populated here -->
                </div>
            </div>
            <div class="p-4 border-t border-gray-200 flex justify-end space-x-2">
                <button onclick="closeConfirmModal()" class="px-4 py-2 bg-gray-600 text-white rounded hover:bg-gray-700">
                    Cancel
                </button>
                <button onclick="confirmUpdate()" class="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700">
                    Ya, Update
                </button>
            </div>
        </div>
    </div>
</div>

<script>
// Load color panels with AJAX
function loadColorPanels() {
    const buyer_id = document.getElementById('search_buyer').value;
    const code_color = document.getElementById('search_code').value;
    
    const params = new URLSearchParams();
    if (buyer_id) params.append('buyer_id', buyer_id);
    if (code_color) params.append('code_color', code_color);
    
    // Show loading
    document.getElementById('color-panels-container').innerHTML = 
        '<div class="flex justify-center items-center p-8">' +
        '<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>' +
        '<span class="ml-2 text-gray-600">Memuat data...</span>' +
        '</div>';
    
    fetch('ajax_get_color_panels.php?' + params.toString())
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayColorPanels(data.data);
            } else {
                document.getElementById('color-panels-container').innerHTML = 
                    '<div class="p-8 text-center text-red-600">Terjadi kesalahan: ' + data.message + '</div>';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('color-panels-container').innerHTML = 
                '<div class="p-8 text-center text-red-600">Terjadi kesalahan saat memuat data</div>';
        });
}

// Display color panels
function displayColorPanels(panels) {
    if (panels.length === 0) {
        document.getElementById('color-panels-container').innerHTML = 
            '<div class="text-center text-gray-500 py-8">Tidak ada master color panel yang ditemukan</div>';
        return;
    }
    
    let html = '<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">';
    
    panels.forEach(panel => {
        html += `
            <div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
                <div class="flex justify-between items-start mb-2">
                    <h4 class="font-semibold text-gray-800">${panel.code_color}</h4>
                    <span class="px-2 py-1 text-xs rounded-full bg-${getStatusColor(panel.status)}-100 text-${getStatusColor(panel.status)}-800">
                        ${panel.status}
                    </span>
                </div>
                <p class="text-gray-600 text-sm mb-2">${panel.deskripsi || 'No description'}</p>
                <p class="text-gray-500 text-xs mb-2">Buyer: ${panel.buyer_name}</p>
                <p class="text-gray-500 text-xs mb-3">Lemari: ${panel.lemari || 'N/A'}</p>
                <button onclick="selectForRename(${panel.id}, '${panel.code_color}', '${panel.deskripsi || ''}', '${panel.buyer_name}', '${panel.keterangan_warna || ''}')" 
                        class="w-full px-3 py-2 bg-blue-600 text-white text-sm rounded hover:bg-blue-700 transition-colors">
                    <i class="fas fa-edit mr-1"></i>Rename
                </button>
            </div>
        `;
    });
    
    html += '</div>';
    document.getElementById('color-panels-container').innerHTML = html;
}

// Get status color for styling
function getStatusColor(status) {
    switch(status) {
        case 'Hijau': return 'green';
        case 'Kuning': return 'yellow';
        case 'Merah': return 'red';
        default: return 'gray';
    }
}

// Select color panel for rename
function selectForRename(id, codeColor, deskripsi, buyerName, keteranganWarna) {
    document.getElementById('form_color_id').value = id;
    document.getElementById('current_code_color').value = codeColor;
    document.getElementById('current_deskripsi').value = deskripsi;
    document.getElementById('current_buyer').value = buyerName;
    document.getElementById('current_keterangan').value = keteranganWarna;
    
    // Pre-fill new fields with current values
    document.getElementById('new_code_color').value = codeColor;
    document.getElementById('new_deskripsi').value = deskripsi;
    document.getElementById('new_keterangan_warna').value = keteranganWarna;
    
    // Show rename form
    document.getElementById('rename-form-container').style.display = 'block';
    document.getElementById('rename-form-container').scrollIntoView({ behavior: 'smooth' });
}

// Cancel rename
function cancelRename() {
    document.getElementById('rename-form-container').style.display = 'none';
    document.getElementById('rename-form').reset();
}

// Reset search
function resetSearch() {
    document.getElementById('search_buyer').value = '';
    document.getElementById('search_code').value = '';
    document.getElementById('color-panels-container').innerHTML = 
        '<div class="text-center text-gray-500 py-8">Klik "Cari" untuk menampilkan daftar master color panel</div>';
    cancelRename();
}

// Form submission with confirmation
document.getElementById('rename-form').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const currentCode = document.getElementById('current_code_color').value;
    const newCode = document.getElementById('new_code_color').value;
    const currentBuyer = document.getElementById('current_buyer').value;
    const newBuyerSelect = document.getElementById('new_buyer_id');
    const newBuyer = newBuyerSelect.options[newBuyerSelect.selectedIndex].text;
    
    document.getElementById('confirm-details').innerHTML = `
        <strong>Perubahan yang akan dilakukan:</strong><br>
        Code Color: ${currentCode} → ${newCode}<br>
        Buyer: ${currentBuyer} → ${newBuyer}<br><br>
        <em>Catatan: Semua stock items terkait juga akan diupdate.</em>
    `;
    
    document.getElementById('confirmModal').classList.remove('hidden');
});

// Close confirmation modal
function closeConfirmModal() {
    document.getElementById('confirmModal').classList.add('hidden');
}

// Confirm update
function confirmUpdate() {
    closeConfirmModal();
    document.getElementById('rename-form').submit();
}

// Close modal when clicking outside
document.getElementById('confirmModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeConfirmModal();
    }
});

// Load panels on page load if there are URL parameters
document.addEventListener('DOMContentLoaded', function() {
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.has('auto_load')) {
        loadColorPanels();
    }
});
</script>

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