<?php
// existing content starts...
// existing content starts...
require_once '../config/db.php';
require_once 'layout.php';

// OVERRIDE: Admin panel needs HTML
header('Content-Type: text/html; charset=utf-8');

// Handle Actions (Ban/Unban)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'], $_POST['user_id'])) {
    $uid = (int)$_POST['user_id'];
    if ($_POST['action'] === 'ban') {
        $pdo->prepare("UPDATE users SET status = 'banned' WHERE id = ?")->execute([$uid]);
    } elseif ($_POST['action'] === 'unban') {
        $pdo->prepare("UPDATE users SET status = 'active' WHERE id = ?")->execute([$uid]);
    }
    // Refresh to prevent resubmit
    echo "<script>window.location.href='users.php';</script>";
    exit;
}

// Fetch Users with Gamification Data
try {
    // We select all columns including xp, level, last_check_in
    $sql = "SELECT * FROM i_users ORDER BY registered DESC LIMIT 50";
    $users = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);

    // Calculate Total Users for Badge
    $total = $pdo->query("SELECT COUNT(*) FROM i_users")->fetchColumn();
    
} catch (PDOException $e) {
    die("Error DB: " . $e->getMessage());
}

renderAdminSidebar('users');
?>

<!-- Header -->
<div class="flex justify-between items-center mb-6">
    <div>
        <h2 class="text-3xl font-bold text-white tracking-tight">Usuarios Registrados</h2>
        <p class="text-gray-400 mt-1">Gestiona los perfiles, niveles y estado de la comunidad.</p>
    </div>
    <div class="flex gap-3">
        <div class="bg-dark-800 border border-dark-700 rounded-lg px-4 py-2 flex items-center gap-3 shadow-lg">
            <div class="w-8 h-8 rounded-full bg-blue-500/20 text-blue-400 flex items-center justify-center">
                <i class="fas fa-users"></i>
            </div>
            <div>
                <p class="text-xs text-gray-400 font-bold uppercase">Total</p>
                <p class="text-lg font-bold text-white leading-none"><?php echo number_format($total); ?></p>
            </div>
        </div>
        <button class="bg-brand-600 hover:bg-brand-700 text-white font-bold py-2 px-4 rounded-lg flex items-center gap-2 shadow-lg shadow-brand-500/20 transition">
            <i class="fas fa-user-plus"></i> Nuevo Usuario
        </button>
    </div>
</div>

