<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Contrato;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class ClienteController extends Controller
{
    public function index()
    {
        $contratos = Contrato::with('portalUser')
            ->orderBy('razao_social')
            ->get();

        return view('pages.admin.clientes', compact('contratos'));
    }

    public function storeAcesso(Request $request, Contrato $contrato): JsonResponse
    {
        $data = $request->validate([
            'name'     => 'required|string|max:100',
            'email'    => 'required|email|unique:users,email',
            'password' => 'required|string|min:6',
        ]);

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

        $contrato->update(['portal_user_id' => $user->id]);

        return response()->json(['ok' => true]);
    }

    public function updateAcesso(Request $request, Contrato $contrato): JsonResponse
    {
        abort_unless($contrato->portalUser, 404);

        $data = $request->validate([
            'name'     => 'required|string|max:100',
            'email'    => "required|email|unique:users,email,{$contrato->portal_user_id}",
            'password' => 'nullable|string|min:6',
        ]);

        $update = ['name' => $data['name'], 'email' => $data['email']];
        if (!empty($data['password'])) {
            $update['password'] = Hash::make($data['password']);
        }
        $contrato->portalUser->update($update);

        return response()->json(['ok' => true]);
    }

    public function revogarAcesso(Contrato $contrato): JsonResponse
    {
        if ($contrato->portalUser) {
            $contrato->portalUser->delete();
        }
        $contrato->update(['portal_user_id' => null]);

        return response()->json(['ok' => true]);
    }

    public function toggleAcesso(Contrato $contrato): JsonResponse
    {
        $user = $contrato->portalUser;
        abort_unless($user, 404);

        // Toggle: se não tem email_verified_at = desativado
        if ($user->email_verified_at) {
            $user->update(['email_verified_at' => null]);
            $status = 'desativado';
        } else {
            $user->update(['email_verified_at' => now()]);
            $status = 'ativado';
        }

        return response()->json(['ok' => true, 'status' => $status]);
    }
}
