<?php
App::uses('Component', 'Controller');

class ReportMonitorComponent extends Component {

    public function start($controller) {

        // Start time
        $controller->reportStartTime = microtime(true);

        // Safe user identification
        $userId = (!empty($controller->Auth) && $controller->Auth->user('id'))
            ? $controller->Auth->user('id')
            : 'guest';

        $ip  = $controller->request->clientIp();
        $url = $controller->request->params['controller'] . '/' .
               $controller->request->params['action'];

        // Count requests per minute (log only)
        $key   = 'report_hits_' . $userId;
        $count = Cache::read($key, 'report_counter');
        $count = $count ? $count + 1 : 1;

        Cache::write($key, $count, 'report_counter');

        // Log rapid access (no blocking)
        if ($count > 3) {
            CakeLog::write('report', json_encode(array(
                'type'     => 'rapid_requests',
                'user_id'  => $userId,
                'ip'       => $ip,
                'url'      => $url,
                'count_1m' => $count
            )));
        }
    }

    public function end($controller) {

        $execTime = microtime(true) - $controller->reportStartTime;

        $userId = (!empty($controller->Auth) && $controller->Auth->user('id'))
            ? $controller->Auth->user('id')
            : 'guest';

        $ip  = $controller->request->clientIp();
        $url = $controller->request->params['controller'] . '/' .
               $controller->request->params['action'];

        // Log every report hit
        CakeLog::write('report', json_encode(array(
            'type'     => 'hit',
            'user_id'  => $userId,
            'ip'       => $ip,
            'url'      => $url,
            'time_sec' => round($execTime, 2)
        )));

        // Log slow reports
        if ($execTime > 20) {
            CakeLog::write('report', json_encode(array(
                'type'     => 'slow_request',
                'user_id'  => $userId,
                'ip'       => $ip,
                'url'      => $url,
                'time_sec' => round($execTime, 2)
            )));
        }
    }
}