<!-- Users Table Card -->
<div class="bg-dark-800 rounded-2xl border border-dark-700 shadow-xl overflow-hidden">
    <!-- Search Bar -->
    <div class="p-4 border-b border-dark-700 bg-dark-900/30 flex justify-between items-center">
        <div class="relative w-64">
            <i class="fas fa-search absolute left-3 top-3 text-gray-500 text-sm"></i>
            <input type="text" placeholder="Buscar por nombre o email..." class="w-full bg-dark-900 border border-dark-700 rounded-lg py-2 pl-9 pr-4 text-sm text-white focus:border-brand-500 focus:ring-0 placeholder-gray-600 transition">
        </div>
        <div class="flex gap-2">
            <select class="bg-dark-900 border border-dark-700 text-gray-300 text-sm rounded-lg px-3 py-2 cursor-pointer focus:border-brand-500">
                <option>Todos los Estados</option>
                <option>Activos</option>
                <option>Baneados</option>
            </select>
            <select class="bg-dark-900 border border-dark-700 text-gray-300 text-sm rounded-lg px-3 py-2 cursor-pointer focus:border-brand-500">
                <option>Ordenar por Registro</option>
                <option>Ordenar por Nivel (Alto-Bajo)</option>
                <option>Ordenar por Diamantes</option>
            </select>
        </div>
    </div>

    <!-- Table -->
    <div class="overflow-x-auto">
        <table class="w-full text-left text-sm text-gray-400">
            <thead class="bg-dark-900 text-gray-200 font-medium uppercase text-xs">
                <tr>
                    <th class="px-6 py-4">Usuario</th>
                    <th class="px-6 py-4">Nivel / XP</th>
                    <th class="px-6 py-4 text-center">Diamantes</th>
                    <th class="px-6 py-4 text-center">Status</th>
                    <th class="px-6 py-4 text-center">Último Login</th>
                    <th class="px-6 py-4 text-right">Acciones</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-dark-700">
                <?php foreach ($users as $user): 
                    // Map i_users columns to standardized vars
                    $uid = $user['iuid'];
                    $username = $user['i_username'];
                    $email = $user['i_user_email'];
                    $avatar = $user['user_avatar'] ?? 'default.png'; 
                    // Add logic to handle full URL or relative path for avatar
                    if ($avatar && strpos($avatar, 'http') === false) {
                       $avatar = '../../' . $avatar; // Approximate path if local
                    }

                    // Mock Gamification Data if columns don't exist yet
                    $level = $user['level'] ?? 1;
                    $xp = $user['xp'] ?? 0;
                    $diamonds = $user['diamonds'] ?? 0; // Check if 'diamonds' exists or uses different name
                    $status = $user['uStatus'] ?? 'active';

                    // Calculate Level Progress Mock
                    $next_level_xp = $level * 1000;
                    $progress = min(100, round(($xp / $next_level_xp) * 100));
                    
                    // Safe JSON for onclick (re-map for JS compatibility)
                    $jsUser = [
                        'id' => $uid,
                        'username' => $username,
                        'email' => $email,
                        'avatar' => $avatar,
                        'level' => $level,
                        'xp' => $xp,
                        'diamonds' => $diamonds
                    ];
                    $userJson = htmlspecialchars(json_encode($jsUser), ENT_QUOTES, 'UTF-8');
                ?>
                <tr class="hover:bg-dark-700/50 transition group">
                    <td class="px-6 py-4">
                        <div class="flex items-center gap-3">
                             <div class="w-10 h-10 rounded-full bg-brand-500/20 text-brand-400 flex items-center justify-center font-bold text-lg overflow-hidden border border-brand-500/30">
                                <?php if ($avatar && $avatar !== 'default.png'): ?>
                                    <img src="<?php echo htmlspecialchars($avatar); ?>" class="w-full h-full object-cover">
                                <?php else: ?>
                                    <?php echo strtoupper(substr($username, 0, 1)); ?>
                                <?php endif; ?>
                            </div>
                            <div>
                                <p class="text-white font-bold group-hover:text-brand-400 transition"><?php echo htmlspecialchars($username); ?></p>
                                <p class="text-xs text-gray-500"><?php echo htmlspecialchars($email); ?></p>
                            </div>
                        </div>
                    </td>
                    <td class="px-6 py-4">
                        <div class="flex items-center gap-2 mb-1">
                            <span class="px-2 py-0.5 bg-brand-600 text-white text-[10px] font-bold rounded-md shadow">Lvl <?php echo $level; ?></span>
                            <span class="text-xs text-brand-300"><?php echo number_format($xp); ?> XP</span>
                        </div>
                        <div class="w-24 bg-dark-900 rounded-full h-1.5 border border-dark-700">
                            <div class="bg-gradient-to-r from-brand-500 to-pink-500 h-1.5 rounded-full" style="width: <?php echo $progress; ?>%"></div>
                        </div>
                    </td>
                    <td class="px-6 py-4 text-center">
                        <span class="font-mono text-yellow-400 font-bold bg-yellow-400/10 px-2 py-1 rounded inline-flex items-center gap-1">
                            <i class="fas fa-gem text-[10px]"></i> <?php echo number_format($diamonds); ?>
                        </span>
                    </td>
                    <td class="px-6 py-4 text-center">
                         <?php if ($status == '1'): // Assuming 1=active, 3=active? based on grep ?> 
                            <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium bg-green-500/20 text-green-400 border border-green-500/20">
                                <span class="w-1.5 h-1.5 rounded-full bg-green-500 animate-pulse"></span> Activo
                            </span>
                        <?php else: ?>
                             <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium bg-red-500/20 text-red-400 border border-red-500/20">
                                <i class="fas fa-ban text-[10px]"></i> Inactivo/Ban
                            </span>
                        <?php endif; ?>
                    </td>
                    <td class="px-6 py-4 text-center text-xs text-gray-500">
                        <?php echo isset($user['last_login']) ? $user['last_login'] : 'Nunca'; ?>
                    </td>
                    <td class="px-6 py-4 text-right">
                        <form method="POST" class="inline">
                            <input type="hidden" name="user_id" value="<?php echo $uid; ?>">
                            <?php if ($status == '1'): ?>
                                <button type="submit" name="action" value="ban" class="text-gray-500 hover:text-red-400 transition p-2 hover:bg-red-400/10 rounded-lg" title="Banear Usuario">
                                    <i class="fas fa-ban"></i>
                                </button>
                            <?php else: ?>
                                <button type="submit" name="action" value="unban" class="text-gray-500 hover:text-green-400 transition p-2 hover:bg-green-400/10 rounded-lg" title="Desbanear Usuario">
                                    <i class="fas fa-check"></i>
                                </button>
                            <?php endif; ?>
                            <button type="button" onclick='openEditModal(<?php echo $userJson; ?>)' class="text-gray-500 hover:text-white transition p-2 hover:bg-dark-700 rounded-lg ml-1" title="Editar Privilegios">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button type="button" onclick='openDiamondsModal(<?php echo $userJson; ?>)' class="text-yellow-500 hover:text-yellow-300 transition p-2 hover:bg-yellow-500/10 rounded-lg ml-1" title="Añadir Diamantes">
                                <i class="fas fa-coins"></i>
                            </button>
                            <button type="button" onclick='openPhotoEditor(<?php echo $userJson; ?>)' class="bg-red-600 text-white px-3 py-1 rounded ml-1 font-bold shadow-lg hover:bg-red-700 transition" title="Editor de Fotos">
                                FOTO/AVATAR
                            </button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        
        <?php if(empty($users)): ?>
            <div class="p-12 text-center">
                 <div class="w-16 h-16 bg-dark-900 rounded-full flex items-center justify-center mx-auto mb-4 text-gray-600">
                    <i class="fas fa-user-slash text-2xl"></i>
                </div>
                <h3 class="text-white font-bold mb-1">No se encontraron usuarios</h3>
                <p class="text-gray-500 text-sm">Intenta ajustar los filtros de búsqueda.</p>
            </div>
        <?php endif; ?>

    </div>
    <!-- Pagination Mock ... -->
    <div class="p-4 border-t border-dark-700 bg-dark-800 flex justify-between items-center text-xs text-gray-500">
        <span>Mostrando <?php echo count($users); ?> de <?php echo $total; ?> usuarios</span>
         <div class="flex gap-2">
            <!-- Mock Pagination -->
        </div>
    </div>
