<?php

namespace App\Http\Controllers\Admin;

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

class ModeratorController extends Controller
{
    public function index()
    {
        $moderators = User::where('role', 'moderator')
            ->withCount('moderatorPermissions')
            ->with('moderatorPermissions:user_id,permission')
            ->orderByDesc('created_at')
            ->paginate(20);

        return view('admin.moderators.index', [
            'moderators' => $moderators,
            'groups'     => ModeratorPermission::$groups,
        ]);
    }

    public function edit(User $user)
    {
        abort_if($user->isAdmin(), 403);

        $permissions = ModeratorPermission::where('user_id', $user->id)
            ->pluck('permission')
            ->flip()  // key = permission, value = true for fast lookup
            ->all();

        return view('admin.moderators.edit', [
            'moderator'   => $user,
            'groups'      => ModeratorPermission::$groups,
            'permissions' => $permissions,
        ]);
    }

    /** Admin assigns a user the moderator role */
    public function promote(Request $request)
    {
        $request->validate(['user_id' => 'required|exists:users,id']);

        $user = User::findOrFail($request->user_id);
        abort_if($user->isAdmin(), 403, 'Admin kullanıcı düzenlenemez.');

        $user->update(['role' => 'moderator']);

        return back()->with('success', "{$user->name} moderatör yapıldı.");
    }

    /** Remove moderator role */
    public function demote(User $user)
    {
        abort_if($user->isAdmin(), 403);
        $user->update(['role' => 'user']);
        ModeratorPermission::where('user_id', $user->id)->delete();
        $user->flushPermCache();

        return back()->with('success', "{$user->name} moderatörlükten çıkarıldı.");
    }

    /** Save permission checkboxes */
    public function savePermissions(Request $request, User $user)
    {
        abort_if($user->isAdmin(), 403);
        abort_if($user->role !== 'moderator', 422, 'Kullanıcı moderatör değil.');

        $allKeys    = ModeratorPermission::allKeys();
        $submitted  = array_intersect($request->input('permissions', []), $allKeys);

        // Delete old, insert new
        ModeratorPermission::where('user_id', $user->id)->delete();
        foreach ($submitted as $perm) {
            ModeratorPermission::create([
                'user_id'    => $user->id,
                'permission' => $perm,
                'granted_by' => auth()->id(),
            ]);
        }

        $user->flushPermCache();

        return back()->with('success', 'İzinler kaydedildi. (' . count($submitted) . ' izin aktif)');
    }

    /** Quick permission toggle via AJAX */
    public function togglePermission(Request $request, User $user)
    {
        abort_if($user->isAdmin(), 403);
        $perm = $request->input('permission');
        abort_unless(in_array($perm, ModeratorPermission::allKeys()), 422);

        $existing = ModeratorPermission::where('user_id', $user->id)
                                       ->where('permission', $perm)->first();
        if ($existing) {
            $existing->delete();
            $active = false;
        } else {
            ModeratorPermission::create(['user_id' => $user->id, 'permission' => $perm, 'granted_by' => auth()->id()]);
            $active = true;
        }

        $user->flushPermCache();

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