<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Helpers\Auth;
use App\Models\AuditLog;

class AuditController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        Auth::requireLogin();
    }

    public function index()
    {
        $page = isset($_GET['page']) ? $_GET['page'] : 1;
        $action = isset($_GET['action']) ? $_GET['action'] : '';

        $auditModel = new AuditLog();

        if ($action) {
            $stmt = $this->db->prepare("SELECT a.*, u.name as user_name FROM audit_logs a LEFT JOIN users u ON a.user_id = u.id WHERE a.action LIKE ? ORDER BY a.created_at DESC");
            $stmt->execute(array("%$action%"));
            $logs = $stmt->fetchAll(\PDO::FETCH_OBJ);
            $total = count($logs);
            $lastPage = 1;
        } else {
            $result = $auditModel->paginate((int)$page, 15);
            $logs = $result->data;
            $total = $result->total;
            $lastPage = $result->lastPage;
        }

        $this->view('audit/index', array(
            'logs' => $logs,
            'total' => $total,
            'page' => (int)$page,
            'lastPage' => $lastPage,
            'action' => $action,
        ));
    }
}
