<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\SecurityLogModel;
use CodeIgniter\HTTP\ResponseInterface;

class SecurityLogs extends BaseController
{
    protected $securityLogModel;

    public function __construct()
    {
        $this->securityLogModel = new SecurityLogModel();
    }

    /**
     * Display the security logs
     *
     * @return string
     */
    public function index()
    {
        // Check user role for access control - only superadmin can view security logs
        $role = session()->get('role');
        if (!$role || $role !== 'superadmin') {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Access denied');
        }

        // Get filter parameters
        $severity = $this->request->getGet('severity');
        $eventType = $this->request->getGet('event_type');
        $search = $this->request->getGet('search');
        $page = $this->request->getGet('page') ?? 1;

        // Get logs with pagination
        $perPage = 20;
        
        // Apply filters
        if ($severity) {
            $this->securityLogModel->where('severity', $severity);
        }
        
        if ($eventType) {
            $this->securityLogModel->where('event_type', $eventType);
        }
        
        if ($search) {
            $this->securityLogModel->groupStart()
                    ->like('description', $search)
                    ->orLike('ip_address', $search)
                    ->groupEnd();
        }
        
        // Order by created_at descending
        $this->securityLogModel->orderBy('created_at', 'DESC');
        
        // Get paginated results
        $logs = $this->securityLogModel->paginate($perPage, 'default', $page);
        $pager = $this->securityLogModel->pager;

        // Get unique event types for filter dropdown
        $eventTypes = $this->securityLogModel->distinct()->select('event_type')->findAll();
        $eventTypes = array_column($eventTypes, 'event_type');

        return view('security/logs', [
            'logs' => $logs,
            'pager' => $pager,
            'severity' => $severity,
            'event_type' => $eventType,
            'search' => $search,
            'event_types' => $eventTypes,
            'title' => 'Security Logs'
        ]);
    }
}