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

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

// Handle form submission
$success_message = '';
$error_message = '';
$preview_data = array();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        $action = $_POST['action'];
        
        // Preview action
        if ($action === 'preview') {
            $prefix = mysqli_real_escape_string($conn, trim($_POST['prefix']));
            $digit_length = intval($_POST['digit_length']);
            
            if (empty($prefix)) {
                $error_message = "Prefix tidak boleh kosong!";
            } elseif ($digit_length < 1 || $digit_length > 5) {
                $error_message = "Panjang digit harus antara 1-5!";
            } else {
                // Get preview data
                $preview_query = "SELECT id, code_color, deskripsi, 
                                  CONCAT('$prefix', '.', LPAD(id, $digit_length, '0')) as new_code 
                                  FROM master_color_panel 
                                  ORDER BY id 
                                  LIMIT 10";
                $preview_result = $conn->query($preview_query);
                
                if ($preview_result) {
                    while ($row = $preview_result->fetch_assoc()) {
                        $preview_data[] = $row;
                    }
                }
            }
        }
        
        // Execute action
        elseif ($action === 'execute') {
            $prefix = mysqli_real_escape_string($conn, trim($_POST['prefix']));
            $digit_length = intval($_POST['digit_length']);
            $confirm = isset($_POST['confirm']) ? $_POST['confirm'] : '';
            
            if (empty($prefix)) {
                $error_message = "Prefix tidak boleh kosong!";
            } elseif ($digit_length < 1 || $digit_length > 5) {
                $error_message = "Panjang digit harus antara 1-5!";
            } elseif ($confirm !== 'EXECUTE') {
                $error_message = "Konfirmasi tidak sesuai! Ketik 'EXECUTE' untuk melanjutkan.";
            } else {
                // Begin transaction
                $conn->begin_transaction();
                
                try {
                    // Step 1: Add temporary column if not exists
                    $check_column = "SHOW COLUMNS FROM master_color_panel LIKE 'old_code_color'";
                    $result = $conn->query($check_column);
                    
                    if ($result->num_rows == 0) {
                        $add_column_sql = "ALTER TABLE master_color_panel 
                                          ADD COLUMN old_code_color VARCHAR(255) NULL 
                                          AFTER keterangan_warna";
                        $conn->query($add_column_sql);
                    }
                    
                    // Step 2: Backup old code_color to old_code_color
                    $backup_sql = "UPDATE master_color_panel SET old_code_color = code_color";
                    $conn->query($backup_sql);
                    
                    // Step 3: SKIP - TIDAK mengubah deskripsi sama sekali
                    // Deskripsi tetap apa adanya
                    
                    // Step 4: Update code_color with new format
                    $update_code_sql = "UPDATE master_color_panel 
                                       SET code_color = CONCAT('$prefix', '.', LPAD(id, $digit_length, '0'))";
                    $conn->query($update_code_sql);
                    
                    // Commit transaction
                    $conn->commit();
                    
                    // Log the action
                    create_audit_log($conn, 'Master Color Code Renamed', $it_id, 'it', 
                                    "IT user renamed all master color codes with prefix: $prefix (deskripsi tidak diubah)");
                    
                    $success_message = "Berhasil! Semua code_color telah diubah dengan prefix '$prefix'. Deskripsi tetap tidak berubah.";
                    
                } catch (Exception $e) {
                    // Rollback on error
                    $conn->rollback();
                    $error_message = "Terjadi kesalahan: " . $e->getMessage();
                }
            }
        }
        
        // Restore action
        elseif ($action === 'restore') {
            $confirm_restore = isset($_POST['confirm_restore']) ? $_POST['confirm_restore'] : '';
            
            if ($confirm_restore !== 'RESTORE') {
                $error_message = "Konfirmasi tidak sesuai! Ketik 'RESTORE' untuk melanjutkan.";
            } else {
                // Check if backup column exists
                $check_column = "SHOW COLUMNS FROM master_color_panel LIKE 'old_code_color'";
                $result = $conn->query($check_column);
                
                if ($result->num_rows == 0) {
                    $error_message = "Tidak ada backup yang tersimpan!";
                } else {
                    $conn->begin_transaction();
                    
                    try {
                        // Restore code_color from backup (deskripsi TIDAK diubah)
                        $restore_sql = "UPDATE master_color_panel 
                                       SET code_color = old_code_color
                                       WHERE old_code_color IS NOT NULL";
                        $conn->query($restore_sql);
                        
                        // Drop backup column
                        $drop_column_sql = "ALTER TABLE master_color_panel DROP COLUMN old_code_color";
                        $conn->query($drop_column_sql);
                        
                        $conn->commit();
                        
                        // Log the action
                        create_audit_log($conn, 'Master Color Code Restored', $it_id, 'it', 
                                        'IT user restored master color codes from backup (deskripsi tidak diubah)');
                        
                        $success_message = "Berhasil! Code_color telah dikembalikan ke format semula. Deskripsi tetap tidak berubah.";
                        
                    } catch (Exception $e) {
                        $conn->rollback();
                        $error_message = "Terjadi kesalahan: " . $e->getMessage();
                    }
                }
            }
        }
    }
}

