<?php
$title = 'Equipos - Sistema de Gestión de Proyectos';
$page_title = 'Gestión de Equipos';
$current_page = 'teams';
$showSidebar = true;
$csrf_token = csrf_token();

ob_start();
?>

<div class="max-w-7xl mx-auto">
    <div class="mb-6">
        <h2 class="text-2xl font-bold text-gray-900">Gestión de Equipos</h2>
        <p class="text-gray-600 mt-1">Administra los equipos de trabajo y sus miembros</p>
    </div>

    <div class="grid grid-cols-1 gap-6">
        <?php foreach ($teams as $team): ?>
        <div class="bg-white shadow rounded-lg p-6">
            <div class="flex items-center justify-between mb-4">
                <div>
                    <h3 class="text-lg font-semibold text-gray-900"><?= htmlspecialchars($team['name']) ?></h3>
                    <p class="text-sm text-gray-500">Código: <?= htmlspecialchars($team['code']) ?></p>
                </div>
                <div class="flex items-center space-x-2">
                    <span class="px-2 py-1 text-xs font-semibold rounded-full <?= $team['is_active'] ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800' ?>">
                        <?= $team['is_active'] ? 'Activo' : 'Inactivo' ?>
                    </span>
                    <button onclick="openAddMemberModal(<?= $team['id'] ?>, '<?= htmlspecialchars($team['name'], ENT_QUOTES) ?>')" 
                            class="px-3 py-1 bg-blue-600 text-white text-sm rounded-md hover:bg-blue-700">
                        <i class="fas fa-user-plus mr-1"></i> Agregar Miembro
                    </button>
                </div>
            </div>
            
            <?php if ($team['description']): ?>
            <p class="text-sm text-gray-600 mb-4"><?= htmlspecialchars($team['description']) ?></p>
            <?php endif; ?>
            
            <div class="mt-4">
                <h4 class="text-sm font-medium text-gray-700 mb-3">Miembros (<?= count($team['members']) ?>)</h4>
                
                <?php if (empty($team['members'])): ?>
                <p class="text-sm text-gray-500 italic">No hay miembros asignados a este equipo</p>
                <?php else: ?>
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Nombre</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Email</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Rol</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Líder</th>
                                <th class="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase">Acciones</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php foreach ($team['members'] as $member): ?>
                            <tr>
                                <td class="px-4 py-3 whitespace-nowrap">
                                    <div class="flex items-center">
                                        <div class="h-8 w-8 rounded-full bg-blue-100 flex items-center justify-center mr-2">
                                            <span class="text-xs font-medium text-blue-600">
                                                <?= strtoupper(substr($member['first_name'], 0, 1) . substr($member['last_name'], 0, 1)) ?>
                                            </span>
                                        </div>
                                        <span class="text-sm font-medium text-gray-900">
                                            <?= htmlspecialchars($member['first_name'] . ' ' . $member['last_name']) ?>
                                        </span>
                                    </div>
                                </td>
                                <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                                    <?= htmlspecialchars($member['email']) ?>
                                </td>
                                <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                                    <?= htmlspecialchars($member['role_name'] ?? 'Sin rol') ?>
                                </td>
                                <td class="px-4 py-3 whitespace-nowrap">
                                    <label class="flex items-center cursor-pointer">
                                        <input type="checkbox" 
                                               <?= $member['is_leader'] ? 'checked' : '' ?>
                                               onchange="toggleLeader(<?= $member['member_id'] ?>, this.checked)"
                                               class="form-checkbox h-4 w-4 text-blue-600 rounded">
                                        <span class="ml-2 text-sm text-gray-700">Líder</span>
                                    </label>
                                </td>
                                <td class="px-4 py-3 whitespace-nowrap text-right text-sm">
                                    <button onclick="removeMember(<?= $member['member_id'] ?>, '<?= htmlspecialchars($member['first_name'] . ' ' . $member['last_name'], ENT_QUOTES) ?>')" 
                                            class="text-red-600 hover:text-red-900">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- Modal Agregar Miembro -->
<div id="addMemberModal" class="hidden fixed z-50 inset-0 overflow-y-auto">
    <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"></div>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
            <form id="addMemberForm">
                <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                <input type="hidden" name="action" value="add_member">
                <input type="hidden" id="team_id" name="team_id" value="">
                
                <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <h3 id="modal-title" class="text-lg font-medium text-gray-900 mb-4">Agregar Miembro</h3>
                    
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Usuario</label>
                        <select name="user_id" id="user_id" required class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">
                            <option value="">-- Seleccionar usuario --</option>
                            <?php foreach ($users as $user): ?>
                            <option value="<?= $user['id'] ?>">
                                <?= htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) ?>
                                <?= $user['role_name'] ? ' - ' . htmlspecialchars($user['role_name']) : '' ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="mb-4">
                        <label class="flex items-center cursor-pointer">
                            <input type="checkbox" name="is_leader" value="1" class="form-checkbox h-4 w-4 text-blue-600 rounded">
                            <span class="ml-2 text-sm text-gray-700">Designar como líder del equipo</span>
                        </label>
                    </div>
                </div>
                
                <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <button type="submit" class="w-full sm:w-auto sm:ml-3 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
                        Agregar
                    </button>
                    <button type="button" onclick="closeAddMemberModal()" class="mt-3 sm:mt-0 w-full sm:w-auto px-4 py-2 bg-white text-gray-700 border border-gray-300 rounded-md hover:bg-gray-50">
                        Cancelar
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function openAddMemberModal(teamId, teamName) {
    document.getElementById('team_id').value = teamId;
    document.getElementById('modal-title').textContent = 'Agregar Miembro a ' + teamName;
    document.getElementById('addMemberModal').classList.remove('hidden');
}

function closeAddMemberModal() {
    document.getElementById('addMemberModal').classList.add('hidden');
    document.getElementById('addMemberForm').reset();
}

document.getElementById('addMemberForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    try {
        const response = await fetch('/admin/teams', {
            method: 'POST',
            body: new URLSearchParams(formData)
        });
        
        const data = await response.json();
        
        if (data.success) {
            showToast(data.message, 'success');
            closeAddMemberModal();
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast(data.message, 'error');
        }
    } catch (error) {
        console.error('Error:', error);
        showToast('Error de conexión', 'error');
    }
});

async function removeMember(memberId, memberName) {
    if (!confirm('¿Estás seguro de eliminar a ' + memberName + ' del equipo?')) return;
    
    try {
        const response = await fetch('/admin/teams', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                action: 'remove_member',
                member_id: memberId,
                csrf_token: '<?= $csrf_token ?>'
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            showToast(data.message, 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast(data.message, 'error');
        }
    } catch (error) {
        console.error('Error:', error);
        showToast('Error de conexión', 'error');
    }
}

async function toggleLeader(memberId, isLeader) {
    try {
        const response = await fetch('/admin/teams', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                action: 'toggle_leader',
                member_id: memberId,
                is_leader: isLeader ? '1' : '0',
                csrf_token: '<?= $csrf_token ?>'
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            showToast(data.message, 'success');
        } else {
            showToast(data.message, 'error');
            setTimeout(() => location.reload(), 1000);
        }
    } catch (error) {
        console.error('Error:', error);
        showToast('Error de conexión', 'error');
    }
}
</script>

<?php
$content = ob_get_clean();
include __DIR__ . '/../layouts/app.php';
?>
