<?php

namespace App\Http\Controllers\School;

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

class AuditLogController extends Controller
{
    public function index(Request $request): Response
    {
        $user = $request->user();
        $schoolId = $user->school_id;

        $auditLogs = DB::table('audit_logs')
            ->leftJoin('users', 'users.id', '=', 'audit_logs.user_id')
            ->where('audit_logs.school_id', $schoolId)
            ->orderByDesc('audit_logs.created_at')
            ->limit(200)
            ->get([
                'audit_logs.id',
                'audit_logs.action',
                'audit_logs.entity_type',
                'audit_logs.entity_id',
                'audit_logs.old_value',
                'audit_logs.new_value',
                'audit_logs.ip_address',
                'audit_logs.created_at',
                'users.first_name',
                'users.last_name',
                'users.username',
                'users.role_key',
            ])
            ->map(fn ($row): array => [
                'id' => $row->id,
                'action' => $row->action,
                'entityType' => $row->entity_type,
                'entityId' => $row->entity_id,
                'oldValue' => $row->old_value,
                'newValue' => $row->new_value,
                'ip' => $row->ip_address,
                'createdAt' => jalaliDate($row->created_at),
                'userName' => $row->username
                    ? trim(($row->first_name ?? '').' '.($row->last_name ?? '')) ?: $row->username
                    : 'سیستم',
                'userRole' => $row->role_key ?? '—',
            ])->values();

        $loginLogs = DB::table('login_logs')
            ->where('school_id', $schoolId)
            ->orderByDesc('created_at')
            ->limit(100)
            ->get(['username', 'status', 'ip_address', 'created_at'])
            ->map(fn ($row): array => [
                'username' => $row->username,
                'status' => $row->status,
                'ip' => $row->ip_address,
                'createdAt' => jalaliDate($row->created_at),
            ])->values();

        return Inertia::render('School/AuditLogs', [
            'auditLogs' => $auditLogs,
            'loginLogs' => $loginLogs,
        ]);
    }
}
