#!/bin/bash
# ================================================================
# OKRFEDEF — Sprint 09: Gestión de organización y proyectos
# Setup inicial, usuarios, navegación principal
# Ejecutar desde: /home/evolucionamos/public_html/estrategia
# Comando: bash sprint_09_setup.sh
# ================================================================
set -e
echo "========================================="
echo "  OKRFEDEF — Sprint 09: Setup y navegación"
echo "========================================="

php artisan make:controller OrganizationController
php artisan make:controller ProjectController
php artisan make:controller UserManagementController

echo ">>> Archivos base creados. Escribiendo lógica..."

# ── 1. ORGANIZATION CONTROLLER ───────────────────────────────────
cat > app/Http/Controllers/OrganizationController.php << 'PHP'
<?php
namespace App\Http\Controllers;

use App\Models\Organization;
use App\Models\Project;
use Illuminate\Http\Request;
use Inertia\Inertia;

class OrganizationController extends Controller
{
    public function index()
    {
        $organizations = Organization::with('projects')->get();
        return Inertia::render('Setup/Organizations', [
            'organizations' => $organizations,
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:200',
            'slug' => 'required|string|unique:organizations|max:100',
        ]);

        $org = Organization::create([
            'name'     => $request->name,
            'slug'     => $request->slug,
            'settings' => [],
        ]);

        return redirect()->route('organizations.index')
            ->with('success', 'Organización creada exitosamente.');
    }
}
PHP

# ── 2. PROJECT CONTROLLER ────────────────────────────────────────
cat > app/Http/Controllers/ProjectController.php << 'PHP'
<?php
namespace App\Http\Controllers;

use App\Models\Cycle;
use App\Models\Organization;
use App\Models\Project;
use Illuminate\Http\Request;
use Inertia\Inertia;

class ProjectController extends Controller
{
    public function index()
    {
        $projects = Project::with(['organization', 'cycles' => fn($q) => $q->where('status','active')])
            ->orderByDesc('created_at')->get();

        return Inertia::render('Setup/Projects', [
            'projects'      => $projects,
            'organizations' => Organization::all(['id','name']),
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'organization_id' => 'required|exists:organizations,id',
            'name'            => 'required|string|max:200',
            'period_start'    => 'required|date',
            'period_end'      => 'required|date|after:period_start',
        ]);

        $project = Project::create([
            'organization_id' => $request->organization_id,
            'name'            => $request->name,
            'description'     => $request->description,
            'period_start'    => $request->period_start,
            'period_end'      => $request->period_end,
            'status'          => 'setup',
        ]);

        // Crear primer ciclo automáticamente
        $year    = now()->year;
        $quarter = ceil(now()->month / 3);
        Cycle::create([
            'project_id' => $project->id,
            'quarter'    => $quarter,
            'year'       => $year,
            'start_date' => now()->startOfQuarter(),
            'end_date'   => now()->endOfQuarter(),
            'status'     => 'active',
        ]);

        return redirect()->route('projects.show', $project->id);
    }

    public function show(Project $project)
    {
        $project->load(['organization', 'cycles', 'dofaSessions', 'strategicBets']);
        $activeCycle = $project->cycles()->where('status','active')->latest()->first();

        return Inertia::render('Setup/ProjectHome', [
            'project'     => $project,
            'activeCycle' => $activeCycle,
            'stats'       => [
                'dofa_done'   => $project->dofaSessions()->where('status','completed')->exists(),
                'bets_count'  => $project->strategicBets()->count(),
                'cycles'      => $project->cycles()->count(),
            ],
        ]);
    }

    public function activate(Project $project)
    {
        $project->update(['status' => 'active']);
        return response()->json(['project' => $project]);
    }
}
PHP

# ── 3. USER MANAGEMENT CONTROLLER ───────────────────────────────
cat > app/Http/Controllers/UserManagementController.php << 'PHP'
<?php
namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Inertia\Inertia;
use Spatie\Permission\Models\Role;

