<?php
// app/Models/ActivityLog.php
// سجل نشاطات المدير (تدقيق)

class ActivityLog {

    public static function record(?int $adminId, string $action, string $entity = '', ?int $entityId = null, string $details = ''): void {
        $s = db()->prepare(
            'INSERT INTO activity_logs (admin_id, action, entity, entity_id, details, ip)
             VALUES (?,?,?,?,?,?)'
        );
        $s->execute([
            $adminId,
            $action,
            $entity ?: null,
            $entityId,
            $details ?: null,
            $_SERVER['REMOTE_ADDR'] ?? null,
        ]);
    }

    public static function recent(int $limit = 50): array {
        $limit = max(1, min($limit, 500));
        $s = db()->prepare(
            'SELECT l.*, u.name AS admin_name
             FROM activity_logs l
             LEFT JOIN users u ON u.id = l.admin_id
             ORDER BY l.created_at DESC
             LIMIT '.$limit
        );
        $s->execute();
        return $s->fetchAll();
    }

    public static function clearOlderThan(int $days = 90): int {
        $s = db()->prepare('DELETE FROM activity_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL ? DAY)');
        $s->execute([$days]);
        return $s->rowCount();
    }
}
