<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class VisitorHit extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'album_id', 'photo_id', 'user_id', 'view_style', 'hit_at', 'ip_address', 'user_agent', 'session_identifier', 'uri'
    ];

    public static function fromRequest(Request $request, $albumID = null, $photoID = null, $viewStyle = null)
    {
        $hit = new VisitorHit();
        $hit->album_id = $albumID;
        $hit->photo_id = $photoID;
        $hit->view_style = $viewStyle;
        $hit->hit_at = new \DateTime();
        $hit->uri = $request->getRequestUri();
        $hit->ip_address = substr($request->getClientIp(), 0, 255);
        $hit->user_agent = substr($request->headers->get('User-Agent'), 0, 255);
        $hit->session_identifier = $request->getSession()->getId();

        if (!is_null(Auth::user()))
        {
            $hit->user_id = Auth::user()->id;
        }

        $hit->save();
        return $hit;
    }
}