class UserManagementController extends Controller
{
    public function index()
    {
        return Inertia::render('Setup/Users', [
            'users' => User::with('roles')->orderBy('name')->get(),
            'roles' => Role::all(['id','name']),
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name'  => 'required|string|max:200',
            'email' => 'required|email|unique:users',
            'role'  => 'required|exists:roles,name',
        ]);

        $tempPassword = Str::random(12);

        $user = User::create([
            'name'              => $request->name,
            'email'             => $request->email,
            'password'          => Hash::make($tempPassword),
            'email_verified_at' => now(),
        ]);

        $user->assignRole($request->role);

        return response()->json([
            'user'          => $user->load('roles'),
            'temp_password' => $tempPassword,
            'message'       => "Usuario creado. Contraseña temporal: {$tempPassword}",
        ]);
    }

    public function assignRole(Request $request, User $user)
    {
        $request->validate(['role' => 'required|exists:roles,name']);
        $user->syncRoles([$request->role]);
        return response()->json(['user' => $user->load('roles')]);
    }
}
PHP

# ── 4. SEEDER FEDEF ──────────────────────────────────────────────
cat > database/seeders/FedefSeeder.php << 'PHP'
<?php
namespace Database\Seeders;

use App\Models\Cycle;
use App\Models\DofaFactor;
use App\Models\Organization;
use App\Models\Project;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class FedefSeeder extends Seeder
{
    public function run(): void
    {
        // Organización FEDEF
        $org = Organization::firstOrCreate(
            ['slug' => 'fedef'],
            [
                'name'   => 'Fondo de Empleados del Sector Empresarial Colombiano',
                'active' => true,
            ]
        );

        // Proyecto plan estratégico 2026-2028
        $project = Project::firstOrCreate(
            ['organization_id' => $org->id, 'name' => 'Plan Estratégico 2026-2028'],
            [
                'period_start' => '2026-01-01',
                'period_end'   => '2028-12-31',
                'status'       => 'active',
            ]
        );

        // Ciclo Q2 2026
        Cycle::firstOrCreate(
            ['project_id' => $project->id, 'quarter' => 2, 'year' => 2026],
            [
                'start_date' => '2026-04-01',
                'end_date'   => '2026-06-30',
                'status'     => 'active',
            ]
        );

        // Usuario consultor (FYCLS)
        $consultor = User::firstOrCreate(
            ['email' => 'consultor@fycls.com'],
            [
                'name'              => 'Consultor FYCLS',
                'password'          => Hash::make('okr2026fedef'),
                'email_verified_at' => now(),
            ]
        );
        $consultor->syncRoles(['consultor']);

        // Usuario gerente FEDEF
        $gerente = User::firstOrCreate(
            ['email' => 'gerente@fedef.com.co'],
            [
                'name'              => 'Natalia Forero Duran',
                'password'          => Hash::make('fedef2026'),
                'email_verified_at' => now(),
            ]
        );
        $gerente->syncRoles(['sponsor']);

        // Factores DOFA del plan anterior (precargados para el retiro)
        $factors = [
            ['type' => 'F', 'description' => 'Excelente reputación y confianza de los asociados', 'order' => 1],
            ['type' => 'F', 'description' => 'Solidez financiera y cultura de pago de los asociados', 'order' => 2],
            ['type' => 'F', 'description' => 'Agilidad operativa frente a entidades de mayor tamaño', 'order' => 3],
            ['type' => 'F', 'description' => 'Atención personalizada y cercanía con el asociado', 'order' => 4],
            ['type' => 'F', 'description' => 'Cumplimiento SIAR y gestión de riesgos sólida', 'order' => 5],
            ['type' => 'F', 'description' => 'Cultura de pago y bajo índice de mora (1.5%)', 'order' => 6],
            ['type' => 'F', 'description' => 'Productos competitivos en tasas y condiciones', 'order' => 7],

            ['type' => 'D', 'description' => 'Forma del manejo de comunicaciones con los asociados', 'order' => 1],
            ['type' => 'D', 'description' => 'Baja colocación de crédito (49.3% vs meta 60%)', 'order' => 2],
            ['type' => 'D', 'description' => 'Sistema de gestión por procesos incompleto (85%)', 'order' => 3],
            ['type' => 'D', 'description' => 'Ausencia de productos segmentados por base social', 'order' => 4],
            ['type' => 'D', 'description' => 'Adopción digital baja (46.9% vs meta 60%)', 'order' => 5],
            ['type' => 'D', 'description' => 'Poca cobertura en medición de satisfacción (8.6%)', 'order' => 6],

            ['type' => 'O', 'description' => 'Mercado potencial importante en el sector empresarial', 'order' => 1],
            ['type' => 'O', 'description' => 'Herramientas tecnológicas e IA al alcance del sector', 'order' => 2],
            ['type' => 'O', 'description' => 'Modelo de outsourcing para vinculación de empresas', 'order' => 3],
            ['type' => 'O', 'description' => 'Mercado de convenios y alianzas estratégicas', 'order' => 4],
            ['type' => 'O', 'description' => 'Política pública favorable al sector solidario', 'order' => 5],
            ['type' => 'O', 'description' => 'Ley de vivienda con cobertura para el sector solidario', 'order' => 6],

            ['type' => 'A', 'description' => 'Normatividad SES sobre vínculo de asociatividad', 'order' => 1],
            ['type' => 'A', 'description' => 'Banca virtual y competencia fintech en crédito', 'order' => 2],
            ['type' => 'A', 'description' => 'Apatía al conocimiento del modelo solidario', 'order' => 3],
            ['type' => 'A', 'description' => 'Aumento en la regulación de entes de vigilancia', 'order' => 4],
            ['type' => 'A', 'description' => 'Sobreendeudamiento de asociados', 'order' => 5],
            ['type' => 'A', 'description' => 'Inestabilidad política y social del país', 'order' => 6],
        ];

        foreach ($factors as $f) {
            DofaFactor::firstOrCreate(
                ['project_id' => $project->id, 'type' => $f['type'], 'description' => $f['description']],
                ['order' => $f['order'], 'created_by' => $consultor->id, 'importance' => 0.05, 'priority' => 6]
            );
        }

        echo "FEDEF configurado:\n";
        echo "  Organización: {$org->name}\n";
        echo "  Proyecto: {$project->name}\n";
        echo "  Consultor: consultor@fycls.com / okr2026fedef\n";
        echo "  Gerente: gerente@fedef.com.co / fedef2026\n";
        echo "  " . count($factors) . " factores DOFA pre-cargados\n";
    }
}
PHP

