<?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\Request;
use Yajra\DataTables\Facades\DataTables;

class SaasAction extends Tenant
{
    use SoftDeletes;

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

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

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

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

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

        $model->leftJoin(
            'users', 'users.id', '=', 'saas_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 setSaasUserActivity($activityId, $options)
    {
        $saasUserId = is_null(Auth::user()->id) ? '' : Auth::user()->id;

        // 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 = [
            'user_id'       => General::getUserId(),
            'parent_id'     => $parentId,
            'action_module' => $actionModule,
            'ip'            => Request::ip(),
            'user_client'   => Request::header('User-Agent'),
            'title'         => $title,
            'message'       => $message,
        ];

        $saasAction             = new SaasAction();
        $saasAction->fill($data);
        $saasAction->save();

        return $saasAction;
    }

}
