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

// Log activity
create_audit_log($conn, 'Rack Rename Access', $it_id, 'it', 'IT user accessed rack rename page');

// Handle form submission
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'auto_rename' && isset($_POST['master_color_id'])) {
        $master_color_id = (int)$_POST['master_color_id'];
        
        try {
            // Start transaction
            $conn->begin_transaction();
            
            // Get master color info first
            $master_query = "SELECT mc.code_color, mc.name_color FROM master_color mc WHERE mc.id = ?";
            $stmt = $conn->prepare($master_query);
            $stmt->bind_param("i", $master_color_id);
            $stmt->execute();
            $master_result = $stmt->get_result();
            $master_data = $master_result->fetch_assoc();
            $stmt->close();
            
            if (!$master_data) {
                throw new Exception("Master color tidak ditemukan");
            }
            
            // Get all copy panels for this master color ordered by id
            $query = "SELECT csi.id, csi.color_id, mcp.lemari, mcp.code_color
                     FROM color_stock_items csi
                     JOIN master_color_panel mcp ON csi.color_id = mcp.id
                     WHERE csi.item_type = 'copy_panel' 
                     AND mcp.master_color_id = ?
                     ORDER BY csi.id ASC";
            
            $stmt = $conn->prepare($query);
            $stmt->bind_param("i", $master_color_id);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows === 0) {
                throw new Exception("Tidak ada copy panel yang ditemukan untuk master color ini");
            }
            
            $updated_count = 0;
            $counter = 1;
            
            while ($row = $result->fetch_assoc()) {
                $lemari = $row['lemari'] ?? 'A';
                
                // Generate new rack number: A.001, A.002, etc.
                $new_rack = sprintf("%s.%03d", $lemari, $counter);
                
                // Update the rack number
                $update_query = "UPDATE color_stock_items SET rack_no = ? WHERE id = ?";
                $update_stmt = $conn->prepare($update_query);
                $update_stmt->bind_param("si", $new_rack, $row['id']);
                
                if ($update_stmt->execute()) {
                    $updated_count++;
                }
                
                $update_stmt->close();
                $counter++;
            }
            
            $stmt->close();
            
            // Commit transaction
            $conn->commit();
            
            // Log the action
            create_audit_log($conn, 'Auto Rename Racks by Master Color', $it_id, 'it', 
                "Successfully renamed $updated_count rack numbers for master color: {$master_data['code_color']} - {$master_data['name_color']}");
            
            $message = "Berhasil memperbaharui $updated_count nomor rack untuk master color: {$master_data['code_color']} - {$master_data['name_color']}!";
            $message_type = 'success';
            
        } catch (Exception $e) {
            // Rollback on error
            $conn->rollback();
            $message = "Terjadi kesalahan: " . $e->getMessage();
            $message_type = 'error';
            
            // Log the error
            create_audit_log($conn, 'Auto Rename Racks Failed', $it_id, 'it', "Error: " . $e->getMessage());
        }
    }
}

// Get all buyers for filter
$buyers_query = "SELECT DISTINCT b.id, b.nama_buyer, b.kode_buyer 
                 FROM buyers b 
                 INNER JOIN master_color mc ON b.id = mc.buyer_id
                 INNER JOIN master_color_panel mcp ON mcp.master_color_id = mc.id
                 INNER JOIN color_stock_items csi ON (csi.color_id = mcp.id AND csi.item_type = 'copy_panel')
                 ORDER BY b.nama_buyer";
$buyers_result = $conn->query($buyers_query);

// Initialize master colors result as null
$master_colors_result = null;
$selected_buyer_id = null;
$selected_color_name = null;

// Handle filter
if (isset($_GET['buyer_id']) && !empty($_GET['buyer_id'])) {
    $selected_buyer_id = (int)$_GET['buyer_id'];
    
    // Base query for master colors
    $master_colors_query = "SELECT 
                                mc.id,
                                mc.code_color,
                                mc.name_color,
                                mc.lemari,
                                mc.lemari_number,
                                b.nama_buyer,
                                c.nama_collection,
                                COUNT(csi.id) as total_copy_panels,
                                COUNT(DISTINCT csi.rack_no) as unique_racks,
                                MIN(csi.rack_no) as min_rack,
                                MAX(csi.rack_no) as max_rack
                            FROM master_color mc
                            LEFT JOIN buyers b ON mc.buyer_id = b.id
                            LEFT JOIN collections c ON mc.collection_id = c.id
                            LEFT JOIN master_color_panel mcp ON mcp.master_color_id = mc.id
                            LEFT JOIN color_stock_items csi ON (csi.color_id = mcp.id AND csi.item_type = 'copy_panel')
                            WHERE mc.buyer_id = ?";
    
    // Add color name filter if provided
    if (isset($_GET['color_name']) && !empty($_GET['color_name'])) {
        $selected_color_name = $_GET['color_name'];
        $master_colors_query .= " AND mc.name_color LIKE ?";
    }
    
    $master_colors_query .= " GROUP BY mc.id, mc.code_color, mc.name_color, mc.lemari, mc.lemari_number, b.nama_buyer, c.nama_collection
                             HAVING total_copy_panels > 0
                             ORDER BY mc.lemari ASC, mc.code_color ASC";
    
    $stmt = $conn->prepare($master_colors_query);
    if ($selected_color_name) {
        $color_search = '%' . $selected_color_name . '%';
        $stmt->bind_param("is", $selected_buyer_id, $color_search);
    } else {
        $stmt->bind_param("i", $selected_buyer_id);
    }
    $stmt->execute();
    $master_colors_result = $stmt->get_result();
}

