<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Permission;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index(Request $request)
    {
        $query = User::query()
            ->with(['permissions', 'consultantProfile'])
            ->latest();

        if ($request->filled('search')) {
            $search = $request->query('search');
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%");
            });
        }

        $users = $query->paginate(20)->through(fn (User $user) => [
            'id' => $user->id,
            'name' => $user->name,
            'email' => $user->email,
            'permissions' => $user->permissions->pluck('key')->values(),
            'consultant_profile' => $user->consultantProfile ? [
                'id' => $user->consultantProfile->id,
                'company_name' => $user->consultantProfile->company_name,
                'is_verified' => $user->consultantProfile->is_verified,
                'is_active' => $user->consultantProfile->is_active,
            ] : null,
            'created_at' => $user->created_at?->toISOString(),
        ]);

        return response()->json($users);
    }

    /** Sistemdeki tüm izinler (atama matrisi için). */
    public function permissions()
    {
        $permissions = Permission::orderBy('key')->get()->map(fn ($p) => [
            'id' => $p->id,
            'key' => $p->key,
            'name' => $p->name,
            'description' => $p->description,
        ]);

        return response()->json(['data' => $permissions]);
    }

    /**
     * Bir kullanıcının izinlerini toptan günceller.
     * Body: { permission_keys: ["listing.create", ...] }
     */
    public function updatePermissions(Request $request, User $user)
    {
        $data = $request->validate([
            'permission_keys' => ['present', 'array'],
            'permission_keys.*' => ['string', 'exists:permissions,key'],
        ]);

        $ids = Permission::whereIn('key', $data['permission_keys'])->pluck('id')->all();
        $user->permissions()->sync($ids);

        return response()->json([
            'data' => [
                'id' => $user->id,
                'permissions' => $user->permissions()->pluck('key')->values(),
            ],
        ]);
    }
}
