<?php

namespace Hilco\Models;

use Carbon\Carbon;

class WebAuthEvent extends WebModel {
    protected $table = 'WebAuthEvents';
    protected $fillable = ['event_type', 'ip_address', 'email', 'webuser_id', 'extra_data'];
    protected $casts = [
        'extra_data' => 'array'
    ];

    public function setIpAddressAttribute($value) {
        $this->attributes['ip_address'] = ip2long($value);
    }

    public function getIpAddressAttribute() {
        return long2ip($this->attributes['ip_address']);
    }

    public function scopeToday($query) {
        return $query->whereBetween('date_created', [Carbon::today()->startOfDay()->toDateTimeString(), Carbon::today()->endOfDay()->toDateTimeString()]);
    }

    /**
     * @param string $type
     * @param string $ipAddress
     * @param string $email
     * @param int $webUserId
     * @param array $extraData
     * @return static
     */
    public static function log($type, $ipAddress, $email = null, $webUserId = null, $extraData = []) {
        $data = [
            'event_type' => $type,
            'ip_address' => $ipAddress,
        ];

        if ($email && strlen($email)) $data['email'] = $email;
        if ($webUserId && !is_null($webUserId)) $data['webuser_id'] = $webUserId;
        if ($extraData && is_array($extraData) && count($extraData)) $data['extra_data'] = $extraData;
        return self::create($data);
    }
}