<?php

namespace App\DataTables;

use App\Models\OnlineStatus;
use Yajra\DataTables\Facades\DataTables;

class OnlineStatusDataTable
{
    public function render($request)
    {
        $query = OnlineStatus::with(['customer']);

        return DataTables::of($query)
            ->addColumn('customer_name', function (OnlineStatus $status) {
                return $status->customer?->name ?? 'Unknown';
            })
            ->addColumn('customer_code', function (OnlineStatus $status) {
                if (! $status->customer) {
                    return '-';
                }
                $code = e($status->customer->customer_code);
                return auth()->user()->can('view', $status->customer)
                    ? '<a class="btn btn-sm btn-outline-success fw-semibold text-nowrap" title="Open Customer Ledger" href="'.route('admin.customers.ledger', $status->customer).'">'.$code.'</a>'
                    : $code;
            })
            ->filterColumn('customer_code', function ($query, $keyword) {
                $query->whereHas('customer', fn ($customer) => $customer
                    ->where('customer_code', 'like', '%'.$keyword.'%'));
            })
            ->filterColumn('customer_name', function ($query, $keyword) {
                $query->whereHas('customer', fn ($customer) => $customer
                    ->where('name', 'like', '%'.$keyword.'%'));
            })
            ->addColumn('status_label', function (OnlineStatus $status) {
                return $status->online
                    ? '<span class="badge bg-success">Online</span>'
                    : '<span class="badge bg-secondary">Offline</span>';
            })
            ->addColumn('actions', function (OnlineStatus $status) {
                return view('admin.online-statuses.partials.actions', compact('status'))->render();
            })
            ->rawColumns(['customer_code', 'status_label', 'actions'])
            ->make(true);
    }
}
