<?php
class LoginLogController extends Controller
{
    public function index(Request $request): void
    {
        $this->view('login-log/index', [
            'title' => lang('admin.login_log'),
            'breadcrumbs' => [['label' => lang('admin.administration'), 'url' => '/admin/login-log'], ['label' => lang('admin.login_log')]],
        ]);
    }

    public function datatable(Request $request): void
    {
        $db = $this->db();
        $draw = (int)$request->post('draw', 1);
        $start = (int)$request->post('start', 0);
        $length = (int)$request->post('length', 25);
        $search = trim($request->post('search')['value'] ?? '');

        $where = "1=1";
        $params = [];
        if ($search !== '') {
            $where .= " AND (ll.username LIKE ? OR ll.ip_address LIKE ?)";
            $s = "%{$search}%";
            $params = [$s, $s];
        }
        $actionFilter = $request->post('action_filter');
        if ($actionFilter) { $where .= " AND ll.action = ?"; $params[] = $actionFilter; }

        $total = (int)$db->fetchColumn("SELECT COUNT(*) FROM login_log ll");
        $filtered = (int)$db->fetchColumn("SELECT COUNT(*) FROM login_log ll WHERE {$where}", $params);
        $rows = $db->fetchAll("SELECT ll.* FROM login_log ll WHERE {$where} ORDER BY ll.created_at DESC LIMIT {$length} OFFSET {$start}", $params);

        $data = [];
        foreach ($rows as $r) {
            $actionBadge = match($r['action']) {
                'login_success' => '<span class="badge bg-success">Login</span>',
                'login_failed' => '<span class="badge bg-danger">Failed</span>',
                'logout' => '<span class="badge bg-info">Logout</span>',
                default => '<span class="badge bg-secondary">' . e($r['action']) . '</span>',
            };
            $data[] = [
                'datetime' => format_datetime($r['created_at']),
                'username' => e($r['username']),
                'action' => $actionBadge,
                'ip' => e($r['ip_address']),
                'reason' => e($r['failure_reason'] ?? '-'),
            ];
        }
        $this->json(['draw' => $draw, 'recordsTotal' => $total, 'recordsFiltered' => $filtered, 'data' => $data]);
    }
}