<?php

namespace App\Http\Controllers;

use App\Http\Requests\Auth\LoginRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;

class AuthController extends Controller
{
    public function showLogin(): Response
    {
        return Inertia::render('Auth/Login');
    }

    public function login(LoginRequest $request): RedirectResponse
    {
        $username = $request->input('username');
        $credentials = $request->only('username', 'password');

        if (! Auth::attempt($credentials, $request->boolean('remember'))) {
            $this->writeLoginLog(null, null, $username, 'failed', $request->ip());

            return back()->withErrors([
                'username' => 'نام کاربری یا رمز عبور درست نیست.',
            ])->onlyInput('username');
        }

        $request->session()->regenerate();

        $user = $request->user();
        $schoolId = $user?->school_id;

        $this->writeLoginLog($user?->id, $schoolId, $username, 'success', $request->ip());
        $this->writeAuditLog($user?->id, $schoolId, 'login_success', 'auth', null, null, null, $request->ip());

        if ($user && ($user->must_complete_profile || $user->must_change_password)) {
            return redirect()->route('profile.complete.edit');
        }

        return redirect()->intended(route('dashboard'));
    }

    public function logout(Request $request): RedirectResponse
    {
        $userId = Auth::id();
        $schoolId = Auth::user()?->school_id;

        Auth::guard('web')->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        $this->writeAuditLog($userId, $schoolId, 'logout', 'auth', null, null, null, $request->ip());

        return redirect()->route('login');
    }

    public function forgotPassword(): Response
    {
        return Inertia::render('Auth/ForgotPassword');
    }

    private function writeLoginLog(?int $userId, ?int $schoolId, string $username, string $status, ?string $ip): void
    {
        try {
            DB::table('login_logs')->insert([
                'school_id' => $schoolId,
                'user_id' => $userId,
                'username' => $username,
                'status' => $status,
                'ip_address' => $ip,
                'created_at' => now(),
            ]);
        } catch (\Throwable) {
        }
    }

    private function writeAuditLog(?int $userId, ?int $schoolId, string $action, ?string $entityType, ?int $entityId, mixed $oldValue, mixed $newValue, ?string $ip): void
    {
        try {
            DB::table('audit_logs')->insert([
                'user_id' => $userId,
                'school_id' => $schoolId,
                'user_role' => $userId ? DB::table('users')->where('id', $userId)->value('role_key') : null,
                'action' => $action,
                'entity_type' => $entityType,
                'entity_id' => $entityId,
                'old_value' => $oldValue !== null ? json_encode($oldValue, JSON_UNESCAPED_UNICODE) : null,
                'new_value' => $newValue !== null ? json_encode($newValue, JSON_UNESCAPED_UNICODE) : null,
                'ip_address' => $ip,
                'created_at' => now(),
            ]);
        } catch (\Throwable) {
        }
    }
}