# ── 5. RUTAS ─────────────────────────────────────────────────────
cat >> routes/web.php << 'PHP'

// ── Setup Routes ──────────────────────────────────────────────────
use App\Http\Controllers\OrganizationController;
use App\Http\Controllers\ProjectController;
use App\Http\Controllers\UserManagementController;

Route::middleware(['auth', 'verified'])->group(function () {
    Route::get('/',                    [ProjectController::class, 'index'])->name('home');
    Route::get('/projects',            [ProjectController::class, 'index'])->name('projects.index');
    Route::post('/projects',           [ProjectController::class, 'store'])->name('projects.store');
    Route::get('/projects/{project}',  [ProjectController::class, 'show'])->name('projects.show');
    Route::post('/projects/{project}/activate', [ProjectController::class, 'activate'])->name('projects.activate');

    Route::get('/organizations',       [OrganizationController::class, 'index'])->name('organizations.index');
    Route::post('/organizations',      [OrganizationController::class, 'store'])->name('organizations.store');

    Route::get('/users',               [UserManagementController::class, 'index'])->name('users.index');
    Route::post('/users',              [UserManagementController::class, 'store'])->name('users.store');
    Route::post('/users/{user}/role',  [UserManagementController::class, 'assignRole'])->name('users.role');
});
PHP

