<?php
// add_user.php
require_once 'config/database.php';
require_once 'config/app.php';
checkAuth();

// Hanya admin yang bisa menambah user
if (!hasRole('admin')) {
    header('Location: index.php');
    exit;
}

$conn = getConnection();
$message = '';
$search = $_GET['search'] ?? '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $employee_id = (int)($_POST['employee_id'] ?? 0);
    $role = $_POST['role'] ?? 'viewer';
    $access_scope = $_POST['access_scope'] ?? 'full';
    
    if ($employee_id) {
        // Cek apakah sudah punya user
        $check = $conn->query("SELECT id FROM users WHERE employee_id = $employee_id");
        if ($check->num_rows > 0) {
            $message = '<div class="bg-red-100 text-red-700 p-3 rounded mb-4">❌ Karyawan sudah memiliki akun!</div>';
        } else {
            // Ambil data karyawan
            $emp = $conn->query("SELECT nik, full_name FROM employees WHERE id = $employee_id")->fetch_assoc();
            
            // Username = NIK, Password default = balimed1
            $username = $emp['nik'];
            $password_hash = password_hash('balimed1', PASSWORD_DEFAULT);
            
            $stmt = $conn->prepare("
                INSERT INTO users (employee_id, username, password_hash, role, access_scope, is_active, must_change_password) 
                VALUES (?, ?, ?, ?, ?, 1, 1)
            ");
            $stmt->bind_param("issss", $employee_id, $username, $password_hash, $role, $access_scope);
            
            if ($stmt->execute()) {
                $message = '<div class="bg-green-100 text-green-700 p-3 rounded mb-4">✅ User berhasil ditambahkan! Username: ' . $username . ', Password: balimed1</div>';
            } else {
                $message = '<div class="bg-red-100 text-red-700 p-3 rounded mb-4">❌ Gagal: ' . $conn->error . '</div>';
            }
        }
    }
}

// Ambil daftar karyawan yang belum punya user dengan pencarian
$sql = "
    SELECT e.* FROM employees e 
    LEFT JOIN users u ON e.id = u.employee_id 
    WHERE u.id IS NULL AND e.employment_status = 'aktif'
";

if (!empty($search)) {
    $search = $conn->real_escape_string($search);
    $sql .= " AND (e.full_name LIKE '%$search%' OR e.nik LIKE '%$search%' OR e.position LIKE '%$search%')";
}

$sql .= " ORDER BY e.full_name ASC";
$employees = $conn->query($sql);
?>
<!DOCTYPE html>
<html>
<head>
    <title>Tambah User</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .search-highlight {
            background-color: #fef3c7;
            padding: 2px 4px;
            border-radius: 4px;
        }
        .employee-item:hover {
            background-color: #f3f4f6;
            cursor: pointer;
        }
    </style>
