<?php
/**
 * SalonPro X - Activity Logging Middleware
 * Logs all user activity on every request
 */

namespace middleware;

use core\Middleware;
use core\Request;
use core\Auth;
use core\Session;

class ActivityMiddleware extends Middleware
{
    private array $excludedPaths = [
        '/login',
        '/logout',
        '/api/dashboard/stats',
        '/api/dashboard/revenue-chart',
        '/api/dashboard/appointments-today',
    ];

    private array $excludedPatterns = [
        '#^/api/#',
        '#^/assets/#',
        '#^/uploads/#',
    ];

    public function handle(Request $request): void
    {
        $url = $request->url();

        // Skip for excluded paths
        if (in_array($url, $this->excludedPaths)) {
            return;
        }

        foreach ($this->excludedPatterns as $pattern) {
            if (preg_match($pattern, $url)) {
                return;
            }
        }

        // Update session activity time
        Session::updateActivity();

        // Check for session expiry
        if (Auth::check() && Session::isExpired()) {
            Auth::logout();
            Session::setAlert('warning', 'Your session has expired. Please login again.');
            $response = new \core\Response();
            $response->redirect(url('login'));
            exit;
        }

        // Log page views for authenticated users
        if (Auth::check() && $request->isGet()) {
            Auth::logActivity('page_view', 'Viewed: ' . $url);
        }
    }
}