# ── 6. VISTAS VUE ────────────────────────────────────────────────
mkdir -p resources/js/Pages/Setup

# Home / Lista de proyectos
cat > resources/js/Pages/Setup/Projects.vue << 'VUE'
<script setup>
import { ref } from 'vue'
import { router } from '@inertiajs/vue3'
import AppLayout from '@/Layouts/AppLayout.vue'

const props = defineProps({
    projects: Array,
    organizations: Array,
})

const showForm = ref(false)
const form = ref({ organization_id: '', name: '', description: '', period_start: '2026-01-01', period_end: '2028-12-31' })
const submitting = ref(false)

const submit = () => {
    submitting.value = true
    router.post(route('projects.store'), form.value, {
        onError: () => { submitting.value = false },
    })
}

const statusColors = { setup: 'bg-yellow-100 text-yellow-800', active: 'bg-green-100 text-green-800', closed: 'bg-gray-100 text-gray-600' }
const statusLabels = { setup: 'Configuración', active: 'Activo', closed: 'Cerrado' }
</script>

<template>
    <AppLayout title="Proyectos estratégicos">
        <div class="max-w-4xl mx-auto px-4 py-8">

            <div class="flex justify-between items-center mb-8">
                <div>
                    <h1 class="text-2xl font-bold text-gray-900">OKRFEDEF</h1>
                    <p class="text-gray-500">Plataforma de estrategia emergente</p>
                </div>
                <button @click="showForm = !showForm"
                        class="bg-green-600 text-white px-4 py-2 rounded-xl text-sm font-medium hover:bg-green-700">
                    + Nuevo proyecto
                </button>
            </div>

            <!-- Formulario -->
            <div v-if="showForm" class="bg-white rounded-2xl shadow p-6 mb-6 border-2 border-green-200">
                <h2 class="font-semibold mb-4">Nuevo plan estratégico</h2>
                <div class="grid grid-cols-2 gap-3">
                    <div class="col-span-2">
                        <label class="text-xs font-semibold text-gray-600 uppercase block mb-1">Organización</label>
                        <select v-model="form.organization_id" class="w-full border border-gray-300 rounded-lg p-2 text-sm">
                            <option value="">Seleccionar...</option>
                            <option v-for="org in organizations" :key="org.id" :value="org.id">{{ org.name }}</option>
                        </select>
                    </div>
                    <div class="col-span-2">
                        <label class="text-xs font-semibold text-gray-600 uppercase block mb-1">Nombre del plan</label>
                        <input v-model="form.name" placeholder="Ej: Plan Estratégico 2026-2028"
                               class="w-full border border-gray-300 rounded-lg p-2 text-sm" />
                    </div>
                    <div>
                        <label class="text-xs font-semibold text-gray-600 uppercase block mb-1">Inicio</label>
                        <input v-model="form.period_start" type="date" class="w-full border border-gray-300 rounded-lg p-2 text-sm" />
                    </div>
                    <div>
                        <label class="text-xs font-semibold text-gray-600 uppercase block mb-1">Fin</label>
                        <input v-model="form.period_end" type="date" class="w-full border border-gray-300 rounded-lg p-2 text-sm" />
                    </div>
                    <div class="col-span-2 flex gap-2">
                        <button @click="submit" :disabled="submitting || !form.organization_id || !form.name"
                                class="bg-green-600 text-white px-4 py-2 rounded-lg text-sm font-medium disabled:bg-gray-300">
                            Crear proyecto
                        </button>
                        <button @click="showForm = false" class="text-gray-500 px-4 py-2 text-sm">Cancelar</button>
                    </div>
                </div>
            </div>

            <!-- Lista de proyectos -->
            <div class="space-y-3">
                <a v-for="project in projects" :key="project.id"
                   :href="route('projects.show', project.id)"
                   class="block bg-white rounded-2xl shadow hover:shadow-md transition-shadow p-5 border border-transparent hover:border-green-200">
                    <div class="flex justify-between items-start">
                        <div class="flex-1">
                            <div class="flex items-center gap-2 mb-1">
                                <span :class="['text-xs px-2 py-0.5 rounded-full font-medium', statusColors[project.status]]">
                                    {{ statusLabels[project.status] }}
                                </span>
                                <span class="text-xs text-gray-400">{{ project.organization?.name }}</span>
                            </div>
                            <h2 class="text-lg font-semibold text-gray-900">{{ project.name }}</h2>
                            <p class="text-sm text-gray-500 mt-1">
                                {{ project.period_start }} → {{ project.period_end }}
                            </p>
                        </div>
                        <span class="text-gray-400 text-lg">→</span>
                    </div>
                </a>

                <div v-if="!projects.length" class="text-center py-16 text-gray-400">
                    <p class="text-5xl mb-4">🎯</p>
                    <p class="text-xl font-medium">Sin proyectos aún</p>
                    <p class="text-sm mt-1">Crea el primer plan estratégico</p>
                </div>
            </div>
        </div>
    </AppLayout>
