<?php

namespace App\Modules\Useraction\Model;

use App\Facades\General;
use App\Models\Tenant;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Request;
use Yajra\DataTables\Facades\DataTables;

class UserAction extends Tenant
{
    use SoftDeletes;

    protected $fillable = ['account_id',
        'user_id',
        'parent_id',
        'action_module',
        'ip',
        'user_client',
        'title',
        'message'];

    /**
     * @return BelongsTo
     */
    public function user()
    {
        return $this->belongsTo('App\User', 'user_id')->withDefault();
    }

    public static function getUserActions()
    {
        $model = self::query();
        $user  = Auth::user();

        $cols = [
            "user_actions.*",
            'user_actions.title as activity',
            'user_actions.ip as remote_ip',
            'users.name as action_by'
        ];
        $model->select($cols);

        if ($user && $user->access_level == 1) {
            $model->where('user_actions.user_id', $user->id);
        }

        $model->leftJoin(
            'users', 'users.id', '=', 'user_actions.user_id'
        );

        $model->orderBy('created_at', 'desc');

        return DataTables::eloquent($model)
            ->addColumn('date', function ($q) {
                return date("d F, Y g:i A", strtotime($q->created_at));
            })
            ->rawColumns(['message'])
            ->make(true);
    }

    /**
     * Set user Activity log
     *
     * @param $activityId
     * @param $options
     * @return mixed
     */
    public static function setUserActivity($activityId, $options)
    {
        // get messages
        $title        = ucfirst(trans("ulmsg.$activityId.TITLE"));
        $eventData    = isset($options['event_data']) ? $options['event_data'] : [];
        $parentId     = isset($options['parent_id']) ? $options['parent_id'] : null;
        $actionModule = isset($options['action_module']) ? $options['action_module'] : null;
        $message      = ucfirst(trans("ulmsg.$activityId.MSG", $eventData));

        $data = [
            'account_id'    => General::getAccountId(),
            'user_id'       => General::getUserId(),
            'parent_id'     => $parentId,
            'action_module' => $actionModule,
            'ip'            => Request::ip(),
            'user_client'   => Request::header('User-Agent'),
            'title'         => $title,
            'message'       => $message,
        ];
        $userAction             = new UserAction();
        $userAction->fill($data);
        $userAction->save();

        return $userAction;
    }


}
