<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Partner;
use App\Models\Role;
use Illuminate\Http\Request;
use App\Http\Requests\StoreUserRequest;
use Illuminate\Support\Facades\Hash;

class UserManagementController extends Controller
{
    public function create()
    {
        $partners = Partner::all();
        return view('users.create', compact('partners'));
    }

    public function store(StoreUserRequest $request)
    {
        $data = $request->validated();
        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => \Illuminate\Support\Facades\Hash::make($data['password']),
            'partner_id' => $data['role'] === 'partner-admin' ? $data['partner_id'] : null,
            'email_verified_at' => now(),
        ]);
        
        // Asignar rol
        $role = \App\Models\Role::where('name', $data['role'])->first();
        if ($role) {
            $user->roles()->sync([$role->id]);
        }

        // Asignar partners adicionales si se proporcionan
        if (isset($data['additional_partners_ids']) && !empty($data['additional_partners_ids'])) {
            $additionalPartnerIds = explode(',', $data['additional_partners_ids']);
            foreach ($additionalPartnerIds as $partnerId) {
                $partnerId = trim($partnerId);
                if ($partnerId && $partnerId != $data['partner_id']) {
                    \App\Models\PartnerInvite::create([
                        'user_id' => $user->id,
                        'partner_id' => $partnerId,
                        'status' => 'accepted'
                    ]);
                }
            }
        }
        // Si no hay partners adicionales, no hacer nada (es opcional)

        return redirect()->route('users.index')->with('success', 'User created successfully!');
    }

    public function index()
    {
        // Solo superadmin puede acceder
        $users = \App\Models\User::with('roles')->get();
        return view('users.management', compact('users'));
    }

    public function edit($id)
    {
        $user = \App\Models\User::findOrFail($id);
        $partners = Partner::all();
        
        return view('users.edit', compact('user', 'partners'));
    }

    public function update(StoreUserRequest $request, $id)
    {
        \Log::info('UserManagementController update', [
            'id' => $id,
            'request_method' => $request->method(),
            'route_parameters' => $request->route()->parameters()
        ]);
        
        $user = \App\Models\User::findOrFail($id);
        
        // Pasar el ID al request para la validación
        $request->merge(['user_id' => $id]);
        
        $data = $request->validated();
        
        $user->name = $data['name'];
        $user->email = $data['email'];
        $user->partner_id = $data['role'] === 'partner-admin' ? $data['partner_id'] : null;
        $user->is_active = isset($data['is_active']) && $data['is_active'] ? true : false;
        
        // Solo actualizar password si se proporciona uno nuevo
        if (isset($data['password']) && !empty($data['password'])) {
            $user->password = \Illuminate\Support\Facades\Hash::make($data['password']);
        }
        
        $user->save();

        // Actualizar rol
        $role = \App\Models\Role::where('name', $data['role'])->first();
        if ($role) {
            $user->roles()->sync([$role->id]);
        }

        // Actualizar partners adicionales
        // Primero eliminar todas las relaciones existentes
        $user->partnerInvites()->delete();
        
        // Luego crear las nuevas relaciones
        if (isset($data['additional_partners_ids']) && !empty($data['additional_partners_ids'])) {
            $additionalPartnerIds = explode(',', $data['additional_partners_ids']);
            foreach ($additionalPartnerIds as $partnerId) {
                $partnerId = trim($partnerId);
                if ($partnerId && $partnerId != $data['partner_id']) {
                    \App\Models\PartnerInvite::create([
                        'user_id' => $user->id,
                        'partner_id' => $partnerId,
                        'status' => 'accepted'
                    ]);
                }
            }
            \Log::info('Updated additional partners', [
                'user_id' => $user->id,
                'additional_partners_ids' => $data['additional_partners_ids'],
                'partners_count' => count($additionalPartnerIds)
            ]);
        } else {
            \Log::info('No additional partners provided, all removed', [
                'user_id' => $user->id,
                'additional_partners_ids' => $data['additional_partners_ids'] ?? 'empty'
            ]);
        }
        // Si no hay partners adicionales, solo se eliminan las relaciones existentes

        return redirect()->route('user-management.index')->with('success', 'User updated successfully!');
    }

    public function destroy($id)
    {
        $user = \App\Models\User::findOrFail($id);
        $user->delete();
        return redirect()->route('user-management.index')->with('success', 'User deleted successfully!');
    }
}