// Get current data sample
$current_data_query = "SELECT id, code_color, deskripsi FROM master_color_panel ORDER BY id LIMIT 10";
$current_data_result = $conn->query($current_data_query);

// Check if backup exists
$backup_exists_query = "SHOW COLUMNS FROM master_color_panel LIKE 'old_code_color'";
$backup_exists_result = $conn->query($backup_exists_query);
$backup_exists = $backup_exists_result->num_rows > 0;

// 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">
            <i class="fas fa-exchange-alt mr-2"></i>Rename Master Color Code
        </h2>
        <p class="text-gray-600">Ubah format Code Color di Master Color Panel dengan prefix yang dapat disesuaikan</p>
        
        <!-- Info Box -->
        <div class="mt-4 bg-blue-50 border-l-4 border-blue-400 p-4">
            <div class="flex">
                <div class="flex-shrink-0">
                    <i class="fas fa-info-circle text-blue-400"></i>
                </div>
                <div class="ml-3">
                    <p class="text-sm text-blue-700">
                        <strong>Cara Kerja:</strong><br>
                        • Code Color akan diganti dengan format baru (contoh: M.001, M.002, dst)<br>
                        • <strong class="text-red-600">Deskripsi TIDAK akan diubah sama sekali</strong> - tetap apa adanya<br>
                        • Backup otomatis akan dibuat untuk restore jika diperlukan
                    </p>
                </div>
            </div>
        </div>
        
        <!-- Warning Alert -->
        <div class="mt-4 bg-yellow-50 border-l-4 border-yellow-400 p-4">
            <div class="flex">
                <div class="flex-shrink-0">
                    <i class="fas fa-exclamation-triangle text-yellow-400"></i>
                </div>
                <div class="ml-3">
                    <p class="text-sm text-yellow-700">
                        <strong>Perhatian:</strong> Proses ini akan mengubah semua code_color di database. 
                        Pastikan Anda melakukan backup database terlebih dahulu!
                    </p>
                </div>
            </div>
        </div>
    </div>

    <!-- Success/Error Messages -->
    <?php if (!empty($success_message)): ?>
    <div class="bg-green-50 border-l-4 border-green-400 p-4 mb-6">
        <div class="flex">
            <div class="flex-shrink-0">
                <i class="fas fa-check-circle text-green-400"></i>
            </div>
            <div class="ml-3">
                <p class="text-sm text-green-700"><?php echo htmlspecialchars($success_message); ?></p>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <?php if (!empty($error_message)): ?>
    <div class="bg-red-50 border-l-4 border-red-400 p-4 mb-6">
        <div class="flex">
            <div class="flex-shrink-0">
                <i class="fas fa-exclamation-circle text-red-400"></i>
            </div>
            <div class="ml-3">
                <p class="text-sm text-red-700"><?php echo htmlspecialchars($error_message); ?></p>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <!-- Current Data -->
        <div class="bg-white rounded-lg shadow-md p-6">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">
                <i class="fas fa-database mr-2"></i>Data Saat Ini (10 Data Teratas)
            </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-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">ID</th>
                            <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">Code Color</th>
                            <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">Deskripsi</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <?php while($row = $current_data_result->fetch_assoc()): ?>
                        <tr>
                            <td class="px-3 py-2 text-sm text-gray-900"><?php echo $row['id']; ?></td>
                            <td class="px-3 py-2 text-sm font-semibold text-blue-600"><?php echo htmlspecialchars($row['code_color']); ?></td>
                            <td class="px-3 py-2 text-sm text-gray-600"><?php echo htmlspecialchars($row['deskripsi']); ?></td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Configuration Form -->
        <div class="bg-white rounded-lg shadow-md p-6">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">
                <i class="fas fa-cog mr-2"></i>Konfigurasi Format Baru
            </h3>
            
            <form method="POST" id="configForm">
                <input type="hidden" name="action" value="preview">
                
                <div class="mb-4">
                    <label for="prefix" class="block text-sm font-medium text-gray-700 mb-2">
                        Prefix (Huruf)
                    </label>
                    <input type="text" 
                           id="prefix" 
                           name="prefix" 
                           value="<?php echo isset($_POST['prefix']) ? htmlspecialchars($_POST['prefix']) : 'M'; ?>"
                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 uppercase"
                           maxlength="3"
                           pattern="[A-Za-z]+"
                           required>
                    <p class="mt-1 text-xs text-gray-500">Contoh: M, C, D, atau PREFIX</p>
                </div>

                <div class="mb-4">
                    <label for="digit_length" class="block text-sm font-medium text-gray-700 mb-2">
                        Panjang Digit Angka
                    </label>
                    <select id="digit_length" 
                            name="digit_length" 
                            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="3" <?php echo (isset($_POST['digit_length']) && $_POST['digit_length'] == 3) ? 'selected' : 'selected'; ?>>3 digit (001, 002, ...)</option>
                        <option value="2" <?php echo (isset($_POST['digit_length']) && $_POST['digit_length'] == 2) ? 'selected' : ''; ?>>2 digit (01, 02, ...)</option>
                        <option value="4" <?php echo (isset($_POST['digit_length']) && $_POST['digit_length'] == 4) ? 'selected' : ''; ?>>4 digit (0001, 0002, ...)</option>
                        <option value="5" <?php echo (isset($_POST['digit_length']) && $_POST['digit_length'] == 5) ? 'selected' : ''; ?>>5 digit (00001, 00002, ...)</option>
                    </select>
                </div>

                <div class="mb-4">
                    <div class="bg-blue-50 border border-blue-200 rounded-md p-3">
                        <p class="text-sm text-blue-700">
                            <strong>Format Preview:</strong><br>
                            <span id="formatPreview" class="font-mono text-lg">M.001, M.002, M.003, ...</span>
                        </p>
                    </div>
                </div>

                <div class="flex space-x-2">
                    <button type="submit" 
                            class="flex-1 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors">
                        <i class="fas fa-eye mr-2"></i>Preview
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Preview Results -->
    <?php if (!empty($preview_data)): ?>
    <div class="mt-6 bg-white rounded-lg shadow-md p-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">
            <i class="fas fa-eye mr-2"></i>Preview Perubahan (10 Data Teratas)
        </h3>
        
        <div class="overflow-x-auto mb-6">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">ID</th>
                        <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">Code Color Lama</th>
                        <th class="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase">
                            <i class="fas fa-arrow-right"></i>
                        </th>
                        <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">Code Color Baru</th>
                        <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">Deskripsi</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php foreach($preview_data as $row): ?>
                    <tr>
                        <td class="px-3 py-2 text-sm text-gray-900"><?php echo $row['id']; ?></td>
                        <td class="px-3 py-2 text-sm text-red-600 line-through"><?php echo htmlspecialchars($row['code_color']); ?></td>
                        <td class="px-3 py-2 text-center">
                            <i class="fas fa-arrow-right text-gray-400"></i>
                        </td>
                        <td class="px-3 py-2 text-sm font-semibold text-green-600"><?php echo htmlspecialchars($row['new_code']); ?></td>
                        <td class="px-3 py-2 text-sm">
                            <span class="text-gray-600"><?php echo htmlspecialchars($row['deskripsi']); ?></span>
                            <span class="text-xs text-blue-600 ml-2">(tidak berubah)</span>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Confirmation Form -->
        <form method="POST" id="executeForm" onsubmit="return confirmExecution()">
            <input type="hidden" name="action" value="execute">
            <input type="hidden" name="prefix" value="<?php echo htmlspecialchars($_POST['prefix']); ?>">
            <input type="hidden" name="digit_length" value="<?php echo htmlspecialchars($_POST['digit_length']); ?>">
            
            <div class="bg-red-50 border border-red-200 rounded-md p-4 mb-4">
                <p class="text-sm text-red-700 mb-3">
                    <strong>PERHATIAN:</strong> Anda akan mengubah SEMUA code_color di database!<br>
                    <strong>Deskripsi TIDAK akan diubah.</strong>
                </p>
                <label for="confirm" class="block text-sm font-medium text-red-700 mb-2">
                    Ketik <strong>"EXECUTE"</strong> untuk konfirmasi:
                </label>
                <input type="text" 
                       id="confirm" 
                       name="confirm" 
                       class="w-full px-3 py-2 border border-red-300 rounded-md focus:outline-none focus:ring-2 focus:ring-red-500"
                       placeholder="EXECUTE"
                       required>
            </div>

            <button type="submit" 
                    class="w-full px-4 py-3 bg-red-600 text-white rounded-md hover:bg-red-700 transition-colors font-semibold">
                <i class="fas fa-bolt mr-2"></i>Eksekusi Perubahan
            </button>
        </form>
    </div>
    <?php endif; ?>

    <!-- Restore Section -->
    <?php if ($backup_exists): ?>
    <div class="mt-6 bg-white rounded-lg shadow-md p-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">
            <i class="fas fa-undo mr-2"></i>Restore ke Format Semula
        </h3>
        
        <div class="bg-yellow-50 border border-yellow-200 rounded-md p-4 mb-4">
            <p class="text-sm text-yellow-700 mb-3">
                Backup ditemukan! Anda dapat mengembalikan code_color ke format semula.<br>
                <strong>Deskripsi tetap tidak akan berubah.</strong>
            </p>
        </div>

        <form method="POST" id="restoreForm" onsubmit="return confirmRestore()">
            <input type="hidden" name="action" value="restore">
            
            <div class="mb-4">
                <label for="confirm_restore" class="block text-sm font-medium text-gray-700 mb-2">
                    Ketik <strong>"RESTORE"</strong> untuk konfirmasi:
                </label>
                <input type="text" 
                       id="confirm_restore" 
                       name="confirm_restore" 
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500"
                       placeholder="RESTORE"
                       required>
            </div>

            <button type="submit" 
                    class="w-full px-4 py-2 bg-yellow-600 text-white rounded-md hover:bg-yellow-700 transition-colors">
                <i class="fas fa-undo mr-2"></i>Restore Code Color
            </button>
        </form>
    </div>
    <?php endif; ?>
