<?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 = "Change Color Description - IT";

// Log activity
create_audit_log($conn, 'Color Description Access', $it_id, 'it', 'IT user accessed color description management');

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_description'])) {
    $panel_id = intval($_POST['panel_id']);
    $new_description = trim($_POST['new_description']);
    $panel_type = $_POST['panel_type'];
    
    if ($panel_id > 0 && !empty($new_description)) {
        $conn->begin_transaction();
        
        try {
            if ($panel_type === 'master_color') {
                // Update master_color table
                $update_master = $conn->prepare("UPDATE master_color SET keterangan_warna = ? WHERE id = ?");
                $update_master->bind_param("si", $new_description, $panel_id);
                $update_master->execute();
                $update_master->close();
                
                // Also update related copy panels
                $update_copies = $conn->prepare("UPDATE master_color_panel SET deskripsi = ? WHERE master_color_id = ?");
                $update_copies->bind_param("si", $new_description, $panel_id);
                $update_copies->execute();
                $update_copies->close();
                
                $success_message = "Deskripsi master color dan copy panel terkait berhasil diperbarui!";
                $log_detail = "Updated master color description (ID: $panel_id) to: $new_description";
            } else {
                // Update master_color_panel table only
                $update_panel = $conn->prepare("UPDATE master_color_panel SET deskripsi = ? WHERE id = ?");
                $update_panel->bind_param("si", $new_description, $panel_id);
                $update_panel->execute();
                $update_panel->close();
                
                $success_message = "Deskripsi copy panel berhasil diperbarui!";
                $log_detail = "Updated copy panel description (ID: $panel_id) to: $new_description";
            }
            
            $conn->commit();
            
            // Log the update
            create_audit_log($conn, 'Update Color Description', $it_id, 'it', $log_detail);
            
        } catch (Exception $e) {
            $conn->rollback();
            $error_message = "Gagal memperbarui deskripsi: " . $e->getMessage();
        }
    } else {
        $error_message = "Data tidak valid. Pastikan semua field terisi dengan benar.";
    }
}

// Get filter parameters
$filter_buyer = isset($_GET['buyer_id']) ? intval($_GET['buyer_id']) : 0;
$search_color = isset($_GET['search_color']) ? trim($_GET['search_color']) : '';

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

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

