<?php
class ExportLogController extends Controller
{
    public function index(Request $request): void
    {
        $this->view('export-log/index', [
            'title' => lang('admin.export_log'),
            'breadcrumbs' => [['label' => lang('admin.administration'), 'url' => '/admin/export-log'], ['label' => lang('admin.export_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);
        $total = (int)$db->fetchColumn("SELECT COUNT(*) FROM export_log");
        $rows = $db->fetchAll(
            "SELECT el.*, u.full_name_en as user_name FROM export_log el LEFT JOIN auth_users u ON el.exported_by = u.id ORDER BY el.exported_at DESC LIMIT {$length} OFFSET {$start}"
        );
        $data = [];
        foreach ($rows as $r) {
            $data[] = [
                'type' => e($r['export_type']),
                'source' => e($r['export_source']),
                'format' => '<span class="badge bg-info">' . e(strtoupper($r['export_format'])) . '</span>',
                'rows' => number_format($r['rows_exported'] ?? 0),
                'user' => e($r['user_name'] ?? '-'),
                'date' => format_datetime($r['exported_at']),
                'ip' => e($r['ip_address'] ?? ''),
            ];
        }
        $this->json(['draw' => $draw, 'recordsTotal' => $total, 'recordsFiltered' => $total, 'data' => $data]);
    }
}