</main>

<script>
// Update format preview
function updateFormatPreview() {
    const prefix = document.getElementById('prefix').value.toUpperCase() || 'M';
    const digitLength = parseInt(document.getElementById('digit_length').value) || 3;
    const sample1 = prefix + '.' + '1'.padStart(digitLength, '0');
    const sample2 = prefix + '.' + '2'.padStart(digitLength, '0');
    const sample3 = prefix + '.' + '3'.padStart(digitLength, '0');
    document.getElementById('formatPreview').textContent = `${sample1}, ${sample2}, ${sample3}, ...`;
}

// Initialize and add event listeners
document.addEventListener('DOMContentLoaded', function() {
    updateFormatPreview();
    
    document.getElementById('prefix').addEventListener('input', function() {
        this.value = this.value.toUpperCase();
        updateFormatPreview();
    });
    
    document.getElementById('digit_length').addEventListener('change', updateFormatPreview);
});

// Confirm execution
function confirmExecution() {
    const confirm = document.getElementById('confirm').value;
    if (confirm !== 'EXECUTE') {
        alert('Konfirmasi tidak sesuai! Ketik "EXECUTE" dengan huruf kapital.');
        return false;
    }
    
    return window.confirm('Anda yakin akan mengubah SEMUA code_color di database?\n\nDESKRIPSI TIDAK AKAN DIUBAH.\n\nPastikan Anda sudah melakukan backup database!');
}

// Confirm restore
function confirmRestore() {
    const confirm = document.getElementById('confirm_restore').value;
    if (confirm !== 'RESTORE') {
        alert('Konfirmasi tidak sesuai! Ketik "RESTORE" dengan huruf kapital.');
        return false;
    }
    
    return window.confirm('Anda yakin akan mengembalikan code_color ke format semula?\n\nDeskripsi tetap tidak akan berubah.');
}
</script>

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