</div>

<!-- Edit Privileges Modal (Existing) -->
<div id="editModal" class="fixed inset-0 z-50 hidden">
    <!-- ... (Keep existing content, just hidden for brevity in replaced chunk if not modifying internal logic) ... -->
    <div class="absolute inset-0 bg-black/80 backdrop-blur-sm" onclick="closeModal('editModal')"></div>
    <div class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-full max-w-lg bg-dark-800 rounded-2xl border border-dark-700 shadow-2xl overflow-hidden">
        <!-- Re-injecting content to persist it because I am replacing the block -->
        <div class="p-6 border-b border-dark-700 flex justify-between items-center bg-dark-900/50">
            <h3 class="text-xl font-bold text-white">Editar Privilegios</h3>
            <button onclick="closeModal('editModal')" class="text-gray-400 hover:text-white"><i class="fas fa-times"></i></button>
        </div>
        <div class="p-6 space-y-4">
            <input type="hidden" id="editUserId">
            <div>
                 <label class="block text-sm font-medium text-gray-400 mb-2">Rol del Usuario</label>
                <select id="editRole" class="w-full bg-dark-900 border border-dark-700 rounded-xl px-4 py-3 text-white focus:border-brand-500 focus:outline-none">
                    <option value="user">Usuario Normal</option>
                    <option value="moderator">Moderador</option>
                    <option value="admin">Administrador</option>
                    <option value="super_admin">Super Admin</option>
                </select>
            </div>
            <div class="flex items-center justify-between p-4 bg-dark-900 rounded-xl border border-dark-700">
                <span class="text-white font-medium">Cuenta Verificada</span>
                <label class="relative inline-flex items-center cursor-pointer">
                    <input type="checkbox" id="editVerified" class="sr-only peer">
                    <div class="w-11 h-6 bg-dark-700 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-brand-600"></div>
                </label>
            </div>
            <div>
                 <label class="block text-sm font-medium text-gray-400 mb-2">Permisos</label>
                <div class="space-y-2" id="editPermissionsContainer"></div>
            </div>
        </div>
        <div class="p-6 border-t border-dark-700 flex justify-end gap-3 bg-dark-900/50">
            <button onclick="closeModal('editModal')" class="px-4 py-2 rounded-xl text-gray-400 hover:bg-dark-700 transition">Cancelar</button>
            <button onclick="saveUserChanges()" class="px-6 py-2 rounded-xl bg-brand-600 text-white font-bold hover:bg-brand-700 transition">Guardar</button>
        </div>
    </div>
</div>

