<?php

namespace Modules\SmartStorage\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\SmartStorage\Entities\SsAccessLog;
use Yajra\DataTables\Facades\DataTables;

class AccessLogController extends Controller
{
    protected function authorizeView(): void
    {
        if (!auth()->user()->can('smart_storage.view_logs')) {
            abort(403, 'Unauthorized action.');
        }
    }

    public function index()
    {
        $this->authorizeView();

        return view('smartstorage::logs.index');
    }

    public function data(Request $request)
    {
        $this->authorizeView();

        $query = SsAccessLog::query()->with('user:id,first_name,surname,username')->latest('id');

        if ($request->filled('action')) {
            $query->where('action', $request->input('action'));
        }
        if ($request->filled('granted') && $request->input('granted') !== 'all') {
            $query->where('granted', (bool) $request->input('granted'));
        }
        if ($request->filled('ip')) {
            $query->where('ip', 'like', '%' . $request->input('ip') . '%');
        }
        if ($request->filled('user_id')) {
            $query->where('user_id', $request->input('user_id'));
        }
        if ($request->filled('date_start')) {
            $query->where('created_at', '>=', $request->input('date_start') . ' 00:00:00');
        }
        if ($request->filled('date_end')) {
            $query->where('created_at', '<=', $request->input('date_end') . ' 23:59:59');
        }

        return DataTables::of($query)
            ->editColumn('user_id', function ($row) {
                if (!$row->user) {
                    return '<em>guest</em>';
                }
                $name = trim(($row->user->first_name ?? '') . ' ' . ($row->user->surname ?? ''));
                return e($name !== '' ? $name : $row->user->username);
            })
            ->editColumn('action', function ($row) {
                $map = ['read' => 'info', 'write' => 'success', 'delete' => 'warning', 'denied' => 'danger'];
                $class = $map[$row->action] ?? 'default';
                return '<span class="label label-' . $class . '">' . e($row->action) . '</span>';
            })
            ->editColumn('granted', fn ($row) => $row->granted
                ? '<span class="text-success">yes</span>'
                : '<span class="text-danger">no</span>')
            ->editColumn('device_fingerprint', fn ($row) => $row->device_fingerprint ? e(substr($row->device_fingerprint, 0, 10)) . '…' : '')
            ->editColumn('created_at', fn ($row) => optional($row->created_at)->format('Y-m-d H:i:s'))
            ->addColumn('geo', fn ($row) => e(trim(($row->geo_city ? $row->geo_city . ', ' : '') . ($row->geo_country ?? ''), ', ')))
            ->rawColumns(['user_id', 'action', 'granted'])
            ->make(true);
    }
}
