<?php

namespace Core\App\Controllers;

use Core\App\Models\PageviewsModel;

class PageViewController
{
    public static function track(): void
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }

        $url = (string)($_SERVER['REQUEST_URI'] ?? '/');
        if ($url === '') {
            $url = '/';
        }

        $path = parse_url($url, PHP_URL_PATH) ?: '/';
        if (!preg_match('~^/product/([^/?#]+)(?:/)?$~', $path)) {
            return;
        }

        $sessionId = session_id();
        $ip = (string)($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0');
        $agent = (string)($_SERVER['HTTP_USER_AGENT'] ?? 'unknown');

        $model = new PageviewsModel();
        $model->addPageview($sessionId, $ip, $agent, $path);
    }
}