</template>
VUE

# Project Home (hub del proyecto)
cat > resources/js/Pages/Setup/ProjectHome.vue << 'VUE'
<script setup>
import AppLayout from '@/Layouts/AppLayout.vue'

const props = defineProps({
    project: Object,
    activeCycle: Object,
    stats: Object,
})

const modules = [
    { label: 'Diagnóstico DOFA', icon: '🔍', desc: 'Calificación colaborativa y análisis de IA', done: true, routeName: 'dofa.index' },
    { label: 'Estrategia Emergente', icon: '🎯', desc: 'Apuestas, capacidades y renuncias', done: true, routeName: 'strategy.aspiration' },
    { label: 'OKR Tree', icon: '🌳', desc: 'Árbol de objetivos y resultados clave', done: true, routeName: 'okr.tree' },
    { label: 'Sesión en vivo', icon: '🎙', desc: 'Consola del facilitador para los retiros', done: true, routeName: 'live.console' },
    { label: 'Dashboard Champion', icon: '📊', desc: 'Seguimiento semanal y agenda CFR', done: true, routeName: 'champion.dashboard' },
    { label: 'Vista Junta', icon: '👔', desc: 'Dashboard ejecutivo institucional', done: true, routeName: 'okr.board' },
    { label: 'Panel IA', icon: '🤖', desc: 'Chat con Claude y análisis histórico', done: true, routeName: 'ai.dashboard' },
]

const getRoute = (module) => {
    if (!props.activeCycle) return '#'
    const needsCycle = ['okr.tree','okr.board','champion.dashboard','okr.checkin','retro.index']
    if (needsCycle.includes(module.routeName)) {
        return route(module.routeName, [props.project.id, props.activeCycle.id])
    }
    return route(module.routeName, props.project.id)
}
</script>

