<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Company;
use App\Models\Project;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;

class InvitationController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth')->except(['show', 'accept']);
    }

    /**
     * Generate invitation link for a client to register in a project
     */
    public function generate(Request $request)
    {
        $request->validate([
            'email' => 'required|email|unique:users,email',
            'project_id' => 'required|exists:projects,id',
            'company_id' => 'required|exists:companies,id',
        ]);

        $token = Str::random(64);

        $user = User::create([
            'name' => '', // El cliente lo completará
            'email' => $request->email,
            'password' => Hash::make(Str::random(16)), // Password temporal
            'role' => User::ROLE_SOLICITANTE,
            'company_id' => $request->company_id,
            'project_id' => $request->project_id,
            'invitation_token' => $token,
            'is_active' => false, // Se activa cuando acepta la invitación
        ]);

        $invitationLink = route('invitation.show', ['token' => $token]);

        return response()->json([
            'success' => true,
            'message' => 'Invitación generada exitosamente',
            'invitation_link' => $invitationLink,
            'user_id' => $user->id,
        ]);
    }

    /**
     * Show invitation acceptance page
     */
    public function show($token)
    {
        $user = User::where('invitation_token', $token)
                    ->whereNull('invitation_accepted_at')
                    ->firstOrFail();

        $company = $user->company;
        $project = $user->project;

        return view('auth.accept-invitation', compact('user', 'company', 'project', 'token'));
    }

    /**
     * Accept invitation and complete registration
     */
    public function accept(Request $request, $token)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'password' => 'required|string|min:8|confirmed',
            'phone' => 'nullable|string|max:20',
            'position' => 'nullable|string|max:100',
        ]);

        $user = User::where('invitation_token', $token)
                    ->whereNull('invitation_accepted_at')
                    ->firstOrFail();

        $user->update([
            'name' => $request->name,
            'password' => Hash::make($request->password),
            'phone' => $request->phone,
            'position' => $request->position,
            'is_active' => true,
            'invitation_accepted_at' => now(),
        ]);

        // Auto-login después de aceptar invitación
        auth()->login($user);

        return redirect()->route('dashboard')->with('success', 'Bienvenido a Ticketera! Tu cuenta ha sido activada.');
    }

    /**
     * List all pending invitations (for admins)
     */
    public function index()
    {
        if (!auth()->user()->isAdmin()) {
            abort(403);
        }

        $pendingInvitations = User::whereNotNull('invitation_token')
                                  ->whereNull('invitation_accepted_at')
                                  ->with(['company', 'project'])
                                  ->get();

        return view('invitations.index', compact('pendingInvitations'));
    }

    /**
     * Resend invitation email
     */
    public function resend($userId)
    {
        $user = User::findOrFail($userId);

        if ($user->invitation_accepted_at) {
            return back()->with('error', 'Esta invitación ya fue aceptada');
        }

        $invitationLink = route('invitation.show', ['token' => $user->invitation_token]);

        // Aquí podrías enviar un email con el link
        // Mail::to($user->email)->send(new InvitationMail($invitationLink));

        return back()->with('success', 'Link de invitación regenerado: ' . $invitationLink);
    }

    /**
     * Cancel invitation
     */
    public function cancel($userId)
    {
        $user = User::findOrFail($userId);

        if ($user->invitation_accepted_at) {
            return back()->with('error', 'Esta invitación ya fue aceptada');
        }

        $user->delete();

        return back()->with('success', 'Invitación cancelada');
    }
}