<!-- Main Content Area -->
<main class="flex-1 p-2 sm: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-3 sm:p-6 mb-4 sm:mb-6">
        <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center">
            <div>
                <h2 class="text-xl sm:text-2xl font-bold text-gray-800 mb-2 sm:mb-4">
                    <i class="fas fa-edit text-blue-600 mr-2"></i>
                    Change Color Description - IT Support
                </h2>
                <p class="text-gray-600 text-sm sm:text-base">Kelola deskripsi warna untuk master color dan copy panel</p>
            </div>
            <div class="mt-3 sm:mt-0">
                <a href="dashboard_it.php" class="bg-gray-500 hover:bg-gray-600 text-white font-medium py-2 px-4 text-sm sm:text-base rounded-md transition duration-150 ease-in-out shadow-md hover:shadow-lg">
                    <i class="fas fa-arrow-left mr-2"></i>Kembali
                </a>
            </div>
        </div>
    </div>
    
    <?php if (isset($success_message)): ?>
    <div class="bg-green-100 border-l-4 border-green-400 text-green-700 px-3 py-2 sm:px-4 sm:py-3 rounded-lg relative mb-4 sm:mb-6 shadow-md" role="alert">
        <div class="flex">
            <div class="flex-shrink-0">
                <i class="fas fa-check-circle text-green-400"></i>
            </div>
            <div class="ml-3">
                <strong class="font-bold">Success!</strong>
                <span class="block sm:inline"><?php echo $success_message; ?></span>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <?php if (isset($error_message)): ?>
    <div class="bg-red-100 border-l-4 border-red-400 text-red-700 px-3 py-2 sm:px-4 sm:py-3 rounded-lg relative mb-4 sm:mb-6 shadow-md" role="alert">
        <div class="flex">
            <div class="flex-shrink-0">
                <i class="fas fa-times-circle text-red-400"></i>
            </div>
            <div class="ml-3">
                <strong class="font-bold">Error!</strong>
                <span class="block sm:inline"><?php echo $error_message; ?></span>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- Filters Section -->
    <div class="bg-white rounded-lg shadow-md p-3 sm:p-6 mb-4 sm:mb-6">
        <h3 class="text-base sm:text-lg font-semibold text-gray-700 mb-3 sm:mb-4">
            <i class="fas fa-filter text-blue-600 mr-2"></i>Filter Data
        </h3>
        
        <form id="filter_form" method="get" action="">
            <div class="grid grid-cols-1 md:grid-cols-3 gap-3 sm:gap-4">
                <!-- Buyer Filter -->
                <div>
                    <label for="buyer_filter" class="block text-sm font-medium text-gray-700 mb-1">Buyer</label>
                    <select id="buyer_filter" name="buyer_id" class="w-full rounded-md border border-gray-300 shadow-sm px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        <option value="">Semua Buyer</option>
                        <?php while ($buyer = $buyers_result->fetch_assoc()): ?>
                            <option value="<?php echo $buyer['id']; ?>" <?php echo ($filter_buyer == $buyer['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($buyer['nama_buyer'] . ' (' . $buyer['kode_buyer'] . ')'); ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>
                
                <!-- Search Color -->
                <div>
                    <label for="search_color" class="block text-sm font-medium text-gray-700 mb-1">Cari Color Code</label>
                    <input type="text" id="search_color" name="search_color" placeholder="Masukkan kode color..." 
                           value="<?php echo htmlspecialchars($search_color); ?>"
                           class="w-full rounded-md border border-gray-300 shadow-sm px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                </div>
                
                <!-- Action Buttons -->
                <div class="flex items-end space-x-2">
                    <button type="submit" class="bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 text-sm rounded-md transition duration-150 ease-in-out w-full sm:w-auto shadow-md hover:shadow-lg">
                        <i class="fas fa-search mr-2"></i>Filter
                    </button>
                    <button type="button" onclick="clearFilters()" class="bg-gray-500 hover:bg-gray-600 text-white font-medium py-2 px-4 text-sm rounded-md transition duration-150 ease-in-out w-full sm:w-auto shadow-md hover:shadow-lg">
                        <i class="fas fa-eraser mr-2"></i>Clear
                    </button>
                </div>
            </div>
        </form>
    </div>
    
    <!-- Color Data Section -->
    <div class="bg-white rounded-lg shadow-md p-3 sm:p-6">
        <h3 class="text-lg sm:text-xl font-semibold text-gray-800 mb-3 sm:mb-4">
            <i class="fas fa-palette text-blue-600 mr-2"></i>Color Description Management
        </h3>
        
        <?php
        // Build query based on filters
        $where_clauses = [];
        $params = [];
        $param_types = "";
        
        // Get master colors with their copy panels
        $query = "
            SELECT 
                mc.id as master_id,
                mc.code_color as master_code,
                mc.name_color,
                mc.keterangan_warna as master_description,
                mcp.id as panel_id,
                mcp.code_color as panel_code,
                mcp.deskripsi as panel_description,
                mcp.panel_type,
                b.nama_buyer,
                b.kode_buyer,
                col.nama_collection
            FROM master_color mc
            LEFT JOIN master_color_panel mcp ON mc.id = mcp.master_color_id
            JOIN buyers b ON mc.buyer_id = b.id
            JOIN collections col ON mc.collection_id = col.id
        ";
        
        // Add buyer filter if set
        if ($filter_buyer > 0) {
            $where_clauses[] = "mc.buyer_id = ?";
            $params[] = $filter_buyer;
            $param_types .= "i";
        }
        
        // Add search filter if set
        if (!empty($search_color)) {
            $where_clauses[] = "(mc.code_color LIKE ? OR mcp.code_color LIKE ?)";
            $search_param = '%' . $search_color . '%';
            $params[] = $search_param;
            $params[] = $search_param;
            $param_types .= "ss";
        }
        
        // Add where clause if any filters are set
        if (!empty($where_clauses)) {
            $query .= " WHERE " . implode(" AND ", $where_clauses);
        }
        
        $query .= " ORDER BY b.nama_buyer, mc.code_color, mcp.panel_type DESC";
        
        // Prepare and execute the query
        $stmt = $conn->prepare($query);
        
        if (!empty($params)) {
            $stmt->bind_param($param_types, ...$params);
        }
        
        $stmt->execute();
        $result = $stmt->get_result();
        
        // Group results by master color
        $grouped_data = [];
        while ($row = $result->fetch_assoc()) {
            $master_id = $row['master_id'];
            
            if (!isset($grouped_data[$master_id])) {
                $grouped_data[$master_id] = [
                    'master_id' => $row['master_id'],
                    'master_code' => $row['master_code'],
                    'name_color' => $row['name_color'],
                    'master_description' => $row['master_description'],
                    'buyer_name' => $row['nama_buyer'],
                    'kode_buyer' => $row['kode_buyer'],
                    'collection' => $row['nama_collection'],
                    'copy_panels' => []
                ];
            }
            
            if ($row['panel_id']) {
                $grouped_data[$master_id]['copy_panels'][] = [
                    'panel_id' => $row['panel_id'],
                    'panel_code' => $row['panel_code'],
                    'panel_description' => $row['panel_description'],
                    'panel_type' => $row['panel_type']
                ];
            }
        }
        
        if (empty($grouped_data)):
        ?>
            <div class="bg-yellow-100 border-l-4 border-yellow-400 text-yellow-800 p-4 rounded-lg shadow-inner">
                <p class="text-center font-medium">
                    <i class="fas fa-info-circle mr-2"></i>Tidak ada data yang ditemukan sesuai filter Anda.
                </p>
            </div>
        <?php else: ?>
            <!-- Desktop View -->
            <div class="hidden md:block overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-blue-50">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Buyer</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Color Code</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Type</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Current Description</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Action</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <?php foreach ($grouped_data as $master): ?>
                            <!-- Master Color Row -->
                            <tr class="hover:bg-gray-50 transition-colors duration-150">
                                <td class="px-4 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-gray-900"><?php echo htmlspecialchars($master['buyer_name']); ?></div>
                                    <div class="text-sm text-gray-500"><?php echo htmlspecialchars($master['kode_buyer']); ?></div>
                                </td>
                                <td class="px-4 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-gray-900"><?php echo htmlspecialchars($master['master_code']); ?></div>
                                    <div class="text-sm text-gray-500"><?php echo htmlspecialchars($master['name_color']); ?></div>
                                </td>
                                <td class="px-4 py-4 whitespace-nowrap">
                                    <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                        <i class="fas fa-crown mr-1"></i>Master Color
                                    </span>
                                </td>
                                <td class="px-4 py-4">
                                    <div class="text-sm text-gray-900 max-w-xs break-words">
                                        <?php echo htmlspecialchars($master['master_description'] ?: 'No description'); ?>
                                    </div>
                                </td>
                                <td class="px-4 py-4 whitespace-nowrap text-sm font-medium">
                                    <button onclick="openEditModal(<?php echo $master['master_id']; ?>, 'master_color', '<?php echo addslashes($master['master_code']); ?>', '<?php echo addslashes($master['master_description']); ?>')" 
                                            class="text-blue-600 hover:text-blue-900 bg-blue-100 px-3 py-1 rounded-md text-xs shadow-sm hover:shadow">
                                        <i class="fas fa-edit mr-1"></i>Edit
                                    </button>
                                </td>
                            </tr>
                            
                            <!-- Copy Panel Rows -->
                            <?php foreach ($master['copy_panels'] as $panel): ?>
                            <tr class="hover:bg-gray-50 transition-colors duration-150 bg-gray-25">
                                <td class="px-4 py-4 whitespace-nowrap">
                                    <div class="text-sm text-gray-500 pl-4">└ Copy Panel</div>
                                </td>
                                <td class="px-4 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-gray-700 pl-4"><?php echo htmlspecialchars($panel['panel_code']); ?></div>
                                </td>
                                <td class="px-4 py-4 whitespace-nowrap">
                                    <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                        <i class="fas fa-copy mr-1"></i><?php echo ucfirst($panel['panel_type']); ?>
                                    </span>
                                </td>
                                <td class="px-4 py-4">
                                    <div class="text-sm text-gray-700 max-w-xs break-words pl-4">
                                        <?php echo htmlspecialchars($panel['panel_description'] ?: 'No description'); ?>
                                    </div>
                                </td>
                                <td class="px-4 py-4 whitespace-nowrap text-sm font-medium">
                                    <button onclick="openEditModal(<?php echo $panel['panel_id']; ?>, 'copy_panel', '<?php echo addslashes($panel['panel_code']); ?>', '<?php echo addslashes($panel['panel_description']); ?>')" 
                                            class="text-green-600 hover:text-green-900 bg-green-100 px-3 py-1 rounded-md text-xs shadow-sm hover:shadow">
                                        <i class="fas fa-edit mr-1"></i>Edit
                                    </button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            
            <!-- Mobile View -->
            <div class="block md:hidden space-y-4">
                <?php foreach ($grouped_data as $master): ?>
                    <div class="border border-gray-200 rounded-lg p-4 shadow-sm">
                        <!-- Master Color Card -->
                        <div class="mb-3 pb-3 border-b border-gray-200">
                            <div class="flex justify-between items-start mb-2">
                                <div>
                                    <div class="font-medium text-gray-900"><?php echo htmlspecialchars($master['master_code']); ?></div>
                                    <div class="text-sm text-gray-500"><?php echo htmlspecialchars($master['buyer_name']); ?></div>
                                </div>
                                <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                    <i class="fas fa-crown mr-1"></i>Master
                                </span>
                            </div>
                            <div class="text-sm text-gray-700 mb-2">
                                <strong>Description:</strong> <?php echo htmlspecialchars($master['master_description'] ?: 'No description'); ?>
                            </div>
                            <button onclick="openEditModal(<?php echo $master['master_id']; ?>, 'master_color', '<?php echo addslashes($master['master_code']); ?>', '<?php echo addslashes($master['master_description']); ?>')" 
                                    class="text-blue-600 hover:text-blue-900 bg-blue-100 px-3 py-1 rounded-md text-xs shadow-sm hover:shadow">
                                <i class="fas fa-edit mr-1"></i>Edit Master
                            </button>
                        </div>
                        
                        <!-- Copy Panels -->
                        <?php foreach ($master['copy_panels'] as $panel): ?>
                        <div class="ml-4 mb-2 p-3 bg-gray-50 rounded border-l-4 border-green-500">
                            <div class="flex justify-between items-start mb-2">
                                <div>
                                    <div class="font-medium text-gray-800"><?php echo htmlspecialchars($panel['panel_code']); ?></div>
                                    <div class="text-xs text-gray-500">Copy Panel</div>
                                </div>
                                <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                    <i class="fas fa-copy mr-1"></i><?php echo ucfirst($panel['panel_type']); ?>
                                </span>
                            </div>
                            <div class="text-sm text-gray-700 mb-2">
                                <strong>Description:</strong> <?php echo htmlspecialchars($panel['panel_description'] ?: 'No description'); ?>
                            </div>
                            <button onclick="openEditModal(<?php echo $panel['panel_id']; ?>, 'copy_panel', '<?php echo addslashes($panel['panel_code']); ?>', '<?php echo addslashes($panel['panel_description']); ?>')" 
                                    class="text-green-600 hover:text-green-900 bg-green-100 px-3 py-1 rounded-md text-xs shadow-sm hover:shadow">
                                <i class="fas fa-edit mr-1"></i>Edit Copy
                            </button>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</main>

<!-- Edit Description Modal -->
<div id="editModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden flex items-center justify-center p-4">
    <div class="bg-white rounded-lg shadow-xl max-w-md w-full">
        <div class="p-4 border-b border-gray-200">
            <h3 class="text-lg font-semibold text-gray-800">
                <i class="fas fa-edit text-blue-600 mr-2"></i>
                Edit Description
            </h3>
        </div>
        <form id="editForm" method="post" action="">
            <div class="p-4 space-y-4">
                <input type="hidden" id="edit_panel_id" name="panel_id">
                <input type="hidden" id="edit_panel_type" name="panel_type">
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Color Code</label>
                    <div id="edit_color_code" class="px-3 py-2 bg-gray-100 border border-gray-300 rounded-md text-gray-700 font-mono"></div>
                </div>
                
                <div>
                    <label for="edit_description" class="block text-sm font-medium text-gray-700 mb-2">Description</label>
                    <textarea id="edit_description" name="new_description" rows="4" required 
                              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                              placeholder="Masukkan deskripsi baru..."></textarea>
                </div>
                
                <div class="bg-yellow-50 border-l-4 border-yellow-400 p-3 rounded">
                    <div class="flex">
                        <div class="flex-shrink-0">
                            <i class="fas fa-info-circle text-yellow-400"></i>
                        </div>
                        <div class="ml-3">
                            <p class="text-sm text-yellow-700">
                                <span class="font-medium">Catatan:</span> Hanya deskripsi yang dapat diubah. Color code tidak dapat dimodifikasi.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="p-4 border-t border-gray-200 flex justify-end space-x-2">
                <button type="button" onclick="closeEditModal()" class="px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400 transition">
                    Batal
                </button>
                <button type="submit" name="update_description" class="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition">
                    <i class="fas fa-save mr-2"></i>Simpan
                </button>
            </div>
        </form>
    </div>
</div>

<script>
// Function to clear filters
function clearFilters() {
    document.getElementById('buyer_filter').value = '';
    document.getElementById('search_color').value = '';
    document.getElementById('filter_form').submit();
}

// Function to open edit modal
function openEditModal(panelId, panelType, colorCode, currentDescription) {
    document.getElementById('edit_panel_id').value = panelId;
    document.getElementById('edit_panel_type').value = panelType;
    document.getElementById('edit_color_code').textContent = colorCode;
    document.getElementById('edit_description').value = currentDescription || '';
    document.getElementById('editModal').classList.remove('hidden');
    
    // Focus on textarea
    setTimeout(() => {
        document.getElementById('edit_description').focus();
    }, 100);
}

// Function to close edit modal
function closeEditModal() {
    document.getElementById('editModal').classList.add('hidden');
    document.getElementById('editForm').reset();
}

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

// Handle escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeEditModal();
    }
});
</script>

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