<template>
    <AppLayout :title="project.name">
        <div class="max-w-4xl mx-auto px-4 py-8">

            <!-- Header -->
            <div class="mb-8">
                <p class="text-sm text-gray-400 mb-1">{{ project.organization?.name }}</p>
                <h1 class="text-3xl font-black text-gray-900">{{ project.name }}</h1>
                <div class="flex gap-3 mt-2 text-sm text-gray-500">
                    <span>{{ project.period_start }} → {{ project.period_end }}</span>
                    <span v-if="activeCycle">· Q{{ activeCycle.quarter }} {{ activeCycle.year }} activo</span>
                </div>
            </div>

            <!-- Indicadores rápidos -->
            <div class="grid grid-cols-3 gap-4 mb-8">
                <div class="bg-white rounded-xl shadow p-4 text-center">
                    <div class="text-3xl font-black text-green-600">{{ stats.dofa_done ? '✓' : '○' }}</div>
                    <div class="text-xs text-gray-500 mt-1">DOFA completado</div>
                </div>
                <div class="bg-white rounded-xl shadow p-4 text-center">
                    <div class="text-3xl font-black text-blue-600">{{ stats.bets_count }}</div>
                    <div class="text-xs text-gray-500 mt-1">Apuestas estratégicas</div>
                </div>
                <div class="bg-white rounded-xl shadow p-4 text-center">
                    <div class="text-3xl font-black text-purple-600">{{ stats.cycles }}</div>
                    <div class="text-xs text-gray-500 mt-1">Ciclos OKR</div>
                </div>
            </div>

            <!-- Módulos -->
            <h2 class="text-sm font-semibold text-gray-500 uppercase mb-4">Módulos del proyecto</h2>
            <div class="grid grid-cols-2 gap-3">
                <a v-for="mod in modules" :key="mod.routeName"
                   :href="getRoute(mod)"
                   class="bg-white rounded-2xl shadow hover:shadow-md transition-all p-5 flex gap-4 items-start group border border-transparent hover:border-green-200">
                    <div class="text-3xl">{{ mod.icon }}</div>
                    <div class="flex-1">
                        <h3 class="font-semibold text-gray-800 group-hover:text-green-700 transition-colors">{{ mod.label }}</h3>
                        <p class="text-xs text-gray-400 mt-0.5">{{ mod.desc }}</p>
                    </div>
                    <span class="text-gray-300 group-hover:text-green-500 text-lg transition-colors">→</span>
                </a>
            </div>
        </div>
    </AppLayout>
</template>
VUE

# Users management
cat > resources/js/Pages/Setup/Users.vue << 'VUE'
<script setup>
import { ref } from 'vue'
import AppLayout from '@/Layouts/AppLayout.vue'
import axios from 'axios'

const props = defineProps({
    users: Array,
    roles: Array,
})

const users = ref([...props.users])
const showForm = ref(false)
const form = ref({ name: '', email: '', role: 'owner' })
const submitting = ref(false)
const newUserPassword = ref(null)

const roleColors = {
    consultor: 'bg-purple-100 text-purple-800',
    sponsor:   'bg-blue-100 text-blue-800',
    champion:  'bg-green-100 text-green-800',
    owner:     'bg-yellow-100 text-yellow-800',
    junta:     'bg-gray-100 text-gray-700',
}

const submit = async () => {
    submitting.value = true
    try {
        const res = await axios.post(route('users.store'), form.value)
        newUserPassword.value = res.data.temp_password
        users.value.push(res.data.user)
        form.value = { name: '', email: '', role: 'owner' }
        showForm.value = false
    } catch (e) {
        console.error(e)
    } finally { submitting.value = false }
}

const changeRole = async (user, newRole) => {
    await axios.post(route('users.role', user.id), { role: newRole })
    user.roles = [{ name: newRole }]
}
</script>

