<?php
class AuditLogController extends Controller
{
    public function index(Request $request): void
    {
        $db = $this->db();
        $modules = $db->fetchAll("SELECT DISTINCT module FROM audit_log ORDER BY module");
        $users = $db->fetchAll("SELECT DISTINCT u.id, u.full_name_en FROM audit_log al JOIN auth_users u ON al.user_id = u.id ORDER BY u.full_name_en");

        $this->view('audit-log/index', [
            'title' => lang('admin.audit_log'),
            'breadcrumbs' => [['label' => lang('admin.administration'), 'url' => '/admin/audit-log'], ['label' => lang('admin.audit_log')]],
            'modules' => $modules,
            'users' => $users,
        ]);
    }

    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 (al.description LIKE ? OR al.entity_type LIKE ? OR u.full_name_en LIKE ?)";
            $s = "%{$search}%";
            $params = array_merge($params, [$s, $s, $s]);
        }

        $userFilter = $request->post('user_filter');
        if ($userFilter) { $where .= " AND al.user_id = ?"; $params[] = (int)$userFilter; }
        $moduleFilter = $request->post('module_filter');
        if ($moduleFilter) { $where .= " AND al.module = ?"; $params[] = $moduleFilter; }
        $actionFilter = $request->post('action_filter');
        if ($actionFilter) { $where .= " AND al.action_type = ?"; $params[] = $actionFilter; }
        $dateFrom = $request->post('date_from');
        if ($dateFrom) { $where .= " AND al.created_at >= ?"; $params[] = $dateFrom . ' 00:00:00'; }
        $dateTo = $request->post('date_to');
        if ($dateTo) { $where .= " AND al.created_at <= ?"; $params[] = $dateTo . ' 23:59:59'; }

        $total = (int)$db->fetchColumn("SELECT COUNT(*) FROM audit_log al");
        $filtered = (int)$db->fetchColumn("SELECT COUNT(*) FROM audit_log al LEFT JOIN auth_users u ON al.user_id = u.id WHERE {$where}", $params);

        $rows = $db->fetchAll(
            "SELECT al.*, u.full_name_en as user_name FROM audit_log al
             LEFT JOIN auth_users u ON al.user_id = u.id WHERE {$where}
             ORDER BY al.created_at DESC LIMIT {$length} OFFSET {$start}", $params
        );

        $data = [];
        foreach ($rows as $r) {
            $actionBadge = match($r['action_type']) {
                'create' => '<span class="badge bg-success">Create</span>',
                'update' => '<span class="badge bg-primary">Update</span>',
                'delete' => '<span class="badge bg-danger">Delete</span>',
                'login' => '<span class="badge bg-info">Login</span>',
                'logout' => '<span class="badge bg-secondary">Logout</span>',
                default => '<span class="badge bg-dark">' . e($r['action_type']) . '</span>',
            };
            $data[] = [
                'id' => $r['id'],
                'datetime' => format_datetime($r['created_at']),
                'user' => e($r['user_name'] ?? 'System'),
                'action' => $actionBadge,
                'module' => e($r['module']),
                'entity' => e($r['entity_type']) . ($r['entity_id'] ? ' #' . $r['entity_id'] : ''),
                'description' => e(str_limit($r['description'], 80)),
                'ip' => e($r['ip_address'] ?? ''),
                'actions' => '<a href="/admin/audit-log/' . $r['id'] . '" class="btn btn-sm btn-outline-info"><i class="fas fa-eye"></i></a>',
            ];
        }
        $this->json(['draw' => $draw, 'recordsTotal' => $total, 'recordsFiltered' => $filtered, 'data' => $data]);
    }

    public function show(Request $request): void
    {
        $id = (int)$request->routeParam('id');
        $db = $this->db();
        $entry = $db->fetchOne("SELECT al.*, u.full_name_en as user_name FROM audit_log al LEFT JOIN auth_users u ON al.user_id = u.id WHERE al.id = ?", [$id]);
        if (!$entry) { $this->abort(404); return; }

        $this->view('audit-log/show', [
            'title' => 'Audit Entry #' . $id,
            'breadcrumbs' => [['label' => lang('admin.administration'), 'url' => '/admin/audit-log'], ['label' => lang('admin.audit_log'), 'url' => '/admin/audit-log'], ['label' => '#' . $id]],
            'entry' => $entry,
        ]);
    }
}