<!-- Diamonds Modal (Existing) -->
<div id="diamondsModal" class="fixed inset-0 z-50 hidden">
    <div class="absolute inset-0 bg-black/80 backdrop-blur-sm" onclick="closeModal('diamondsModal')"></div>
    <div class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-full max-w-sm bg-dark-800 rounded-2xl border border-dark-700 shadow-2xl">
         <div class="p-6 text-center">
            <div class="w-16 h-16 bg-yellow-500/20 rounded-full flex items-center justify-center mx-auto mb-4 border border-yellow-500/30">
                <i class="fas fa-coins text-2xl text-yellow-500"></i>
            </div>
            <h3 class="text-xl font-bold text-white mb-2">Añadir Diamantes</h3>
            <p class="text-gray-400 text-sm mb-6">Añadir saldo a <span id="diamondUsername" class="text-white font-medium">Usuario</span></p>
            <input type="hidden" id="diamondUserId">
             <input type="number" id="diamondAmount" placeholder="Cantidad (ej: 500)" class="w-full bg-dark-900 border border-dark-700 rounded-xl px-4 py-3 text-white text-center text-xl font-bold mb-6 focus:border-yellow-500 focus:outline-none">
            <div class="flex gap-3">
                <button onclick="closeModal('diamondsModal')" class="flex-1 px-4 py-3 rounded-xl bg-dark-700 text-white font-medium hover:bg-dark-600 transition">Cancelar</button>
                <button onclick="saveDiamonds()" class="flex-1 px-4 py-3 rounded-xl bg-yellow-500 text-black font-bold hover:bg-yellow-400 transition">Confirmar</button>
            </div>
        </div>
    </div>
</div>

<!-- NEW: Photo Editor Modal -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.js"></script>

<div id="photoEditorModal" class="fixed inset-0 z-[60] hidden">
    <div class="absolute inset-0 bg-black/90 backdrop-blur-sm" onclick="closeModal('photoEditorModal')"></div>
    <div class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-full max-w-4xl bg-dark-900 rounded-2xl border border-dark-700 shadow-2xl flex flex-col max-h-[90vh]">
        
        <!-- Header -->
        <div class="p-6 border-b border-dark-700 flex justify-between items-center bg-dark-800">
            <div>
                 <h3 class="text-xl font-bold text-white">Editor de Fotos Moderno</h3>
                <p class="text-sm text-gray-400">Personaliza Avatar y Portada para <span id="editorUsername" class="text-brand-400">User</span></p>
            </div>
            <button onclick="closeModal('photoEditorModal')" class="text-gray-400 hover:text-white"><i class="fas fa-times text-xl"></i></button>
        </div>

        <!-- Body -->
        <div class="flex-1 overflow-hidden flex flex-col md:flex-row">
            <!-- Sidebar Controls -->
            <div class="w-full md:w-64 bg-dark-800 p-6 flex flex-col gap-6 border-r border-dark-700">
                
                <!-- Toggle Type -->
                <div class="flex bg-dark-900 p-1 rounded-lg">
                    <button onclick="setEditorType('avatar')" id="btnTypeAvatar" class="flex-1 py-2 text-sm font-bold rounded-md bg-brand-600 text-white shadow transition">Avatar</button>
                    <button onclick="setEditorType('cover')" id="btnTypeCover" class="flex-1 py-2 text-sm font-bold rounded-md text-gray-400 hover:text-white transition">Portada</button>
                </div>

                <!-- Upload Button -->
                <div class="relative group">
                    <input type="file" id="imageInput" accept="image/*" class="absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10" onchange="previewImage(this)">
                    <div class="w-full py-4 border-2 border-dashed border-dark-600 rounded-xl flex flex-col items-center justify-center text-gray-500 group-hover:border-brand-500 group-hover:text-brand-500 transition">
                         <i class="fas fa-cloud-upload-alt text-2xl mb-2"></i>
                        <span class="text-xs font-bold uppercase">Subir Imagen</span>
                    </div>
                </div>

                <!-- Info -->
                <div class="text-xs text-gray-500 leading-relaxed">
                    <p class="mb-2"><strong class="text-gray-300">Avatar:</strong> Recorte (1:1). Ideal para perfiles.</p>
                    <p><strong class="text-gray-300">Portada:</strong> Recorte (16:9). Se mostrará en el encabezado del perfil.</p>
                </div>

                 <div class="mt-auto">
                    <button onclick="cropAndSave()" class="w-full py-3 rounded-xl bg-brand-600 text-white font-bold hover:bg-brand-700 shadow-lg shadow-brand-500/20 transition flex items-center justify-center gap-2">
                        <i class="fas fa-save"></i> Guardar Cambios
                    </button>
                </div>
            </div>

            <!-- Canvas Area -->
            <div class="flex-1 bg-black flex items-center justify-center relative bg-[url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAABVJREFUOE9jZACD/0Bs40ABoxs4MAAAg00L/X3p38YAAAAASUVORK5CYII=')]">
                <div class="max-w-full max-h-full p-4">
                     <img id="editorImage" src="" class="max-w-full max-h-[60vh] hidden">
                     <div id="editorPlaceholder" class="text-center text-gray-600">
                        <i class="fas fa-image text-6xl mb-4 opacity-20"></i>
                        <p>Selecciona una imagen para editar</p>
                     </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Auth helper (mock) - ideally get from localStorage or cookie if standard auth used