<template>
    <AppLayout title="Gestión de usuarios">
        <div class="max-w-3xl mx-auto px-4 py-8">

            <div class="flex justify-between items-center mb-6">
                <h1 class="text-2xl font-bold text-gray-900">Usuarios</h1>
                <button @click="showForm = !showForm"
                        class="bg-blue-600 text-white px-4 py-2 rounded-xl text-sm font-medium hover:bg-blue-700">
                    + Agregar usuario
                </button>
            </div>

            <!-- Contraseña temporal -->
            <div v-if="newUserPassword" class="bg-green-50 border border-green-200 rounded-xl p-4 mb-4">
                <p class="text-sm font-semibold text-green-700">Usuario creado exitosamente</p>
                <p class="text-sm text-green-600 mt-1">Contraseña temporal: <strong class="font-mono">{{ newUserPassword }}</strong></p>
                <p class="text-xs text-green-500 mt-1">Comparte esta contraseña con el usuario. Podrá cambiarla al ingresar.</p>
                <button @click="newUserPassword = null" class="text-xs text-green-600 mt-2 hover:underline">Cerrar</button>
            </div>

            <!-- Formulario -->
            <div v-if="showForm" class="bg-white rounded-2xl shadow p-5 mb-6 border-2 border-blue-200">
                <h2 class="font-semibold mb-4">Nuevo usuario</h2>
                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="text-xs font-semibold text-gray-600 uppercase block mb-1">Nombre</label>
                        <input v-model="form.name" class="w-full border border-gray-300 rounded-lg p-2 text-sm" />
                    </div>
                    <div>
                        <label class="text-xs font-semibold text-gray-600 uppercase block mb-1">Email</label>
                        <input v-model="form.email" type="email" class="w-full border border-gray-300 rounded-lg p-2 text-sm" />
                    </div>
                    <div>
                        <label class="text-xs font-semibold text-gray-600 uppercase block mb-1">Rol</label>
                        <select v-model="form.role" class="w-full border border-gray-300 rounded-lg p-2 text-sm">
                            <option v-for="role in roles" :key="role.id" :value="role.name">{{ role.name }}</option>
                        </select>
                    </div>
                    <div class="flex items-end gap-2">
                        <button @click="submit" :disabled="submitting || !form.name || !form.email"
                                class="flex-1 bg-blue-600 text-white py-2 rounded-lg text-sm font-medium disabled:bg-gray-300">
                            {{ submitting ? 'Creando...' : 'Crear usuario' }}
                        </button>
                        <button @click="showForm = false" class="text-gray-500 text-sm px-2">✕</button>
                    </div>
                </div>
            </div>

            <!-- Lista de usuarios -->
            <div class="bg-white rounded-2xl shadow overflow-hidden">
                <div v-for="user in users" :key="user.id"
                     class="flex items-center gap-4 px-5 py-4 border-b border-gray-100 last:border-0">
                    <div class="w-10 h-10 bg-gray-200 rounded-full flex items-center justify-center font-bold text-gray-600">
                        {{ user.name.charAt(0).toUpperCase() }}
                    </div>
                    <div class="flex-1">
                        <p class="font-medium text-gray-800">{{ user.name }}</p>
                        <p class="text-sm text-gray-500">{{ user.email }}</p>
                    </div>
                    <select :value="user.roles[0]?.name"
                            @change="changeRole(user, $event.target.value)"
                            :class="['text-xs px-2 py-1 rounded-full font-medium border-0', roleColors[user.roles[0]?.name] || 'bg-gray-100 text-gray-700']">
                        <option v-for="role in roles" :key="role.id" :value="role.name">{{ role.name }}</option>
                    </select>
                </div>
            </div>
        </div>
    </AppLayout>
</template>
VUE

# ── 7. EJECUTAR SEEDER FEDEF ─────────────────────────────────────
php artisan db:seed --class=FedefSeeder

# ── 8. COMPILAR Y CACHEAR ────────────────────────────────────────
echo ">>> Compilando assets Vue..."
npm run build

php artisan config:clear
php artisan route:clear
php artisan config:cache
php artisan route:cache
php artisan view:cache

echo ""
echo "========================================="
echo "  Sprint 09 completado exitosamente"
echo ""
echo "  Módulos creados:"
echo "  ✅ OrganizationController"
echo "  ✅ ProjectController (hub del proyecto)"
echo "  ✅ UserManagementController"
echo "  ✅ FedefSeeder (datos reales FEDEF)"
echo "  ✅ 3 vistas: Projects, ProjectHome,"
echo "     Users"
echo "  ✅ Ruta home → lista de proyectos"
echo ""
echo "  FEDEF configurado:"
echo "  Consultor: consultor@fycls.com"
echo "  Contraseña: okr2026fedef"
echo "  Gerente: gerente@fedef.com.co"
echo "  Contraseña: fedef2026"
echo "  24 factores DOFA pre-cargados"
echo "========================================="
