<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\Activitylog\Models\Activity;
use Yajra\DataTables\Facades\DataTables;
use App\Models\User;

class ActivityLogsController extends Controller
{
    public function index()
    {
        $users = User::select('id','name')->get();
        return view('audit-logs.index',compact('users'));
    }

     public function data(Request $request)
    {

        $query = Activity::with('causer')->orderBy('created_at','desc');

        if($request->event){
            $query->where('description',$request->event);
        }

        if($request->user_id){
            $query->where('causer_id',$request->user_id);
        }

        if($request->date_from){
            $query->whereDate('created_at','>=',$request->date_from);
        }

        if($request->date_to){
            $query->whereDate('created_at','<=',$request->date_to);
        }

        return DataTables::of($query)

        ->addColumn('module', function ($log) {
            return class_basename($log->subject_type);
        })

        ->addColumn('user', function ($log) {
            return $log->causer->name ?? 'System';
        })

        ->editColumn('created_at', function ($log) {
            return '<span title="'.$log->created_at.'">
                    '.$log->created_at->diffForHumans().'
                </span>';
        })

        ->addColumn('action', function ($log) {

            return '<button class="btn btn-sm btn-inverse-info rounded-25 view-log"
                data-description="'.$log->description.'"
                data-user="'.($log->causer->name ?? 'System').'"
                data-time="'.$log->created_at.'"
                data-module="'.class_basename($log->subject_type).'"
                data-log=\''.json_encode($log->properties).'\'>
                <span class="fa fa-file-text-o"></span>
            </button>';

        })

        ->rawColumns(['created_at','action'])

        ->make(true);

    }

}
