<?php

namespace App\DataTables;

use App\Services\MikrotikRouterCacheService;
use Yajra\DataTables\Facades\DataTables;

class MikrotikOnlineDataTable
{
    public function __construct(protected MikrotikRouterCacheService $cacheService) {}

    public function render($request)
    {
        $rows = collect($this->cacheService->getOnlineCustomerRecords())
            ->map(function ($session) {
                return [
                    'name' => $session['name'] ?? null,
                    'customer_name' => $session['customer_name'] ?? null,
                    'customer_code' => $session['customer_code'] ?? null,
                    'contact_phone' => $session['contact_phone'] ?? null,
                    'customer_url' => ! empty($session['customer_id']) ? route('admin.customers.ledger', $session['customer_id']) : null,
                    'address' => $session['address'] ?? null,
                    'profile' => $session['profile'] ?? null,
                    'service' => $session['service'] ?? null,
                    'uptime' => $session['uptime'] ?? null,
                    'caller_id' => $session['caller_id'] ?? null,
                    'router_name' => $session['router_name'] ?? null,
                    'router_ip' => $session['router_ip'] ?? null,
                ];
            })
            ->all();

        return DataTables::of($rows)
            ->editColumn('customer_code', fn ($row) => $row['customer_url']
                ? '<a class="btn btn-sm btn-outline-success fw-semibold text-nowrap" title="Open Customer Ledger" href="'.e($row['customer_url']).'">'.e($row['customer_code']).'</a>'
                : '<span class="text-muted">—</span>')
            ->editColumn('customer_name', fn ($row) => $row['customer_name'] ?: 'Unmatched')
            ->rawColumns(['customer_code'])
            ->with('sync_status', $this->cacheService->getSyncStatus())->make(true);
    }
}