// 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 Rack Numbers by Master Color</h2>
        <p class="text-gray-600">Perbaharui nomor rack per master color agar urut dan tidak duplikat</p>
    </div>

    <!-- Alert Messages -->
    <?php if ($message): ?>
    <div class="mb-6 p-4 rounded-lg <?php echo $message_type === 'success' ? 'bg-green-100 border border-green-400 text-green-700' : 'bg-red-100 border border-red-400 text-red-700'; ?>">
        <div class="flex items-center">
            <i class="fas <?php echo $message_type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'; ?> mr-2"></i>
            <span><?php echo htmlspecialchars($message); ?></span>
        </div>
    </div>
    <?php endif; ?>

    <!-- Filter Section -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">Filter Master Color</h3>
        
        <form method="GET" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <!-- Buyer Filter -->
                <div>
                    <label for="buyer_id" class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-building mr-1"></i>
                        Pilih Buyer <span class="text-red-500">*</span>
                    </label>
                    <select id="buyer_id" name="buyer_id" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" onchange="this.form.submit()" required>
                        <option value="">-- Pilih Buyer --</option>
                        <?php while ($buyer = $buyers_result->fetch_assoc()): ?>
                            <option value="<?php echo $buyer['id']; ?>" <?php echo ($selected_buyer_id == $buyer['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($buyer['nama_buyer']) . ' (' . htmlspecialchars($buyer['kode_buyer']) . ')'; ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>

                <!-- Color Name Filter -->
                <div>
                    <label for="color_name" class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-palette mr-1"></i>
                        Nama Color (Optional)
                    </label>
                    <div class="relative">
                        <input type="text" 
                               id="color_name" 
                               name="color_name" 
                               value="<?php echo htmlspecialchars($selected_color_name ?? ''); ?>"
                               placeholder="Masukkan nama color untuk pencarian..."
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 <?php echo !$selected_buyer_id ? 'bg-gray-100 cursor-not-allowed' : ''; ?>"
                               <?php echo !$selected_buyer_id ? 'disabled' : ''; ?>>
                        <button type="submit" class="absolute inset-y-0 right-0 px-4 py-2 bg-blue-600 text-white rounded-r-md hover:bg-blue-700 <?php echo !$selected_buyer_id ? 'bg-gray-400 cursor-not-allowed' : ''; ?>" <?php echo !$selected_buyer_id ? 'disabled' : ''; ?>>
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                </div>
            </div>

            <?php if ($selected_buyer_id): ?>
            <div class="flex space-x-2">
                <a href="<?php echo $_SERVER['PHP_SELF']; ?>" class="px-4 py-2 bg-gray-500 text-white rounded-md hover:bg-gray-600 transition-colors">
                    <i class="fas fa-undo mr-1"></i>
                    Reset Filter
                </a>
                <?php if ($selected_color_name): ?>
                <a href="<?php echo $_SERVER['PHP_SELF']; ?>?buyer_id=<?php echo $selected_buyer_id; ?>" class="px-4 py-2 bg-orange-500 text-white rounded-md hover:bg-orange-600 transition-colors">
                    <i class="fas fa-times mr-1"></i>
                    Clear Color Filter
                </a>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </form>
    </div>

    <!-- Master Colors List -->
    <div class="bg-white rounded-lg shadow-md p-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">Daftar Master Color dengan Copy Panels</h3>
        
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Master Color</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Buyer</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Collection</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Lemari</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Copy Panels</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Unique Racks</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Rack Range</th>
                        <th class="px-6 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 if ($master_colors_result && $master_colors_result->num_rows > 0): ?>
                        <?php while ($master = $master_colors_result->fetch_assoc()): ?>
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm font-medium text-gray-900">
                                    <?php echo htmlspecialchars($master['code_color']); ?>
                                </div>
                                <div class="text-sm text-gray-500">
                                    <?php echo htmlspecialchars($master['name_color'] ?? 'No Name'); ?>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                <?php echo htmlspecialchars($master['nama_buyer'] ?? 'N/A'); ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                <?php echo htmlspecialchars($master['nama_collection'] ?? 'N/A'); ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                <?php echo htmlspecialchars($master['lemari'] ?? 'A') . '.' . htmlspecialchars($master['lemari_number']); ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800">
                                    <?php echo number_format($master['total_copy_panels']); ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                <?php echo number_format($master['unique_racks']); ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                <?php if ($master['min_rack'] && $master['max_rack']): ?>
                                    <?php echo htmlspecialchars($master['min_rack']) . ' - ' . htmlspecialchars($master['max_rack']); ?>
                                <?php else: ?>
                                    <span class="text-red-500">No Racks</span>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                <div class="flex space-x-2">
                                    <button onclick="previewMasterColor(<?php echo $master['id']; ?>, '<?php echo htmlspecialchars($master['code_color'], ENT_QUOTES); ?>')"
                                            class="text-green-600 hover:text-green-900 px-3 py-1 rounded border border-green-300 hover:bg-green-50">
                                        <i class="fas fa-eye mr-1"></i>Preview
                                    </button>
                                    <form method="POST" style="display: inline;" onsubmit="return confirmRename('<?php echo htmlspecialchars($master['code_color'], ENT_QUOTES); ?>')">
                                        <input type="hidden" name="action" value="auto_rename">
                                        <input type="hidden" name="master_color_id" value="<?php echo $master['id']; ?>">
                                        <button type="submit" class="text-blue-600 hover:text-blue-900 px-3 py-1 rounded border border-blue-300 hover:bg-blue-50">
                                            <i class="fas fa-sync-alt mr-1"></i>Rename
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="8" class="px-6 py-4 text-center text-gray-500">
                                <?php if (!$selected_buyer_id): ?>
                                    Silakan pilih buyer terlebih dahulu untuk melihat master color
                                <?php elseif ($selected_color_name): ?>
                                    Tidak ada master color yang ditemukan untuk buyer dan nama color yang dipilih
                                <?php else: ?>
                                    Tidak ada master color dengan copy panels yang ditemukan untuk buyer ini
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Preview Modal -->
    <div id="previewModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
        <div class="relative top-20 mx-auto p-5 border w-11/12 max-w-4xl shadow-lg rounded-md bg-white">
            <div class="mt-3">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-medium text-gray-900" id="previewTitle">Preview Copy Panels</h3>
                    <button onclick="closePreview()" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                <div id="previewContent">
                    <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>
                </div>
            </div>
        </div>
    </div>
</main>

<script>
function confirmRename(masterColorCode) {
    return confirm(`Apakah Anda yakin ingin memperbaharui nomor rack untuk master color: ${masterColorCode}?\n\nProses ini akan mengubah nomor rack untuk semua copy panel dalam master color ini secara otomatis.\n\nKlik OK untuk melanjutkan.`);
}

function previewMasterColor(masterColorId, masterColorCode) {
    document.getElementById('previewModal').classList.remove('hidden');
    document.getElementById('previewTitle').textContent = `Preview Copy Panels - ${masterColorCode}`;
    
    const container = document.getElementById('previewContent');
    
    // Show loading
    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 preview...</span>
        </div>
    `;
    
    // Fetch preview data
    fetch(`ajax_rack_preview.php?master_color_id=${masterColorId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                let html = '<div class="overflow-x-auto"><table class="min-w-full divide-y divide-gray-200">';
                html += '<thead class="bg-gray-50"><tr>';
                html += '<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">ID</th>';
                html += '<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Copy Panel Code</th>';
                html += '<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Kode Barang</th>';
                html += '<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Component</th>';
                html += '<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Current Rack</th>';
                html += '<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Predicted New Rack</th>';
                html += '<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>';
                html += '</tr></thead><tbody class="bg-white divide-y divide-gray-200">';
                
                data.items.forEach((item, index) => {
                    const predictedRack = `${item.lemari}.${String(index + 1).padStart(3, '0')}`;
                    html += '<tr>';
                    html += '<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">' + item.id + '</td>';
                    html += '<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">' + item.code_color + '</td>';
                    html += '<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">' + item.kode_barang + '</td>';
                    html += '<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">' + item.component_name + '</td>';
                    html += '<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">' + item.current_rack + '</td>';
                    html += '<td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-blue-600">' + predictedRack + '</td>';
                    html += '<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">' + item.status + '</td>';
                    html += '</tr>';
                });
                
                html += '</tbody></table></div>';
                
                if (data.items.length === 0) {
                    html = '<div class="text-center p-8 text-gray-500">Tidak ada copy panel untuk master color ini</div>';
                }
                
                container.innerHTML = html;
            } else {
                container.innerHTML = '<div class="text-center p-8 text-red-600">Error: ' + data.message + '</div>';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            container.innerHTML = '<div class="text-center p-8 text-red-600">Terjadi kesalahan saat memuat preview</div>';
        });
}

function closePreview() {
    document.getElementById('previewModal').classList.add('hidden');
}

// Close modal when clicking outside
document.getElementById('previewModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closePreview();
    }
});
</script>

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