<?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 Illuminate\Support\Str;
use Inertia\Inertia;
use Inertia\Response;

class UserController extends Controller
{
    public function index(Request $request): Response
    {
        $schoolId = $this->currentSchoolId($request);

        $users = $schoolId
            ? DB::table('users')
                ->where('school_id', $schoolId)
                ->whereNotIn('role_key', ['super_admin', 'support', 'finance'])
                ->orderBy('role_key')
                ->orderBy('last_name')
                ->get([
                    'id', 'username', 'first_name', 'last_name',
                    'mobile', 'email', 'role_key', 'status',
                    'last_login_at', 'must_change_password',
                ])
            : collect();

        $roleLabels = $this->roleLabels();

        return Inertia::render('School/Users', [
            'users' => $users->map(fn ($user): array => [
                'id' => (int) $user->id,
                'username' => $user->username,
                'firstName' => $user->first_name,
                'lastName' => $user->last_name,
                'fullName' => trim($user->first_name.' '.$user->last_name),
                'mobile' => $user->mobile ?? '',
                'email' => $user->email ?? '',
                'role' => $user->role_key,
                'roleLabel' => $roleLabels[$user->role_key] ?? $user->role_key,
                'status' => $user->status,
                'lastLogin' => $user->last_login_at ? $this->jalaliDate($user->last_login_at, true) : 'هرگز',
                'mustChangePassword' => (bool) $user->must_change_password,
            ])->values(),
            'roles' => array_map(
                fn ($key, $label) => ['value' => $key, 'label' => $label],
                array_keys($roleLabels),
                $roleLabels,
            ),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);
        abort_unless($schoolId, 422, 'مدرسه مشخص نیست.');

        $data = $request->validate([
            'username' => ['required', 'string', 'max:120', 'unique:users,username'],
            'first_name' => ['required', 'string', 'max:120'],
            'last_name' => ['required', 'string', 'max:120'],
            'mobile' => ['nullable', 'string', 'max:30'],
            'email' => ['nullable', 'email', 'max:190'],
            'role_key' => ['required', 'string', 'in:owner,principal,moaven,teacher,student'],
            'password' => ['required', 'string', 'min:6'],
        ]);

        DB::table('users')->insert([
            'school_id' => $schoolId,
            'username' => $data['username'],
            'password' => \Illuminate\Support\Facades\Hash::make($data['password']),
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
            'mobile' => $data['mobile'] ?? null,
            'email' => $data['email'] ?? null,
            'role_key' => $data['role_key'],
            'status' => 'active',
            'must_complete_profile' => false,
            'must_change_password' => true,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return redirect()->route('school.users')->with('success', 'کاربر ساخته شد. رمز اولیه باید در اولین ورود تغییر کند.');
    }

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

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

        abort_unless($user, 404);

        $data = $request->validate([
            'status' => ['required', 'string', 'in:active,inactive,blocked'],
        ]);

        DB::table('users')->where('id', $id)->update([
            'status' => $data['status'],
            'updated_at' => now(),
        ]);

        return redirect()->route('school.users')->with('success', 'وضعیت کاربر تغییر کرد.');
    }

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

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

        abort_unless($user, 404);

        $tempPassword = Str::random(10);

        DB::table('users')->where('id', $id)->update([
            'password' => \Illuminate\Support\Facades\Hash::make($tempPassword),
            'must_change_password' => true,
            'updated_at' => now(),
        ]);

        try {
            DB::table('audit_logs')->insert([
                'school_id' => $schoolId,
                'user_id' => $request->user()?->id,
                'action' => 'password_reset_by_admin',
                'entity_type' => 'user',
                'entity_id' => $id,
                'ip_address' => $request->ip(),
                'created_at' => now(),
            ]);
        } catch (\Throwable) {
        }

        return redirect()->route('school.users')->with('temp_password', "رمز موقت «{$user->username}»: {$tempPassword} — این رمز فقط یک بار نمایش داده می‌شود.");
    }

    private function roleLabels(): array
    {
        return [
            'owner' => 'مدیر اصلی',
            'principal' => 'مدیر اجرایی',
            'moaven' => 'معاون',
            'teacher' => 'معلم',
            'student' => 'دانش‌آموز',
        ];
    }
}
