<?php
require_once __DIR__ . '/BaseModel.php';

class AuditLog extends BaseModel {
    protected $table = 'audit_logs';

    public function log($action, $targetType, $targetId = null, $details = null) {
        $data = [
            'admin_id' => $_SESSION['admin_id'] ?? null,
            'action' => $action,
            'target_type' => $targetType,
            'target_id' => $targetId,
            'details' => is_array($details) ? json_encode($details) : $details,
            'ip_address' => $_SERVER['REMOTE_ADDR'] ?? null
        ];
        return $this->insert($data);
    }

    public function getLatest($limit = 100) {
        $stmt = $this->db->prepare("
            SELECT al.*, a.name as admin_name 
            FROM {$this->table} al
            LEFT JOIN admins a ON al.admin_id = a.id
            ORDER BY al.created_at DESC LIMIT ?
        ");
        $stmt->bindValue(1, (int)$limit, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }
}
