<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Client;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\View\View;

class ClientPortalUserController extends Controller
{
    public function index(Client $client): View
    {
        $page_title = 'Portal Kullanıcıları';
        $page_description = $client->company_name.' müşteri portalı erişimleri';
        $client->load('users');

        return view('admin.client-users.index', compact('page_title', 'page_description', 'client'));
    }

    public function create(Client $client): View
    {
        $page_title = 'Portal Kullanıcısı Ekle';
        $page_description = $client->company_name.' için müşteri portalı kullanıcısı oluştur';

        return view('admin.client-users.create', compact('page_title', 'page_description', 'client'));
    }

    public function store(Request $request, Client $client): RedirectResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255'],
            'password' => ['nullable', 'string', 'min:8', 'confirmed'],
            'role' => ['required', 'in:viewer,report_viewer,manager'],
            'is_active' => ['nullable', 'boolean'],
        ]);

        $plainPassword = $data['password'] ?? Str::random(12).'A1!';
        $user = User::firstOrCreate(
            ['email' => $data['email']],
            ['name' => $data['name'], 'password' => Hash::make($plainPassword)]
        );

        if (! $user->wasRecentlyCreated && $request->filled('password')) {
            $user->update([
                'name' => $data['name'],
                'password' => Hash::make($plainPassword),
            ]);
        }

        $client->users()->syncWithoutDetaching([
            $user->id => [
                'role' => $data['role'],
                'is_active' => $request->boolean('is_active', true),
                'permissions' => json_encode(['reports' => true, 'alerts' => true, 'dashboard' => true]),
            ],
        ]);

        $message = $user->wasRecentlyCreated && ! $request->filled('password')
            ? 'Portal kullanıcısı oluşturuldu. Geçici şifre: '.$plainPassword
            : 'Portal kullanıcısı kaydedildi.';

        return redirect()->route('admin.clients.portal-users.index', $client)->with('success', $message);
    }

    public function update(Request $request, Client $client, User $user): RedirectResponse
    {
        abort_unless($client->users()->where('users.id', $user->id)->exists(), 404);

        $data = $request->validate([
            'role' => ['required', 'in:viewer,report_viewer,manager'],
            'is_active' => ['nullable', 'boolean'],
        ]);

        $client->users()->updateExistingPivot($user->id, [
            'role' => $data['role'],
            'is_active' => $request->boolean('is_active'),
        ]);

        return back()->with('success', 'Portal kullanıcı yetkisi güncellendi.');
    }

    public function destroy(Client $client, User $user): RedirectResponse
    {
        $client->users()->detach($user->id);

        return back()->with('success', 'Portal erişimi kaldırıldı.');
    }
}