</head>
<body class="p-6 bg-gray-100 font-['Poppins']">
    <div class="max-w-4xl mx-auto">
        <!-- Header -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
            <div class="flex items-center justify-between mb-6">
                <div>
                    <h1 class="text-2xl font-bold text-gray-800">Tambah User Baru</h1>
                    <p class="text-gray-600 text-sm mt-1">Buat akun untuk karyawan yang belum memiliki akses sistem</p>
                </div>
                <a href="index.php" class="text-blue-600 hover:text-blue-800">
                    <i class="fas fa-arrow-left mr-2"></i> Kembali
                </a>
            </div>
            
            <?= $message ?>
            
            <form method="POST" id="userForm">
                <!-- Pencarian Karyawan -->
                <div class="mb-6">
                    <label class="block text-sm font-medium mb-2 text-gray-700">
                        <i class="fas fa-search text-gray-400 mr-2"></i> Cari Karyawan
                    </label>
                    <div class="relative">
                        <input type="text" 
                               id="searchInput" 
                               value="<?= htmlspecialchars($search) ?>" 
                               placeholder="Cari berdasarkan nama, NIK, atau jabatan..." 
                               class="w-full px-4 py-3 pl-10 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        <i class="fas fa-search absolute left-3 top-3.5 text-gray-400"></i>
                        <button type="button" id="searchBtn" class="absolute right-2 top-1.5 bg-blue-600 text-white px-4 py-1.5 rounded-lg text-sm hover:bg-blue-700">
                            Cari
                        </button>
                    </div>
                    <p class="text-xs text-gray-500 mt-2">
                        <i class="fas fa-info-circle mr-1"></i> Ketik minimal 3 karakter untuk mencari
                    </p>
                </div>
                
                <!-- Hasil Pencarian / Daftar Karyawan -->
                <div class="mb-6">
                    <label class="block text-sm font-medium mb-2 text-gray-700">
                        <i class="fas fa-users text-gray-400 mr-2"></i> Daftar Karyawan
                    </label>
                    <div class="border border-gray-200 rounded-lg overflow-hidden">
                        <div class="bg-gray-50 px-4 py-2 border-b border-gray-200 text-sm font-medium text-gray-600">
                            <div class="grid grid-cols-12 gap-2">
                                <div class="col-span-1">No</div>
                                <div class="col-span-4">Nama Lengkap</div>
                                <div class="col-span-2">NIK</div>
                                <div class="col-span-3">Jabatan</div>
                                <div class="col-span-2">Departemen</div>
                            </div>
                        </div>
                        <div id="employeeList" class="max-h-96 overflow-y-auto">
                            <?php if ($employees && $employees->num_rows > 0): ?>
                                <?php $no = 1; while ($emp = $employees->fetch_assoc()): ?>
                                <div class="employee-item px-4 py-3 border-b border-gray-100 hover:bg-gray-50 transition cursor-pointer"
                                     data-id="<?= $emp['id'] ?>"
                                     data-name="<?= htmlspecialchars($emp['full_name']) ?>"
                                     data-nik="<?= htmlspecialchars($emp['nik']) ?>"
                                     onclick="selectEmployee(this)">
                                    <div class="grid grid-cols-12 gap-2 items-center">
                                        <div class="col-span-1 text-gray-500"><?= $no++ ?></div>
                                        <div class="col-span-4 font-medium text-gray-800">
                                            <?= highlightSearch(htmlspecialchars($emp['full_name']), $search) ?>
                                        </div>
                                        <div class="col-span-2 text-gray-600">
                                            <?= highlightSearch(htmlspecialchars($emp['nik']), $search) ?>
                                        </div>
                                        <div class="col-span-3 text-gray-600 text-sm">
                                            <?= highlightSearch(htmlspecialchars($emp['position'] ?? '-'), $search) ?>
                                        </div>
                                        <div class="col-span-2 text-gray-500 text-sm">
                                            <?= htmlspecialchars($emp['department'] ?? '-') ?>
                                        </div>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <div class="px-4 py-8 text-center text-gray-500">
                                    <i class="fas fa-user-slash text-4xl mb-2 opacity-50"></i>
                                    <p>Tidak ada karyawan yang belum memiliki akun</p>
                                    <?php if (!empty($search)): ?>
                                        <p class="text-sm mt-1">Coba dengan kata kunci pencarian yang berbeda</p>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <!-- Form Pilihan Karyawan (Hidden) -->
                <input type="hidden" name="employee_id" id="selectedEmployeeId" value="">
                
                <!-- Informasi Karyawan Terpilih -->
                <div id="selectedInfo" class="mb-6 hidden">
                    <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                        <div class="flex items-start">
                            <i class="fas fa-user-check text-blue-600 text-xl mr-3 mt-1"></i>
                            <div class="flex-1">
                                <p class="text-sm font-medium text-blue-800 mb-1">Karyawan Terpilih:</p>
                                <p class="font-semibold text-gray-800" id="selectedName"></p>
                                <p class="text-sm text-gray-600" id="selectedNik"></p>
                            </div>
                            <button type="button" onclick="clearSelection()" class="text-blue-600 hover:text-blue-800">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Role dan Access Scope -->
                <div class="grid grid-cols-2 gap-4 mb-6">
                    <div>
                        <label class="block text-sm font-medium mb-2 text-gray-700">
                            <i class="fas fa-user-tag text-gray-400 mr-2"></i> Role
                        </label>
                        <select name="role" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                            <option value="viewer">👁️ Viewer (Hanya Lihat)</option>
                            <option value="editor">✏️ Editor (Tambah/Ubah)</option>
                            <option value="admin">👑 Admin (Full Access)</option>
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium mb-2 text-gray-700">
                            <i class="fas fa-globe text-gray-400 mr-2"></i> Access Scope
                        </label>
                        <select name="access_scope" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                            <option value="full">🌍 Full Access</option>
                            <option value="custom">⚙️ Custom</option>
                        </select>
                    </div>
                </div>
                
                <!-- Info Password Default -->
                <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-6">
                    <div class="flex items-start">
                        <i class="fas fa-key text-yellow-600 text-xl mr-3 mt-1"></i>
                        <div>
                            <p class="text-sm font-medium text-yellow-800 mb-1">Informasi Password Default</p>
                            <p class="text-sm text-yellow-700">
                                Password default: <strong class="font-mono bg-yellow-100 px-2 py-0.5 rounded">balimed1</strong><br>
                                User akan diminta untuk mengganti password saat login pertama kali.
                            </p>
                        </div>
                    </div>
                </div>
                
                <!-- Tombol Submit -->
                <div class="flex gap-3">
                    <button type="submit" id="submitBtn" disabled class="bg-blue-600 text-white px-6 py-2.5 rounded-lg hover:bg-blue-700 transition disabled:opacity-50 disabled:cursor-not-allowed">
                        <i class="fas fa-plus mr-2"></i> Tambah User
                    </button>
                    <button type="button" onclick="resetForm()" class="border border-gray-300 text-gray-700 px-6 py-2.5 rounded-lg hover:bg-gray-50 transition">
                        <i class="fas fa-undo-alt mr-2"></i> Reset
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <script>
        // Fungsi untuk highlight teks pencarian
        function highlightText(text, search) {
            if (!search || search.length < 2) return text;
            const regex = new RegExp(`(${search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
            return text.replace(regex, '<mark class="bg-yellow-200 px-0.5 rounded">$1</mark>');
        }
        
        // Pilih karyawan
        function selectEmployee(element) {
            const id = element.dataset.id;
            const name = element.dataset.name;
            const nik = element.dataset.nik;
            
            // Set hidden input
            document.getElementById('selectedEmployeeId').value = id;
            
            // Tampilkan info terpilih
            document.getElementById('selectedName').innerHTML = `<i class="fas fa-user mr-2"></i> ${name}`;
            document.getElementById('selectedNik').innerHTML = `<i class="fas fa-id-card mr-2"></i> NIK: ${nik}`;
            document.getElementById('selectedInfo').classList.remove('hidden');
            
            // Highlight row yang dipilih
            document.querySelectorAll('.employee-item').forEach(item => {
                item.classList.remove('bg-blue-50', 'border-l-4', 'border-l-blue-500');
            });
            element.classList.add('bg-blue-50', 'border-l-4', 'border-l-blue-500');
            
            // Enable submit button
            document.getElementById('submitBtn').disabled = false;
        }
        
        // Clear selection
        function clearSelection() {
            document.getElementById('selectedEmployeeId').value = '';
            document.getElementById('selectedInfo').classList.add('hidden');
            document.getElementById('submitBtn').disabled = true;
            
            document.querySelectorAll('.employee-item').forEach(item => {
                item.classList.remove('bg-blue-50', 'border-l-4', 'border-l-blue-500');
            });
        }
        
        // Reset form
        function resetForm() {
            clearSelection();
            document.getElementById('searchInput').value = '';
            // Reload page to reset employee list
            window.location.href = window.location.pathname;
        }
        
        // Pencarian dengan debounce
        let searchTimeout;
        const searchInput = document.getElementById('searchInput');
        const searchBtn = document.getElementById('searchBtn');
        
        function performSearch() {
            const searchTerm = searchInput.value.trim();
            if (searchTerm.length >= 2 || searchTerm.length === 0) {
                window.location.href = window.location.pathname + '?search=' + encodeURIComponent(searchTerm);
            } else if (searchTerm.length > 0 && searchTerm.length < 2) {
                alert('Minimal 2 karakter untuk mencari');
            }
        }
        
        searchInput.addEventListener('keyup', function(e) {
            if (e.key === 'Enter') {
                performSearch();
            }
        });
        
        searchBtn.addEventListener('click', performSearch);
        
        // Jika ada search parameter, fokus ke input
        <?php if (!empty($search)): ?>
        searchInput.focus();
        searchInput.setSelectionRange(searchInput.value.length, searchInput.value.length);
        <?php endif; ?>
        
        // Keyboard navigation
        let selectedIndex = -1;
        const employeeItems = document.querySelectorAll('.employee-item');
        
        searchInput.addEventListener('keydown', function(e) {
            if (e.key === 'ArrowDown') {
                e.preventDefault();
                if (employeeItems.length > 0) {
                    selectedIndex = (selectedIndex + 1) % employeeItems.length;
                    employeeItems[selectedIndex].scrollIntoView({ block: 'nearest' });
                    employeeItems[selectedIndex].focus?.();
                }
            } else if (e.key === 'ArrowUp') {
                e.preventDefault();
                if (employeeItems.length > 0) {
                    selectedIndex = (selectedIndex - 1 + employeeItems.length) % employeeItems.length;
                    employeeItems[selectedIndex].scrollIntoView({ block: 'nearest' });
                    employeeItems[selectedIndex].focus?.();
                }
            }
        });
        
        // Tooltip untuk role
        const roleSelect = document.querySelector('select[name="role"]');
        const roleInfo = {
            viewer: 'Hanya dapat melihat data, tidak bisa mengubah atau menghapus',
            editor: 'Dapat menambah dan mengubah data, tapi tidak bisa menghapus user',
            admin: 'Akses penuh ke semua fitur termasuk manajemen user'
        };
        
        roleSelect.addEventListener('change', function() {
            const info = roleInfo[this.value];
            if (info) {
                // Bisa ditambahkan tooltip atau notifikasi
                console.log('Role info:', info);
            }
        });
    </script>
    
    <?php
    // Helper function untuk highlight search result
    function highlightSearch($text, $search) {
        if (empty($search) || strlen($search) < 2) {
            return $text;
        }
        $pattern = '/' . preg_quote($search, '/') . '/i';
        return preg_replace($pattern, '<span class="bg-yellow-200 px-0.5 rounded">$0</span>', $text);
    }
    ?>
</body>
</html>