<?php

namespace App\DataTables;

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

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

    public function render($request)
    {
        $rows = collect($this->cacheService->getPppOfflineCustomerRecords())
            ->map(function ($secret) {
                return [
                    'name' => $secret['name'] ?? null,
                    'customer_name' => $secret['customer_name'] ?? null,
                    'customer_code' => $secret['customer_code'] ?? null,
                    'contact_phone' => $secret['contact_phone'] ?? null,
                    'customer_url' => ! empty($secret['customer_id']) ? route('admin.customers.ledger', $secret['customer_id']) : null,
                    'profile' => $secret['profile'] ?? null,
                    'remote_address' => $secret['remote_address'] ?? null,
                    'router_name' => $secret['router_name'] ?? null,
                    'router_ip' => $secret['router_ip'] ?? null,
                    'status' => isset($secret['disabled']) && $secret['disabled'] ? 'Disabled' : 'Active',
                ];
            })
            ->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);
    }
}
