<?php

namespace AleshaCMS\Models;

use Illuminate\Database\Eloquent\Model;

class ViewLog extends Model
{
    public $timestamps = false;

    protected $fillable = ['post_id', 'date', 'ip_hash', 'referrer'];

    protected $casts = ['date' => 'date'];

    public static function record(?\AleshaCMS\Models\Post $post, \Illuminate\Http\Request $request): void
    {
        $ua = strtolower($request->userAgent() ?? '');
        if (preg_match('/bot|crawl|spider|slurp|mediapartners|facebookexternalhit/i', $ua)) {
            return;
        }

        $sessionKey = 'vl_' . ($post?->id ?? '0') . '_' . now()->toDateString();
        if (session()->has($sessionKey)) {
            return;
        }
        session()->put($sessionKey, true);

        static::create([
            'post_id'  => $post?->id,
            'date'     => now()->toDateString(),
            'ip_hash'  => hash('sha256', $request->ip() . $request->userAgent()),
            'referrer' => self::cleanReferrer($request->header('referer')),
        ]);
    }

    private static function cleanReferrer(?string $ref): ?string
    {
        if (!$ref) return null;
        $host = parse_url($ref, PHP_URL_HOST);
        return $host ?: null;
    }
}
