<?php

namespace App\Http\Controllers\School;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;

class MoavenPermissionsController extends Controller
{
    private const PERMISSION_GROUPS = [
        'دانش‌آموزان' => ['students.view', 'students.create', 'students.import'],
        'کلاس‌ها' => ['classes.manage'],
        'حضور و غیاب' => ['attendance.create', 'attendance.approve_absence_sms'],
        'نمره‌دهی' => ['grades.create', 'grades.approve'],
        'تکالیف' => ['homework.create'],
        'امتحانات' => ['exams.online.create'],
        'SMS' => ['sms.view_wallet', 'sms.charge_wallet', 'sms.send_to_absents', 'sms.send_bulk'],
        'رأی‌گیری' => ['voting.create', 'voting.publish', 'voting.view_results', 'voting.export_results'],
        'گزارش‌ها' => ['reports.export'],
    ];

    public function show(Request $request, int $user): Response
    {
        $schoolId = $this->currentSchoolId($request);

        $targetUser = DB::table('users')
            ->where('id', $user)
            ->where('school_id', $schoolId)
            ->where('role_key', 'moaven')
            ->first(['id', 'first_name', 'last_name', 'username', 'role_key']);

        abort_unless($targetUser, 404);

        $allPermissions = DB::table('permissions')
            ->get(['id', 'key_name', 'name_fa'])
            ->keyBy('key_name');

        $grantedKeys = DB::table('user_permissions')
            ->join('permissions', 'permissions.id', '=', 'user_permissions.permission_id')
            ->where('user_permissions.user_id', $user)
            ->where('user_permissions.effect', 'allow')
            ->pluck('permissions.key_name')
            ->flip()
            ->all();

        $groups = [];
        foreach (self::PERMISSION_GROUPS as $groupLabel => $keys) {
            $items = [];
            foreach ($keys as $key) {
                $perm = $allPermissions->get($key);
                if ($perm) {
                    $items[] = [
                        'id' => (int) $perm->id,
                        'key' => $perm->key_name,
                        'label' => $perm->name_fa,
                        'granted' => isset($grantedKeys[$key]),
                    ];
                }
            }
            if ($items) {
                $groups[] = ['group' => $groupLabel, 'items' => $items];
            }
        }

        return Inertia::render('School/MoavenPermissions', [
            'targetUser' => [
                'id' => (int) $targetUser->id,
                'name' => trim($targetUser->first_name . ' ' . $targetUser->last_name),
                'username' => $targetUser->username,
            ],
            'groups' => $groups,
        ]);
    }

    public function update(Request $request, int $user): RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);

        $targetUser = DB::table('users')
            ->where('id', $user)
            ->where('school_id', $schoolId)
            ->where('role_key', 'moaven')
            ->first(['id']);

        abort_unless($targetUser, 404);

        $grantedIds = array_filter(
            array_map('intval', (array) $request->input('permission_ids', [])),
            fn ($id) => $id > 0
        );

        DB::transaction(function () use ($user, $grantedIds): void {
            DB::table('user_permissions')->where('user_id', $user)->delete();

            foreach ($grantedIds as $permId) {
                $exists = DB::table('permissions')->where('id', $permId)->exists();
                if ($exists) {
                    DB::table('user_permissions')->insertOrIgnore([
                        'user_id' => $user,
                        'permission_id' => $permId,
                        'effect' => 'allow',
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                }
            }
        });

        return back()->with('success', 'دسترسی‌های معاون ذخیره شد.');
    }
}