function getToken() {
    return localStorage.getItem('klkapp_token') || 'dummy_token_if_cookie_auth';
}

function closeModal(id) {
    document.getElementById(id).classList.add('hidden');
}

// Reuse existing open helper if present, else define generic
function openModal(id) {
    document.getElementById(id).classList.remove('hidden');
}

let cropper;
let currentEditorType = 'avatar';
let editorUserId = null;

function openPhotoEditor(user) {
    editorUserId = user.id;
    document.getElementById('editorUsername').textContent = user.username;
    
    // Reset view
    document.getElementById('editorImage').src = '';
    document.getElementById('editorImage').classList.add('hidden');
    document.getElementById('editorPlaceholder').classList.remove('hidden');
    if (cropper) cropper.destroy();

    // Reset Input
    document.getElementById('imageInput').value = '';

    setEditorType('avatar');
    document.getElementById('photoEditorModal').classList.remove('hidden');
}

function setEditorType(type) {
    currentEditorType = type;
    
    // Update Tabs
    const btnAvatar = document.getElementById('btnTypeAvatar');
    const btnCover = document.getElementById('btnTypeCover');
    
    if (type === 'avatar') {
        btnAvatar.classList.add('bg-brand-600', 'text-white', 'shadow');
        btnAvatar.classList.remove('text-gray-400');
        btnCover.classList.remove('bg-brand-600', 'text-white', 'shadow');
        btnCover.classList.add('text-gray-400');
    } else {
        btnCover.classList.add('bg-brand-600', 'text-white', 'shadow');
        btnCover.classList.remove('text-gray-400');
        btnAvatar.classList.remove('bg-brand-600', 'text-white', 'shadow');
        btnAvatar.classList.add('text-gray-400');
    }

    // Update Cropper Ratio if active
    if (cropper) {
        cropper.setAspectRatio(type === 'avatar' ? 1 : 16 / 9);
    }
}

function previewImage(input) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const img = document.getElementById('editorImage');
            img.src = e.target.result;
            img.classList.remove('hidden');
            document.getElementById('editorPlaceholder').classList.add('hidden');
            
            if (cropper) cropper.destroy();
            
            cropper = new Cropper(img, {
                aspectRatio: currentEditorType === 'avatar' ? 1 : 16 / 9,
                viewMode: 1,
                dragMode: 'move',
                autoCropArea: 1,
                restore: false,
                guides: true,
                center: true,
                highlight: false,
                cropBoxMovable: true,
                cropBoxResizable: true,
                toggleDragModeOnDblclick: false,
            });
        }
        reader.readAsDataURL(input.files[0]);
    }
}

async function cropAndSave() {
    if (!cropper) return alert('Primero sube una imagen.');
    
    // Get Blob
    cropper.getCroppedCanvas({
        width: currentEditorType === 'avatar' ? 500 : 1280,
        height: currentEditorType === 'avatar' ? 500 : 720,
        fillColor: '#fff', // for transparency
        imageSmoothingEnabled: true,
        imageSmoothingQuality: 'high',
    }).toBlob(async (blob) => {
        const formData = new FormData();
        formData.append('image', blob, 'image.jpg'); // Send blob as file
        formData.append('type', currentEditorType); // 'avatar' or 'cover'
        formData.append('target_user_id', editorUserId);
        
        const token = getToken();
        // if (!token) return alert('Session Error: No Token');

        try {
            // Updated Endpoint: Relative path from users.php
            const res = await fetch('../api/upload/image.php', {
                method: 'POST',
                headers: { 'Authorization': `Bearer ${token}` },
                body: formData
            });
            const data = await res.json();
            
            if (data.success) {
                alert('¡Imagen actualizada con éxito!');
                location.reload();
            } else {
                alert('Error: ' + (data.error || 'Desconocido'));
            }
        } catch(e) {
            alert('Error de red: ' + e.message);
        }
    }, 'image/jpeg', 0.9);
}
</script>

<?php renderAdminFooter(); ?>
